<script setup>
import { ref } from 'vue'
import { WordCreateService, WordUpdateService } from '@/api/word'
const dialogVisible = ref(false)
const formRef = ref()
// 是否为修改操作
const isUpdate = ref(false)
// 敏感词等级
const levelOptions = ref([
  { label: '轻度', value: 1 },
  { label: '中度', value: 2 },
  { label: '重度', value: 3 }
])
// 规则
const rules = {
  word: [{ required: true, message: '请输入敏感词内容', trigger: 'blur' }],
  level: [{ required: true, message: '请选择等级', trigger: 'blur' }]
}
const formModel = ref({
  word: '',
  level: 1
})
// 组件对外暴露一个方法 open ，基于 open 传来的参数，区分添加还是编辑
const open = (op, obj) => {
  if (op === 'add') {
    isUpdate.value = false
  } else {
    isUpdate.value = true
    formModel.value = { ...obj }
  }
  dialogVisible.value = true
}
// 向外暴露
defineExpose({
  open
})
const emit = defineEmits(['success'])
// 提交新增事件
const handleSubmit = async () => {
  await formRef.value.validate()
  ElMessageBox.confirm('确认提交？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'info'
  })
    .then(async () => {
      isUpdate.value
        ? await WordUpdateService(formModel.value)
        : await WordCreateService(formModel.value)
      dialogVisible.value = false
      emit('success')
      ElNotification({
        title: '操作结果',
        message: '敏感词' + (isUpdate.value ? '编辑' : '添加') + '成功',
        type: 'success'
      })
    })
    .catch(() => {})
}
const onClose = () => {
  dialogVisible.value = false
  formRef.value.clearValidate()
  // 重置数据
  formModel.value = {
    word: '',
    level: 1
  }
}
</script>
<template>
  <!-- 添加/修改敏感词弹窗 -->
  <el-dialog
    v-model="dialogVisible"
    :title="isUpdate ? '编辑' : '添加'"
    @close="onClose"
    width="20vw"
  >
    <el-form
      ref="formRef"
      :model="formModel"
      :rules="rules"
      label-width="65px"
      style="padding-right: 10px"
    >
      <el-form-item label="敏感词" prop="word">
        <el-input v-model="formModel.word" placeholder="请输入敏感词" />
      </el-form-item>
      <el-form-item label="等级" prop="level">
        <el-select v-model="formModel.level" style="width: 100%">
          <el-option
            v-for="item in levelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="handleSubmit">{{
        isUpdate ? '修改' : '添加'
      }}</el-button>
      <el-button @click="dialogVisible = false">取消</el-button>
    </template>
  </el-dialog>
</template>
