<template>
  <el-dialog :title="title" v-model="dialogOpen" width="50%" append-to-body>
    <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入标题" maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择类型" clearable style="width: 200px">
              <el-option v-for="dict in types" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="内容" prop="content">
            <Editor v-model="form.content" :height="500" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { addKnowledge, updateKnowledge } from '@/api/knowledge'
import Editor from '@/components/Editor'
import { defaultForm } from '../config'

defineExpose({
  setForm,
  resetForm,
})

const props = defineProps({
  open: { type: Boolean, required: true },
  title: { type: String, required: true },
  types: { type: Array, required: true },
})

const form = ref({ ...defaultForm })

const emits = defineEmits(['update:open', 'success'])

// 创建本地状态来响应open属性的变化
const dialogOpen = ref(props.open)

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请填写标题', trigger: 'blur' }],
  type: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
  content: [{ required: true, message: '请填写内容', trigger: 'blur' }],
}

// 创建表单引用
const formRef = ref(null)

const { proxy } = getCurrentInstance()

// 监听props.open的变化，同步到本地状态
watch(
  () => props.open,
  (newValue) => {
    dialogOpen.value = newValue
  }
)

// 监听本地状态的变化，通知父组件更新
watch(
  dialogOpen,
  (newValue) => {
    if (newValue !== props.open) {
      emits('update:open', newValue)
    }
  }
)

// 移除或修改相关函数中的emits调用
// 提交表单
async function submitForm() {
  try {
    await formRef.value.validate()

    if (form.value.id) {
      await updateKnowledge(form.value)
      proxy.$modal.msgSuccess('修改成功')
    } else {
      await addKnowledge(form.value)
      proxy.$modal.msgSuccess('新增成功')
    }

    dialogOpen.value = false
    resetForm()
    emits('success')
  } catch (error) {
    // 表单验证失败不提示错误
    if (error !== 'cancel') {
      proxy.$modal.msgError('操作失败: ' + (error.message || '未知错误'))
    }
  }
}

// 取消按钮操作
function cancel() {
  resetForm()
  dialogOpen.value = false
}

function setForm(data) {
  form.value = { ...data }
}

function resetForm() {
  form.value = { ...defaultForm }
  formRef.value?.resetFields()
}
</script>