<template>
  <el-dialog
    v-model="visible"
    :title="dialogType === 'add' ? '新增字典项数据' : '编辑字典项数据'"
    width="600px"
    align-center
    @close="handleClose"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <el-form-item label="字典标签" prop="label">
        <el-input v-model="formData.label" placeholder="请输入字典标签" />
      </el-form-item>
      <el-form-item label="字典键值" prop="value">
        <el-input v-model="formData.value" placeholder="请输入字典键值" />
      </el-form-item>
      <el-form-item label="颜色选择" prop="color">
        <el-color-picker v-model="formData.color" color-format="hex" :predefine="predefineColors" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="formData.sort" placeholder="请输入排序" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <SaiRadio v-model="formData.status" dict="data_status" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import api from '@/api/safeguard/dict'
  import { ElMessage } from 'element-plus'
  import { useDictStore } from '@/store/modules/dict'
  import SaiRadio from '@/components/sai/sa-radio/index.vue'
  import type { FormInstance, FormRules } from 'element-plus'

  interface Props {
    modelValue: boolean
    dialogType: string
    data?: Record<string, any>
  }

  interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    dialogType: 'add',
    data: undefined
  })

  const emit = defineEmits<Emits>()
  const dictStore = useDictStore()

  const formRef = ref<FormInstance>()

  const predefineColors = ref([
    '#ff4500',
    '#ff8c00',
    '#ffd700',
    '#90ee90',
    '#00ced1',
    '#1e90ff',
    '#c71585',
    '#5d87ff',
    '#b48df3',
    '#1d84ff',
    '#60c041',
    '#38c0fc',
    '#f9901f',
    '#ff80c8',
    '#909399'
  ])

  /**
   * 弹窗显示状态双向绑定
   */
  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  })

  /**
   * 表单验证规则
   */
  const rules = reactive<FormRules>({
    label: [{ required: true, message: '请输入字典标签', trigger: 'blur' }],
    value: [{ required: true, message: '请输入字典键值', trigger: 'blur' }]
  })

  /**
   * 初始数据
   */
  const initialFormData = {
    id: null,
    type_id: '',
    code: '',
    label: '',
    color: '#5d87ff',
    value: '',
    remark: '',
    sort: 100,
    status: 1
  }

  /**
   * 表单数据
   */
  const formData = reactive({ ...initialFormData })

  /**
   * 监听弹窗打开，初始化表单数据
   */
  watch(
    () => props.modelValue,
    (newVal) => {
      if (newVal) {
        initPage()
      }
    }
  )
  // 初始化页面数据
  const initPage = async () => {
    // 先重置为初始值
    Object.assign(formData, initialFormData)
    // 如果有数据，则填充数据
    if (props.data) {
      await nextTick()
      initForm(props.data)
    }
  }

  /**
   * 初始化表单数据
   */
  const initForm = (data: any) => {
    if (data) {
      for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
          ;(formData as any)[key] = data[key]
        }
      }
    }
  }

  /**
   * 关闭弹窗并重置表单
   */
  const handleClose = () => {
    visible.value = false
    formRef.value?.resetFields()
  }

  /**
   * 提交表单
   */
  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()
      if (props.dialogType === 'add') {
        await api.dataSave(formData)
        ElMessage.success('新增成功')
      } else {
        await api.dataUpdate(formData)
        ElMessage.success('修改成功')
      }
      dictStore.refresh()
      emit('success')
      handleClose()
    } catch (error) {
      console.log('表单验证失败:', error)
    }
  }
</script>
