<template>
  <div class="permissions-page">
    <a-card class="mb-4">
      <template #title>权限管理</template>
      <template #extra>
        <a-button v-if="isSuperAdmin" type="primary" @click="handleAdd">新增权限</a-button>
      </template>
    </a-card>
    <a-table :columns="columns" :data-source="dataSource" :loading="loading" :pagination="pagination"
      @change="handleTableChange">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'description'">
          <span>{{ record.description || '-' }}</span>
        </template>
        <template v-if="column.key === 'action'">
          <a-space>
            <a-button v-if="isSuperAdmin" type="link" size="small" @click="handleEdit(record)">
              编辑
            </a-button>
            <a-button v-if="isSuperAdmin" type="link" size="small" danger @click="handleDelete(record)">
              删除
            </a-button>
            <span v-if="!isSuperAdmin" class="text-gray-400">仅超级管理员可编辑</span>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 新增/编辑权限弹窗 -->
    <a-modal v-model:open="modalVisible" :title="modalTitle" :confirm-loading="submitLoading" @ok="handleSubmit"
      @cancel="handleCancel" width="600px" :loading="detailLoading">
      <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="权限名称" name="name">
          <a-input v-model:value="form.name" placeholder="请输入权限名称" :maxlength="50" />
        </a-form-item>
        <a-form-item label="权限编码" name="code">
          <a-input v-model:value="form.code" placeholder="请输入权限编码（如：user:create）" :maxlength="50" />
        </a-form-item>
        <a-form-item label="资源名称" name="resource">
          <a-input v-model:value="form.resource" placeholder="请输入资源名称（如：user）" :maxlength="50" />
        </a-form-item>
        <a-form-item label="操作类型" name="action">
          <a-select v-model:value="form.action" placeholder="请选择操作类型">
            <a-select-option value="create">创建</a-select-option>
            <a-select-option value="read">查看</a-select-option>
            <a-select-option value="update">更新</a-select-option>
            <a-select-option value="delete">删除</a-select-option>
            <a-select-option value="assign">分配</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="权限描述" name="description">
          <a-textarea v-model:value="form.description" placeholder="请输入权限描述" :rows="4" :maxlength="200" show-count />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, computed } from 'vue'
import { message, Modal } from 'ant-design-vue'
import type { TableColumnsType, FormInstance } from 'ant-design-vue'
import { permissionsApi, type Permission, type CreatePermissionForm } from '@/api/permissions'
import { useListRequest } from '@/composables/useListRequest'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()

// 检查是否为超级管理员
const isSuperAdmin = computed(() => {
  return authStore.hasRole('super_admin')
})

const submitLoading = ref(false)
const detailLoading = ref(false)
const modalVisible = ref(false)
const modalTitle = ref('新增权限')
const formRef = ref<FormInstance>()
const editingId = ref<number | null>(null)

// 使用列表请求组合函数
const {
  loading,
  dataSource,
  pagination,
  handleTableChange,
  refresh: refreshList,
} = useListRequest<Permission>({
  requestFn: permissionsApi.getList,
  errorMessage: '获取权限列表失败',
})

const form = reactive<CreatePermissionForm>({
  name: '',
  code: '',
  resource: '',
  action: '',
  description: '',
})

const rules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { max: 50, message: '权限名称不能超过50个字符', trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z][a-zA-Z0-9:_]*$/,
      message: '权限编码只能包含字母、数字、冒号和下划线，且必须以字母开头',
      trigger: 'blur'
    },
    { max: 50, message: '权限编码不能超过50个字符', trigger: 'blur' },
  ],
  resource: [
    { required: true, message: '请输入资源名称', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/,
      message: '资源名称只能包含字母、数字和下划线，且必须以字母开头',
      trigger: 'blur'
    },
    { max: 50, message: '资源名称不能超过50个字符', trigger: 'blur' },
  ],
  action: [
    { required: true, message: '请选择操作类型', trigger: 'change' },
  ],
  description: [
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' },
  ],
}

const columns: TableColumnsType = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '权限名称', dataIndex: 'name', key: 'name' },
  { title: '权限编码', dataIndex: 'code', key: 'code' },
  { title: '资源', dataIndex: 'resource', key: 'resource' },
  { title: '描述', dataIndex: 'description', key: 'description' },
  { title: '操作', key: 'action', width: 200, fixed: 'right' },
]


// 新增权限
const handleAdd = () => {
  if (!isSuperAdmin.value) {
    message.warning('只有超级管理员才能新增权限')
    return
  }
  modalTitle.value = '新增权限'
  editingId.value = null
  modalVisible.value = true
  // 清除表单验证状态
  nextTick(() => {
    formRef.value?.resetFields()
    form.name = ''
    form.code = ''
    form.resource = ''
    form.action = ''
    form.description = ''
  })
}

// 编辑权限
const handleEdit = async (record: Permission) => {
  if (!isSuperAdmin.value) {
    message.warning('只有超级管理员才能编辑权限')
    return
  }
  modalTitle.value = '编辑权限'
  editingId.value = record.id
  modalVisible.value = true
  detailLoading.value = true

  try {
    const detail = await permissionsApi.getDetail(record.id)
    form.name = detail.name
    form.code = detail.code
    form.resource = detail.resource
    form.action = detail.action
    form.description = detail.description || ''
  } catch (error) {
    message.error('获取权限详情失败')
    modalVisible.value = false
  } finally {
    detailLoading.value = false
  }
}

// 删除权限
const handleDelete = (record: Permission) => {
  if (!isSuperAdmin.value) {
    message.warning('只有超级管理员才能删除权限')
    return
  }
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除权限 "${record.name}" 吗？删除后无法恢复。`,
    okText: '确定',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      try {
        await permissionsApi.delete(record.id)
        message.success('删除成功')
        refreshList()
      } catch (error: any) {
        const errorMessage = error?.response?.data?.message || '删除失败'
        message.error(errorMessage)
      }
    },
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!isSuperAdmin.value) {
    message.warning('只有超级管理员才能操作权限')
    return
  }
  try {
    await formRef.value?.validate()
    submitLoading.value = true

    if (editingId.value) {
      // 编辑
      await permissionsApi.update(editingId.value, form)
      message.success('编辑成功')
    } else {
      // 新增
      await permissionsApi.create(form)
      message.success('新增成功')
    }

    modalVisible.value = false
    refreshList()
  } catch (error: any) {
    if (error?.errorFields) {
      // 表单验证错误
      return
    }
    const errorMessage = error?.response?.data?.message || (editingId.value ? '编辑失败' : '新增失败')
    message.error(errorMessage)
  } finally {
    submitLoading.value = false
  }
}

// 取消表单
const handleCancel = () => {
  modalVisible.value = false
  formRef.value?.resetFields()
}

</script>

<style scoped>
.text-gray-400 {
  color: #9ca3af;
  font-size: 12px;
}
</style>
