<script setup lang="ts">
import type { DataTableColumns } from 'naive-ui'
import { NButton, NDataTable, NForm, NFormItem, NInput, NModal, NPopconfirm, NSpace, useMessage } from 'naive-ui'
import { h, ref, watch } from 'vue'
import { addOrUpdateDictionaryUIType, deleteDictionaryItem, getDictionaryListUITypeByDicID } from '@/service/api/dictionary'

const props = defineProps<{
  visible: boolean
  dictionaryId: number
}>()

const emit = defineEmits<{
  (e: 'update:visible', visible: boolean): void
}>()

const loading = ref(false)
const tableData = ref<any[]>([])
const message = useMessage()

// Modal control for Add/Edit UI Type
const showEditModal = ref(false)
const modalTitle = ref('新增字典类型')
const formRef = ref()
const formData = ref<Api.Dictionary.AddOrUpdateDictionaryUITypeParams>({
  id: 0,
  uI_Key: '',
  uI_Value: '',
  bakValue: '',
  dictionaryID: 0,
})

const rules = {
  uI_Key: { required: true, message: '请输入键', trigger: 'blur' },
  uI_Value: { required: true, message: '请输入值', trigger: 'blur' },
}

async function fetchData() {
  if (!props.dictionaryId)
    return
  loading.value = true
  try {
    const { data: res, error } = await getDictionaryListUITypeByDicID(props.dictionaryId)
    if (!error && res) {
      tableData.value = res.data || []
    }
  }
  catch (error) {
    console.error(error)
  }
  finally {
    loading.value = false
  }
}

watch(() => props.visible, (val) => {
  if (val) {
    fetchData()
  }
})

const columns: DataTableColumns<any> = [
  { title: 'ID', key: 'ID', width: 80 },
  { title: '键 (Key)', key: 'UI_Key' },
  { title: '值 (Value)', key: 'UI_Value', width: 100 },
  { title: '备注', key: 'BakValue' },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    render(row) {
      return h(NSpace, null, {
        default: () => [
          h(NButton, { size: 'small', type: 'primary', onClick: () => handleEdit(row) }, { default: () => '编辑' }),
          h(
            NPopconfirm,
            { onPositiveClick: () => handleDelete(row) },
            {
              default: () => '确认删除？',
              trigger: () => h(NButton, { size: 'small', type: 'error' }, { default: () => '删除' }),
            },
          ),
        ],
      })
    },
  },
]

function handleAdd() {
  modalTitle.value = '新增字典类型'
  formData.value = {
    id: 0,
    uI_Key: '',
    uI_Value: '',
    bakValue: '',
    dictionaryID: props.dictionaryId,
  }
  showEditModal.value = true
}

function handleEdit(row: any) {
  modalTitle.value = '编辑字典类型'
  const { BakValue, ID, UI_Key, UI_Value } = row
  formData.value = { ...row, bakValue: BakValue, id: ID, uI_Key: UI_Key, uI_Value: UI_Value, dictionaryID: props.dictionaryId }
  showEditModal.value = true
}

async function handleDelete(row: any) {
  try {
    const { error } = await deleteDictionaryItem(row.ID)
    if (!error) {
      message.success('删除成功')
      fetchData()
    }
  }
  catch (e) {
    console.error(e)
  }
}

function handleSubmit() {
  formRef.value?.validate(async (errors: any) => {
    if (!errors) {
      try {
        const { error } = await addOrUpdateDictionaryUIType(formData.value)
        if (!error) {
          message.success('操作成功')
          showEditModal.value = false
          fetchData()
        }
      }
      catch (e) {
        console.error(e)
      }
    }
  })
}

function handleClose() {
  emit('update:visible', false)
}
</script>

<template>
  <NModal :show="visible" preset="card" title="字典类型管理" class="w-[800px]" @update:show="handleClose">
    <div class="mb-4">
      <NButton type="primary" @click="handleAdd">
        新增类型
      </NButton>
    </div>
    <NDataTable :columns="columns" :data="tableData" :loading="loading" bordered :row-key="(row) => row.id" />

    <NModal v-model:show="showEditModal" :title="modalTitle" preset="card" class="w-[500px]">
      <NForm ref="formRef" :model="formData" :rules="rules" label-placement="left" label-width="80">
        <NFormItem label="键" path="uI_Key">
          <NInput v-model:value="formData.uI_Key" placeholder="请输入键" />
        </NFormItem>
        <NFormItem label="值" path="uI_Value">
          <NInput v-model:value="formData.uI_Value" placeholder="请输入值" />
        </NFormItem>
        <NFormItem label="备注" path="bakValue">
          <NInput v-model:value="formData.bakValue" placeholder="请输入备注" />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace justify="end">
          <NButton @click="showEditModal = false">
            取消
          </NButton>
          <NButton type="primary" @click="handleSubmit">
            确定
          </NButton>
        </NSpace>
      </template>
    </NModal>
  </NModal>
</template>
