<template>
  <el-dialog
    v-model="visible"
    :title="dialogType === 'add' ? '新增摇色子配置' : '编辑摇色子配置'"
    width="600px"
    align-center
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="分组" prop="group">
        <el-input
          v-model="formData.group"
          placeholder="请输入分组"
          :disabled="dialogType === 'edit'"
        />
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入标题（中文）" />
      </el-form-item>
      <el-form-item label="标题(英文)" prop="title_en">
        <el-input v-model="formData.title_en" placeholder="请输入标题（英文）" />
      </el-form-item>
      <el-form-item label="配置名称" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入配置名称"
          :disabled="dialogType === 'edit'"
        />
      </el-form-item>
      <el-form-item label="值" prop="value">
        <el-input v-model="formData.value" type="textarea" :rows="5" placeholder="请输入值（中文）" />
      </el-form-item>
      <el-form-item label="值(英文)" prop="value_en">
        <el-input v-model="formData.value_en" type="textarea" :rows="5" 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/config/index'
  import { ElMessage } from 'element-plus'
  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 formRef = ref<FormInstance>()

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

  /**
   * 表单验证规则
   */
  const rules = reactive<FormRules>({
    group: [{ required: true, message: '分组必需填写', trigger: 'blur' }],
    title: [{ required: true, message: '标题必需填写', trigger: 'blur' }],
    title_en: [{ max: 255, message: '英文标题长度需小于 255 字符', trigger: 'blur' }],
    name: [{ required: true, message: '配置名称必需填写', trigger: 'blur' }],
    value: [{ required: true, message: '值必需填写', trigger: 'blur' }]
  })

  /**
   * 初始数据
   */
  const initialFormData = {
    id: null,
    value: '',
    value_en: '',
    name: '',
    group: '',
    title: '',
    title_en: ''
  }

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

  /**
   * 监听弹窗打开，初始化表单数据
   */
  watch(
    () => props.modelValue,
    (newVal) => {
      if (newVal) {
        initPage()
      }
    }
  )

  /**
   * 初始化页面数据
   */
  const initPage = async () => {
    // 先重置为初始值
    Object.assign(formData, initialFormData)
    // 如果有数据，则填充数据
    if (props.data) {
      await nextTick()
      initForm()
    }
  }

  /**
   * 初始化表单数据
   */
  const initForm = () => {
    if (props.data) {
      for (const key in formData) {
        if (props.data[key] != null && props.data[key] != undefined) {
          ;(formData as any)[key] = props.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.save(formData)
        ElMessage.success('新增成功')
      } else {
        await api.update(formData)
        ElMessage.success('修改成功')
      }
      emit('success')
      handleClose()
    } catch (error) {
      console.log('表单验证失败:', error)
    }
  }
</script>
