<template>
  <div class="dict-page">
    <a-card class="mb-4">
      <template #title>数据字典</template>
      <template #extra>
        <a-button v-permission="'dict:create'" 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-permission="'dict:update'" type="link" size="small" @click="handleEdit(record)">
              编辑
            </a-button>
            <a-button v-permission.hide="'dict:delete'" type="link" size="small" danger @click="handleDelete(record)">
              删除
            </a-button>
          </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_status）" :maxlength="50"
            :disabled="!!editingId" />
        </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 } from 'vue'
import { message, Modal } from 'ant-design-vue'
import type { TableColumnsType, FormInstance } from 'ant-design-vue'
import { dictApi, type Dict, type CreateDictForm, type UpdateDictForm } from '@/api/dict'
import { useListRequest } from '@/composables/useListRequest'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()

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<Dict>({
  requestFn: dictApi.getList,
  errorMessage: '获取字典列表失败',
})

const form = reactive<CreateDictForm>({
  name: '',
  code: '',
  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' },
  ],
  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: 'description', key: 'description' },
  { title: '操作', key: 'action', width: 150, fixed: 'right' },
]

// 新增字典
const handleAdd = () => {
  // 权限检查
  if (!authStore.hasPermission('dict:create')) {
    message.error('您没有创建字典的权限')
    return
  }

  modalTitle.value = '新增字典'
  editingId.value = null
  modalVisible.value = true
  nextTick(() => {
    formRef.value?.resetFields()
    form.name = ''
    form.code = ''
    form.description = ''
  })
}

// 编辑字典
const handleEdit = async (record: Dict) => {
  modalTitle.value = '编辑字典'
  editingId.value = record.id
  modalVisible.value = true
  detailLoading.value = true

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

// 删除字典
const handleDelete = (record: Dict) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除字典 "${record.name}" 吗？删除后无法恢复。`,
    okText: '确定',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      try {
        await dictApi.delete(record.id)
        message.success('删除成功')
        refreshList()
      } catch (error: any) {
        const errorMessage = error?.response?.data?.message || '删除失败'
        message.error(errorMessage)
      }
    },
  })
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitLoading.value = true

    if (editingId.value) {
      // 编辑
      await dictApi.update(editingId.value, form)
      message.success('编辑成功')
    } else {
      // 新增
      await dictApi.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 lang="scss">
.dict-page {
  // 数据字典页面样式
}
</style>
