<template>
  <popup
    v-model="showDialog"
    :title="popupTitle"
    width="480px"
    :close-on-click-modal="false"
    :confirmLoading="isLoading"
    @confirm="handleSubmit"
  >
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="90px" v-loading="isLoading">
      <el-form-item label="模板名称" prop="template_name">
        <el-input v-model="formData.template_name" placeholder="请输入模板名称" clearable />
      </el-form-item>
      <el-form-item label="模板键名" prop="template_key">
        <el-input v-model="formData.template_key" placeholder="请输入模板键名" clearable />
      </el-form-item>
      <el-form-item label="模板值" prop="template_value">
        <el-input v-model="formData.template_value" placeholder="请输入模板值" clearable />
      </el-form-item>
    </el-form>
  </popup>
</template>

<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { templateCreate, templateUpdate } from '@/api/message/template'

// 定义组件事件
const emit = defineEmits<{
  (event: 'success'): void
}>()

// 表单引用
const formRef = shallowRef<FormInstance>()
// 模式：add=新增，edit=编辑
const mode = ref<'add' | 'edit'>('add')
// 加载状态
const isLoading = ref(false)
// 是否显示弹窗
const showDialog = ref(false)
// 初始表单数据
const initialFormData = {
  id: '',
  template_name: '',
  template_key: '',
  template_value: ''
}
// 表单数据
const formData = reactive<Record<string, any>>({ ...initialFormData })
// 表单验证规则
const formRules = reactive({
  template_name: [{ required: true, message: '请输入模板名称', trigger: ['blur', 'change'] }],
  template_key: [{ required: true, message: '请输入模板键名', trigger: ['blur', 'change'] }],
  template_value: [{ required: true, message: '请输入模板值', trigger: ['blur', 'change'] }]
})
// 弹窗标题
const popupTitle = computed(() => (mode.value === 'edit' ? '编辑模板' : '新增模板'))

// 打开弹窗
const open = (type: 'add' | 'edit' = 'add') => {
  mode.value = type
  showDialog.value = true
}
// 设置表单数据
const setFormData = (row?: Record<string, any>) => {
  resetForm()
  if (!row) return
  Object.keys(formData).forEach((key: string) => {
    if (row[key] != undefined) formData[key] = row[key]
  })
}
// 表单重置
const resetForm = () => {
  Object.assign(formData, initialFormData)
  formRef.value?.resetFields()
}
// 提交表单
const handleSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return
    isLoading.value = true
    const submitEvent = mode.value === 'edit' ? templateUpdate : templateCreate
    submitEvent(formData)
      .then(() => {
        isLoading.value = false
        showDialog.value = false
        ElMessage.success('操作成功')
        emit('success')
      })
      .catch(() => {
        isLoading.value = false
      })
  })
}

defineExpose({
  open,
  setFormData
})
</script>
