<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="600px"
    destroy-on-close
    :close-on-click-modal="false"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="模板名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入模板名称" />
      </el-form-item>
      <el-form-item label="模板编码" prop="code">
        <el-input v-model="form.code" placeholder="请输入模板编码" :disabled="isEdit" />
      </el-form-item>
      <el-form-item label="消息类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择类型" style="width: 100%">
          <el-option label="短信" value="sms" />
          <el-option label="邮件" value="email" />
          <el-option label="站内信" value="site" />
        </el-select>
      </el-form-item>
      <el-form-item label="模板内容" prop="content">
        <vab-editor v-model="form.content" height="300px" placeholder="请输入模板内容，可使用变量如 ${name}" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">停用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSave">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['success'])

const visible = ref(false)
const formRef = ref()
const isEdit = ref(false)

const form = reactive({
  id: '',
  name: '',
  code: '',
  type: 'sms',
  content: '',
  status: 1
})

const rules = {
  name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入模板编码', trigger: 'blur' }],
  type: [{ required: true, message: '请选择消息类型', trigger: 'change' }],
  content: [{ required: true, message: '请输入模板内容', trigger: 'blur' }]
}

const title = computed(() => (isEdit.value ? '编辑消息模板' : '新增消息模板'))

const open = (row?: any) => {
  visible.value = true
  if (row) {
    isEdit.value = true
    Object.assign(form, row)
  } else {
    isEdit.value = false
    Object.assign(form, {
      id: '',
      name: '',
      code: '',
      type: 'sms',
      content: '',
      status: 1
    })
  }
}

const handleSave = async () => {
  if (!formRef.value) return
  await formRef.value.validate((valid: boolean) => {
    if (valid) {
      ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
      emit('success', { ...form })
      visible.value = false
    }
  })
}

defineExpose({ open })
</script>
