<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" class="el-col2">
        <ElButton v-ripple @click="handleSearch">搜索</ElButton>
        <ElButton v-ripple @click="showDialog('add')">新增角色</ElButton>
      </ElCol>
    </ElRow>

    <ArtTable :data="filteredData" index>
      <template #default>
        <ElTableColumn label="角色名称" prop="roleName" />
        <ElTableColumn label="角色编码" prop="roleCode" />
        <ElTableColumn label="能力边界" prop="abilities">
          <template #default="scope">
            <ElTag
              v-for="(ability, index) in scope.row.abilities"
              :key="index"
              size="small"
              style="margin-right: 4px"
            >
              {{ ability }}
            </ElTag>
          </template>
        </ElTableColumn>
        <ElTableColumn label="描述" prop="description" show-overflow-tooltip />
        <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="180">
          <template #default="scope">
            <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="600px"
      align-center
    >
      <ElForm ref="formRef" :model="form" :rules="rules" label-width="120px">
        <ElFormItem label="角色名称" prop="roleName">
          <ElInput v-model="form.roleName" placeholder="请输入角色名称" />
        </ElFormItem>
        <ElFormItem label="角色编码" prop="roleCode">
          <ElInput v-model="form.roleCode" placeholder="请输入角色编码" />
        </ElFormItem>
        <ElFormItem label="能力边界" prop="abilities">
          <ElCheckboxGroup v-model="form.abilities">
            <ElCheckbox label="查看网卡">查看网卡</ElCheckbox>
            <ElCheckbox label="操作网卡">操作网卡</ElCheckbox>
            <ElCheckbox label="查看套餐">查看套餐</ElCheckbox>
            <ElCheckbox label="购买套餐">购买套餐</ElCheckbox>
            <ElCheckbox label="查看设备">查看设备</ElCheckbox>
            <ElCheckbox label="管理设备">管理设备</ElCheckbox>
            <ElCheckbox label="查看佣金">查看佣金</ElCheckbox>
            <ElCheckbox label="提现佣金">提现佣金</ElCheckbox>
          </ElCheckboxGroup>
        </ElFormItem>
        <ElFormItem label="描述" prop="description">
          <ElInput
            v-model="form.description"
            type="textarea"
            :rows="3"
            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>
  </div>
</template>

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

  defineOptions({ name: 'CustomerRole' })

  interface CustomerRole {
    id?: string
    roleName: string
    roleCode: string
    abilities: string[]
    description: string
    status: 'active' | 'inactive'
    createTime?: string
  }

  // Mock 数据
  const mockData = ref<CustomerRole[]>([
    {
      id: '1',
      roleName: '标准客户',
      roleCode: 'CUSTOMER_STANDARD',
      abilities: ['查看网卡', '查看套餐', '查看设备'],
      description: '标准客户角色，拥有基本查看权限',
      status: 'active',
      createTime: '2026-01-01 10:00:00'
    },
    {
      id: '2',
      roleName: 'VIP客户',
      roleCode: 'CUSTOMER_VIP',
      abilities: ['查看网卡', '操作网卡', '查看套餐', '购买套餐', '查看设备', '管理设备'],
      description: 'VIP客户角色，拥有更多操作权限',
      status: 'active',
      createTime: '2026-01-02 11:00:00'
    },
    {
      id: '3',
      roleName: '企业客户',
      roleCode: 'CUSTOMER_ENTERPRISE',
      abilities: [
        '查看网卡',
        '操作网卡',
        '查看套餐',
        '购买套餐',
        '查看设备',
        '管理设备',
        '查看佣金'
      ],
      description: '企业客户角色，拥有完整业务权限',
      status: 'active',
      createTime: '2026-01-03 12:00:00'
    }
  ])

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

  const form = reactive<CustomerRole>({
    roleName: '',
    roleCode: '',
    abilities: [],
    description: '',
    status: 'active'
  })

  const rules = reactive<FormRules>({
    roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
    roleCode: [{ required: true, message: '请输入角色编码', trigger: 'blur' }],
    abilities: [{ required: true, message: '请至少选择一项能力', trigger: 'change' }]
  })

  const filteredData = computed(() => {
    if (!searchQuery.value) return mockData.value
    return mockData.value.filter((item) =>
      item.roleName.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  })

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

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

    if (type === 'edit' && row) {
      form.id = row.id
      form.roleName = row.roleName
      form.roleCode = row.roleCode
      form.abilities = [...row.abilities]
      form.description = row.description
      form.status = row.status
    } else {
      resetForm()
    }
  }

  const resetForm = () => {
    form.id = undefined
    form.roleName = ''
    form.roleCode = ''
    form.abilities = []
    form.description = ''
    form.status = 'active'
  }

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

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

  const handleDelete = (row: CustomerRole) => {
    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('删除成功')
    })
  }
</script>

<style lang="scss" scoped>
  .page-content {
    :deep(.el-checkbox) {
      margin-right: 20px;
      margin-bottom: 10px;
    }
  }
</style>
