<template>
    <el-dialog
      :title="isEditing ? '编辑字典项' : '添加字典项'"
      v-model="visible"
      width="600px"
      :close-on-click-modal="false"
      @close="handleClose"
    >
      <el-form
        :model="dictItemForm"
        :rules="formRules"
        ref="dictItemFormRef"
        label-width="100px"
      >
        <el-form-item label="字典类型" prop="dict_type_id">
          <el-select
            v-model="dictItemForm.dict_type_id"
            placeholder="请选择字典类型"
            filterable
            style="width: 100%"
            :disabled="isEditing || !!dictTypeId"
          >
            <el-option
              v-for="type in dictTypes"
              :key="type.id"
              :label="`${type.dict_name} (${type.dict_code})`"
              :value="type.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="字典标签" prop="dict_label">
          <el-input
            v-model="dictItemForm.dict_label"
            placeholder="请输入字典标签（显示值）"
          />
        </el-form-item>
        <el-form-item label="字典值" prop="dict_value">
          <el-input
            v-model="dictItemForm.dict_value"
            placeholder="请输入字典值（存储值）"
          />
        </el-form-item>
        <!-- <el-form-item label="父级ID" prop="parent_id">
          <el-input-number
            v-model="dictItemForm.parent_id"
            :min="0"
            style="width: 100%"
            placeholder="0表示顶级"
          />
          <div class="form-tip">0表示顶级字典项</div>
        </el-form-item> -->
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="dictItemForm.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序序号" prop="sort">
          <el-input-number
            v-model="dictItemForm.sort"
            :min="0"
            style="width: 100%"
            placeholder="数字越小越靠前"
          />
        </el-form-item>
        <el-form-item label="颜色标记" prop="color">
          <el-input
            v-model="dictItemForm.color"
            placeholder="请输入颜色值（如：#FF0000 或 red）"
            maxlength="20"
          />
          <div class="form-tip">用于前端显示时的颜色标记</div>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input
            v-model="dictItemForm.icon"
            placeholder="请输入图标名称或类名"
            maxlength="50"
          />
          <div class="form-tip">用于前端显示时的图标</div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="dictItemForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          保存
        </el-button>
      </template>
    </el-dialog>
  </template>
  
  <script setup lang="ts">
  import { ref, reactive, watch, computed, onMounted } from 'vue'
  import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
  import { getDictTypes, addDictItem, updateDictItem } from '@/api/dict'
  
  interface Props {
    modelValue: boolean
    dictItem?: any
    dictTypeId?: number | null
  }
  
  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    dictItem: null,
    dictTypeId: null,
  })
  
  const emit = defineEmits<{
    'update:modelValue': [value: boolean]
    success: []
  }>()
  
  const visible = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val),
  })
  
  const submitting = ref(false)
  const dictItemFormRef = ref<FormInstance>()
  const dictTypes = ref<any[]>([])
  
  // 判断是否为编辑模式
  const isEditing = computed(() => {
    return !!(props.dictItem && props.dictItem.id)
  })
  
  // 表单数据
  const dictItemForm = reactive({
    id: null as number | null,
    dict_type_id: null as number | null,
    dict_label: '',
    dict_value: '',
    parent_id: 0,
    status: 1,
    sort: 0,
    color: '',
    icon: '',
    remark: '',
  })
  
  // 表单验证规则
  const formRules: FormRules = {
    dict_type_id: [
      { required: true, message: '请选择字典类型', trigger: 'change' },
    ],
    dict_label: [
      { required: true, message: '请输入字典标签', trigger: 'blur' },
      { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' },
    ],
    dict_value: [
      { required: true, message: '请输入字典值', trigger: 'blur' },
      { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' },
    ],
    parent_id: [
      { type: 'number', min: 0, message: '父级ID必须大于等于 0', trigger: 'blur' },
    ],
    sort: [
      { type: 'number', min: 0, message: '排序序号必须大于等于 0', trigger: 'blur' },
    ],
    color: [
      { max: 20, message: '颜色值长度不能超过 20 个字符', trigger: 'blur' },
    ],
    icon: [
      { max: 50, message: '图标长度不能超过 50 个字符', trigger: 'blur' },
    ],
    remark: [
      { max: 500, message: '备注长度不能超过 500 个字符', trigger: 'blur' },
    ],
  }
  
  // 获取字典类型列表
  async function fetchDictTypes() {
    try {
      const res = await getDictTypes()
      if (res.success === true && res.data) {
        dictTypes.value = Array.isArray(res.data) ? res.data : []
      } else if (Array.isArray(res)) {
        dictTypes.value = res
      } else if (res && res.data) {
        dictTypes.value = Array.isArray(res.data) ? res.data : []
      }
    } catch (err: any) {
      console.error('获取字典类型列表失败:', err)
    }
  }
  
  // 监听 dictItem 变化，填充表单数据
  watch(
    () => props.dictItem,
    (newDictItem) => {
      if (newDictItem) {
        dictItemForm.id = newDictItem.id || null
        dictItemForm.dict_type_id = newDictItem.dict_type_id || null
        dictItemForm.dict_label = newDictItem.dict_label || ''
        dictItemForm.dict_value = newDictItem.dict_value || ''
        dictItemForm.parent_id = newDictItem.parent_id || 0
        dictItemForm.status = newDictItem.status !== undefined ? newDictItem.status : 1
        dictItemForm.sort = newDictItem.sort || 0
        dictItemForm.color = newDictItem.color || ''
        dictItemForm.icon = newDictItem.icon || ''
        dictItemForm.remark = newDictItem.remark || ''
      } else {
        resetForm()
      }
    },
    { immediate: true }
  )
  
  // 监听 dictTypeId 变化
  watch(
    () => props.dictTypeId,
    (newTypeId) => {
      if (newTypeId && !isEditing.value) {
        dictItemForm.dict_type_id = newTypeId
      }
    },
    { immediate: true }
  )
  
  // 重置表单
  function resetForm() {
    dictItemForm.id = null
    dictItemForm.dict_type_id = props.dictTypeId || null
    dictItemForm.dict_label = ''
    dictItemForm.dict_value = ''
    dictItemForm.parent_id = 0
    dictItemForm.status = 1
    dictItemForm.sort = 0
    dictItemForm.color = ''
    dictItemForm.icon = ''
    dictItemForm.remark = ''
    dictItemFormRef.value?.clearValidate()
  }
  
  // 关闭对话框
  function handleClose() {
    visible.value = false
    resetForm()
  }
  
  // 提交表单
  async function handleSubmit() {
    if (!dictItemFormRef.value) return
  
    try {
      await dictItemFormRef.value.validate()
    } catch (error) {
      return
    }
  
    submitting.value = true
    try {
      const submitData: any = {
        dict_type_id: dictItemForm.dict_type_id,
        dict_label: dictItemForm.dict_label,
        dict_value: dictItemForm.dict_value,
        parent_id: dictItemForm.parent_id,
        status: dictItemForm.status,
        sort: dictItemForm.sort,
        color: dictItemForm.color || '',
        icon: dictItemForm.icon || '',
        remark: dictItemForm.remark || '',
      }
  
      if (isEditing.value) {
        const res = await updateDictItem(dictItemForm.id!, submitData)
        if (res.success === true || res.code === 0) {
          ElMessage.success('字典项更新成功')
          emit('success')
          handleClose()
        } else {
          ElMessage.error(res.message || '更新失败，请重试')
        }
      } else {
        const res = await addDictItem(submitData)
        if (res.success === true || res.code === 0) {
          ElMessage.success('字典项添加成功')
          emit('success')
          handleClose()
        } else {
          ElMessage.error(res.message || '添加失败，请重试')
        }
      }
    } catch (error: any) {
      ElMessage.error(error.message || '操作失败，请重试')
    } finally {
      submitting.value = false
    }
  }
  
  onMounted(() => {
    fetchDictTypes()
  })
  </script>
  
  <style scoped lang="less">
  .form-tip {
    font-size: 12px;
    color: var(--el-text-color-secondary);
    margin-top: 4px;
    line-height: 1.4;
  }
  </style>
  
  