<template>
  <a-modal
    :open="visible"
    :title="isEdit ? '编辑字典' : '新增字典'"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :confirm-loading="submitLoading"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
    >
      <a-form-item label="字典名称" name="name">
        <a-input v-model:value="formData.name" placeholder="请输入字典名称" />
      </a-form-item>
      <a-form-item label="字典编码" name="code">
        <a-input v-model:value="formData.code" placeholder="请输入字典编码" :disabled="isEdit" />
      </a-form-item>
      <a-form-item label="备注" name="remark">
        <a-textarea v-model:value="formData.remark" placeholder="请输入备注" :rows="3" />
      </a-form-item>
      <a-form-item label="状态" name="status">
        <a-radio-group v-model:value="formData.status">
          <a-radio :value="1">正常</a-radio>
          <a-radio :value="0">禁用</a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'

// 字典类型定义
interface DictRecord {
  id?: number
  name: string
  code: string
  remark?: string
  status: number
}

const props = defineProps<{
  visible: boolean
  editData?: DictRecord | null
}>()

const emit = defineEmits(['update:visible', 'success'])

const isEdit = ref(false)
const submitLoading = ref(false)
const formRef = ref<FormInstance>()

const formData = reactive<DictRecord>({
  id: undefined,
  name: '',
  code: '',
  remark: '',
  status: 1
})

const formRules = {
  name: [{ required: true, message: '请输入字典名称' }],
  code: [{ required: true, message: '请输入字典编码' }]
}

// 监听 editData 变化，初始化表单
watch(
  () => props.editData,
  (val) => {
    if (val) {
      isEdit.value = true
      formData.id = val.id
      formData.name = val.name
      formData.code = val.code
      formData.remark = val.remark || ''
      formData.status = val.status
    } else {
      isEdit.value = false
      formData.id = undefined
      formData.name = ''
      formData.code = ''
      formData.remark = ''
      formData.status = 1
    }
  },
  { immediate: true }
)

// 监听 visible，重置表单
watch(
  () => props.visible,
  (val) => {
    if (val && !props.editData) {
      formRef.value?.resetFields()
    }
  }
)

function handleCancel() {
  emit('update:visible', false)
}

async function handleSubmit() {
  try {
    await formRef.value?.validate()
    submitLoading.value = true

    // TODO: 接入真实API
    // if (isEdit.value) {
    //   await updateDict(formData)
    // } else {
    //   await createDict(formData)
    // }

    message.success(isEdit.value ? '编辑成功' : '新增成功')
    emit('update:visible', false)
    emit('success')
  } catch (error) {
    // 验证失败
  } finally {
    submitLoading.value = false
  }
}
</script>
