<script setup lang="tsx">
import type { DataTableColumns } from 'naive-ui'
import { NButton, NDataTable, NForm, NFormItem, NInput, NModal, NPopconfirm, NSpace, useMessage } from 'naive-ui'
import { onMounted, ref } from 'vue'
import { addOrUpdateDictionary, deleteDictionary, getDictionaryList } from '@/service/api/dictionary'
import DictionaryTypeModal from './modules/DictionaryTypeModal.vue'

// 表格数据
const loading = ref(false)
const tableData = ref<Api.Dictionary.DictionaryItem[]>([])

// 字典类型模态框
const showTypeModal = ref(false)
const currentDictionaryId = ref(0)

function handleOpenTypeModal(row: Api.Dictionary.DictionaryItem) {
  currentDictionaryId.value = row.Id
  showTypeModal.value = true
}

// 模态框控制
const showModal = ref(false)
const modalTitle = ref('新增字典')
const formRef = ref()
const formData = ref<Api.Dictionary.AddOrUpdateParams>({
  Id: 0,
  DicKey: '',
  DicValue: '',
  bakValue: '',
})

// 表单验证规则
const rules = {
  dicKey: { required: true, message: '请输入字典键', trigger: 'blur' },
  dicValue: { required: true, message: '请输入字典值', trigger: 'blur' },
}

const message = useMessage()

// 获取列表数据
async function fetchData() {
  loading.value = true
  try {
    const { data: res, error } = await getDictionaryList()

    if (!error && res) {
      tableData.value = res.data || []
    }
  }
  catch (error) {
    console.error(error)
  }
  finally {
    loading.value = false
  }
}

// 列定义
const columns: DataTableColumns<Api.Dictionary.DictionaryItem> = [
  { title: 'ID', key: 'Id' },
  {
    title: '字典键 (Key)',
    key: 'DicKey',
    render(row) {
      return (
        <NButton text type="primary" onClick={() => handleOpenTypeModal(row)}>
          {row.DicKey}
        </NButton>
      )
    },
  },
  { title: '字典值 (Value)', key: 'DicValue' },
  { title: '备注/备份值', key: 'BakValue' },
  {
    title: '操作',
    key: 'actions',
    render(row) {
      return (
        <NSpace>
          <NButton size="small" type="primary" onClick={() => handleEdit(row)}>
            编辑
          </NButton>
          <NPopconfirm
            onPositiveClick={() => handleDelete(row)}
            v-slots={{
              default: () => '确认删除该条数据吗？',
              trigger: () => (
                <NButton size="small" type="error">
                  删除
                </NButton>
              ),
            }}
          />
        </NSpace>
      )
    },
  },
]

// 新增
function handleAdd() {
  modalTitle.value = '新增字典'
  formData.value = {
    Id: 0,
    DicKey: '',
    DicValue: '',
    bakValue: '',
  }
  showModal.value = true
}

// 编辑
function handleEdit(row: Api.Dictionary.DictionaryItem) {
  modalTitle.value = '编辑字典'
  formData.value = { ...row }
  showModal.value = true
}

// 删除
async function handleDelete(row: Api.Dictionary.DictionaryItem) {
  try {
    await deleteDictionary(row.Id)
    message.success('删除成功')
    fetchData()
  }
  catch (error) {
    console.error(error)
  }
}

// 提交表单
function handleSubmit() {
  formRef.value?.validate(async (errors: any) => {
    if (!errors) {
      try {
        await addOrUpdateDictionary(formData.value)
        message.success(formData.value.Id ? '更新成功' : '新增成功')
        showModal.value = false
        fetchData()
      }
      catch (error) {
        console.error(error)
      }
    }
  })
}

onMounted(() => {
  fetchData()
})
</script>

<template>
  <div class="h-full p-4">
    <NCard title="字典列表" :bordered="false" page-size="small" class="card-wrapper sm:flex-1-hidden">
      <template #header-extra>
        <NButton type="primary" @click="handleAdd">
          新增字典
        </NButton>
      </template>

      <NDataTable
        :columns="columns" :data="tableData" :loading="loading" :pagination="false"
        :row-key="(row) => row.id" bordered
        max-height="100%"
      />
    </NCard>
    <DictionaryTypeModal
      v-model:visible="showTypeModal"
      :dictionary-id="currentDictionaryId"
    />

    <NModal v-model:show="showModal" :title="modalTitle" preset="card" class="w-[600px]">
      <NForm
        ref="formRef" :model="formData" :rules="rules" label-placement="left" label-width="100"
        require-mark-placement="right-hanging"
      >
        <NFormItem label="字典名称" path="DicKey">
          <NInput v-model:value="formData.DicKey" placeholder="请输入字典名称" />
        </NFormItem>
        <NFormItem label="字典类型" path="DicValue">
          <NInput v-model:value="formData.DicValue" placeholder="请输入字典值" type="textarea" />
        </NFormItem>
        <NFormItem label="备注" path="bakValue">
          <NInput v-model:value="formData.bakValue" placeholder="请输入备注或备份值" />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace justify="end">
          <NButton @click="showModal = false">
            取消
          </NButton>
          <NButton type="primary" @click="handleSubmit">
            确定
          </NButton>
        </NSpace>
      </template>
    </NModal>
  </div>
</template>

<style scoped></style>
