<template>
  <div class="page-content">
    <ElRow>
      <ElCol :xs="24" :sm="12" :lg="6">
        <ElInput v-model="searchQuery" placeholder="代理商名称/联系人" clearable></ElInput>
      </ElCol>
      <div style="width: 12px"></div>
      <ElCol :xs="24" :sm="12" :lg="6">
        <ElSelect v-model="levelFilter" placeholder="代理商等级" clearable style="width: 100%">
          <ElOption label="一级代理" value="1" />
          <ElOption label="二级代理" value="2" />
          <ElOption label="三级代理" value="3" />
        </ElSelect>
      </ElCol>
      <div style="width: 12px"></div>
      <ElCol :xs="24" :sm="12" :lg="6" class="el-col2">
        <ElButton v-ripple @click="handleSearch">搜索</ElButton>
        <ElButton v-ripple @click="showDialog('add')">新增代理商</ElButton>
      </ElCol>
    </ElRow>

    <ArtTable :data="filteredData" index row-key="id">
      <template #default>
        <ElTableColumn label="代理商名称" prop="agentName" min-width="150" />
        <ElTableColumn label="代理商编码" prop="agentCode" />
        <ElTableColumn label="等级" prop="level">
          <template #default="scope">
            <ElTag :type="getLevelTagType(scope.row.level)">
              {{ getLevelText(scope.row.level) }}
            </ElTag>
          </template>
        </ElTableColumn>
        <ElTableColumn label="上级代理" prop="parentName" show-overflow-tooltip />
        <ElTableColumn label="联系人" prop="contactPerson" />
        <ElTableColumn label="联系电话" prop="contactPhone" />
        <ElTableColumn label="账号数量" prop="accountCount" />
        <ElTableColumn label="网卡数量" prop="simCardCount" />
        <ElTableColumn label="佣金总额" prop="totalCommission">
          <template #default="scope"> ¥{{ scope.row.totalCommission.toFixed(2) }} </template>
        </ElTableColumn>
        <ElTableColumn label="状态" prop="status">
          <template #default="scope">
            <ElTag :type="scope.row.status === 'active' ? 'success' : 'info'">
              {{ scope.row.status === 'active' ? '启用' : '禁用' }}
            </ElTag>
          </template>
        </ElTableColumn>
        <ElTableColumn label="创建时间" prop="createTime" width="180" />
        <ElTableColumn fixed="right" label="操作" width="280">
          <template #default="scope">
            <el-button link @click="viewAccountList(scope.row)">账号管理</el-button>
            <el-button link @click="viewCommission(scope.row)">佣金配置</el-button>
            <el-button link @click="showDialog('edit', scope.row)">编辑</el-button>
            <el-button link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </ElTableColumn>
      </template>
    </ArtTable>

    <!-- 新增/编辑对话框 -->
    <ElDialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增代理商' : '编辑代理商'"
      width="700px"
      align-center
    >
      <ElForm ref="formRef" :model="form" :rules="rules" label-width="120px">
        <ElRow :gutter="20">
          <ElCol :span="12">
            <ElFormItem label="代理商名称" prop="agentName">
              <ElInput v-model="form.agentName" placeholder="请输入代理商名称" />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="代理商编码" prop="agentCode">
              <ElInput v-model="form.agentCode" placeholder="请输入代理商编码" />
            </ElFormItem>
          </ElCol>
        </ElRow>
        <ElRow :gutter="20">
          <ElCol :span="12">
            <ElFormItem label="代理商等级" prop="level">
              <ElSelect v-model="form.level" placeholder="请选择代理商等级" style="width: 100%">
                <ElOption label="一级代理" :value="1" />
                <ElOption label="二级代理" :value="2" />
                <ElOption label="三级代理" :value="3" />
              </ElSelect>
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="上级代理" prop="parentId">
              <ElSelect
                v-model="form.parentId"
                placeholder="请选择上级代理"
                clearable
                style="width: 100%"
              >
                <ElOption label="无" :value="undefined" />
                <ElOption
                  v-for="agent in parentAgentOptions"
                  :key="agent.id"
                  :label="agent.agentName"
                  :value="agent.id"
                />
              </ElSelect>
            </ElFormItem>
          </ElCol>
        </ElRow>
        <ElRow :gutter="20">
          <ElCol :span="12">
            <ElFormItem label="联系人" prop="contactPerson">
              <ElInput v-model="form.contactPerson" placeholder="请输入联系人" />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="联系电话" prop="contactPhone">
              <ElInput v-model="form.contactPhone" placeholder="请输入联系电话" />
            </ElFormItem>
          </ElCol>
        </ElRow>
        <ElRow :gutter="20">
          <ElCol :span="12">
            <ElFormItem label="邮箱" prop="email">
              <ElInput v-model="form.email" placeholder="请输入邮箱" />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="公司地址" prop="address">
              <ElInput v-model="form.address" placeholder="请输入公司地址" />
            </ElFormItem>
          </ElCol>
        </ElRow>
        <ElFormItem label="备注" prop="remark">
          <ElInput v-model="form.remark" type="textarea" :rows="2" placeholder="请输入备注信息" />
        </ElFormItem>
        <ElFormItem label="状态">
          <ElSwitch v-model="form.status" active-value="active" inactive-value="inactive" />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <div class="dialog-footer">
          <ElButton @click="dialogVisible = false">取消</ElButton>
          <ElButton type="primary" @click="handleSubmit(formRef)">提交</ElButton>
        </div>
      </template>
    </ElDialog>

    <!-- 账号管理对话框 -->
    <ElDialog v-model="accountDialogVisible" title="代理商账号管理" width="900px" align-center>
      <div style="margin-bottom: 16px">
        <ElButton type="primary" size="small" @click="addSubAccount">创建子账号</ElButton>
      </div>
      <ArtTable :data="currentAgentAccounts" index>
        <template #default>
          <ElTableColumn label="账号" prop="username" />
          <ElTableColumn label="真实姓名" prop="realName" />
          <ElTableColumn label="手机号" prop="phone" />
          <ElTableColumn label="角色" prop="role" />
          <ElTableColumn label="状态" prop="status">
            <template #default="scope">
              <ElTag :type="scope.row.status === 'active' ? 'success' : 'info'">
                {{ scope.row.status === 'active' ? '正常' : '禁用' }}
              </ElTag>
            </template>
          </ElTableColumn>
          <ElTableColumn label="创建时间" prop="createTime" />
          <ElTableColumn fixed="right" label="操作" width="150">
            <template #default>
              <el-button link>编辑</el-button>
              <el-button link>禁用</el-button>
            </template>
          </ElTableColumn>
        </template>
      </ArtTable>
    </ElDialog>

    <!-- 佣金配置对话框 -->
    <ElDialog v-model="commissionDialogVisible" title="佣金配置" width="600px" align-center>
      <ElForm label-width="120px">
        <ElFormItem label="佣金模式">
          <ElRadioGroup v-model="commissionForm.mode">
            <ElRadio value="fixed">固定佣金</ElRadio>
            <ElRadio value="percent">比例佣金</ElRadio>
          </ElRadioGroup>
        </ElFormItem>
        <ElFormItem v-if="commissionForm.mode === 'fixed'" label="固定金额">
          <ElInputNumber v-model="commissionForm.fixedAmount" :min="0" :precision="2" />
          <span style="margin-left: 8px">元/笔</span>
        </ElFormItem>
        <ElFormItem v-if="commissionForm.mode === 'percent'" label="佣金比例">
          <ElInputNumber v-model="commissionForm.percent" :min="0" :max="100" :precision="2" />
          <span style="margin-left: 8px">%</span>
        </ElFormItem>
        <ElFormItem label="结算周期">
          <ElSelect v-model="commissionForm.settlementCycle" style="width: 100%">
            <ElOption label="实时结算" value="realtime" />
            <ElOption label="日结" value="daily" />
            <ElOption label="周结" value="weekly" />
            <ElOption label="月结" value="monthly" />
          </ElSelect>
        </ElFormItem>
      </ElForm>
      <template #footer>
        <div class="dialog-footer">
          <ElButton @click="commissionDialogVisible = false">取消</ElButton>
          <ElButton type="primary" @click="saveCommissionConfig">保存</ElButton>
        </div>
      </template>
    </ElDialog>
  </div>
</template>

<script setup lang="ts">
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'

  defineOptions({ name: 'AgentManagement' })

  interface Agent {
    id?: string
    agentName: string
    agentCode: string
    level: number
    parentId?: string | null
    parentName?: string
    contactPerson: string
    contactPhone: string
    email?: string
    address?: string
    remark?: string
    accountCount?: number
    simCardCount?: number
    totalCommission?: number
    status: 'active' | 'inactive'
    createTime?: string
  }

  // Mock 数据
  const mockData = ref<Agent[]>([
    {
      id: '1',
      agentName: '华东区总代理',
      agentCode: 'AGENT_HD_001',
      level: 1,
      parentId: null,
      parentName: '无',
      contactPerson: '张三',
      contactPhone: '13800138001',
      email: 'zhangsan@example.com',
      address: '上海市浦东新区',
      accountCount: 5,
      simCardCount: 1000,
      totalCommission: 158900.5,
      status: 'active',
      createTime: '2026-01-01 10:00:00'
    },
    {
      id: '2',
      agentName: '江苏省代理',
      agentCode: 'AGENT_JS_001',
      level: 2,
      parentId: '1',
      parentName: '华东区总代理',
      contactPerson: '李四',
      contactPhone: '13800138002',
      email: 'lisi@example.com',
      address: '江苏省南京市',
      accountCount: 3,
      simCardCount: 500,
      totalCommission: 78500.0,
      status: 'active',
      createTime: '2026-01-05 11:00:00'
    },
    {
      id: '3',
      agentName: '南京市代理',
      agentCode: 'AGENT_NJ_001',
      level: 3,
      parentId: '2',
      parentName: '江苏省代理',
      contactPerson: '王五',
      contactPhone: '13800138003',
      email: 'wangwu@example.com',
      address: '江苏省南京市玄武区',
      accountCount: 2,
      simCardCount: 200,
      totalCommission: 32800.0,
      status: 'active',
      createTime: '2026-01-10 12:00:00'
    }
  ])

  const searchQuery = ref('')
  const levelFilter = ref('')
  const dialogVisible = ref(false)
  const accountDialogVisible = ref(false)
  const commissionDialogVisible = ref(false)
  const dialogType = ref<'add' | 'edit'>('add')
  const formRef = ref<FormInstance>()

  const form = reactive<Agent>({
    agentName: '',
    agentCode: '',
    level: 1,
    parentId: null,
    contactPerson: '',
    contactPhone: '',
    email: '',
    address: '',
    remark: '',
    status: 'active'
  })

  const commissionForm = reactive({
    mode: 'fixed',
    fixedAmount: 10,
    percent: 5,
    settlementCycle: 'monthly'
  })

  const currentAgentAccounts = ref([
    {
      username: 'agent001',
      realName: '张三',
      phone: '13800138001',
      role: '管理员',
      status: 'active',
      createTime: '2026-01-01 10:00:00'
    }
  ])

  const rules = reactive<FormRules>({
    agentName: [{ required: true, message: '请输入代理商名称', trigger: 'blur' }],
    agentCode: [{ required: true, message: '请输入代理商编码', trigger: 'blur' }],
    level: [{ required: true, message: '请选择代理商等级', trigger: 'change' }],
    contactPerson: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
    contactPhone: [
      { required: true, message: '请输入联系电话', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ]
  })

  const parentAgentOptions = computed(() => {
    return mockData.value.filter((item) => item.level < form.level)
  })

  const filteredData = computed(() => {
    let data = mockData.value
    if (searchQuery.value) {
      data = data.filter(
        (item) =>
          item.agentName.includes(searchQuery.value) ||
          item.contactPerson.includes(searchQuery.value)
      )
    }
    if (levelFilter.value) {
      data = data.filter((item) => item.level === parseInt(levelFilter.value))
    }
    return data
  })

  const getLevelText = (level: number) => {
    const levelMap: Record<number, string> = { 1: '一级代理', 2: '二级代理', 3: '三级代理' }
    return levelMap[level] || '未知'
  }

  const getLevelTagType = (level: number) => {
    const typeMap: Record<number, string> = { 1: 'primary', 2: 'success', 3: 'warning' }
    return typeMap[level] || 'info'
  }

  const handleSearch = () => {
    // 搜索逻辑已通过 computed 实现
  }

  const showDialog = (type: 'add' | 'edit', row?: Agent) => {
    dialogType.value = type
    dialogVisible.value = true

    if (type === 'edit' && row) {
      Object.assign(form, row)
    } else {
      resetForm()
    }
  }

  const resetForm = () => {
    Object.assign(form, {
      agentName: '',
      agentCode: '',
      level: 1,
      parentId: null,
      contactPerson: '',
      contactPhone: '',
      email: '',
      address: '',
      remark: '',
      status: 'active'
    })
  }

  const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return

    await formEl.validate((valid) => {
      if (valid) {
        if (dialogType.value === 'add') {
          const parentAgent = mockData.value.find((item) => item.id === form.parentId)
          mockData.value.push({
            ...form,
            id: Date.now().toString(),
            parentName: parentAgent ? parentAgent.agentName : '无',
            accountCount: 0,
            simCardCount: 0,
            totalCommission: 0,
            createTime: new Date().toLocaleString('zh-CN')
          })
          ElMessage.success('新增成功')
        } else {
          const index = mockData.value.findIndex((item) => item.id === form.id)
          if (index !== -1) {
            const parentAgent = mockData.value.find((item) => item.id === form.parentId)
            mockData.value[index] = {
              ...form,
              parentName: parentAgent ? parentAgent.agentName : '无'
            }
          }
          ElMessage.success('修改成功')
        }
        dialogVisible.value = false
        formEl.resetFields()
      }
    })
  }

  const handleDelete = (row: Agent) => {
    ElMessageBox.confirm('确定删除该代理商吗？删除后其下属代理商和账号也将被删除。', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }).then(() => {
      const index = mockData.value.findIndex((item) => item.id === row.id)
      if (index !== -1) {
        mockData.value.splice(index, 1)
      }
      ElMessage.success('删除成功')
    })
  }

  const viewAccountList = (row: Agent) => {
    accountDialogVisible.value = true
    // 实际应用中应该根据代理商ID加载账号列表
    console.log(row)
  }

  const viewCommission = (row: Agent) => {
    commissionDialogVisible.value = true
    // 实际应用中应该根据代理商ID加载佣金配置
    console.log(row)
  }

  const addSubAccount = () => {
    ElMessage.info('创建子账号功能')
  }

  const saveCommissionConfig = () => {
    ElMessage.success('佣金配置保存成功')
    commissionDialogVisible.value = false
  }
</script>

<style lang="scss" scoped>
  .page-content {
    // 自定义样式
  }
</style>
