<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isAdd ? '添加' : '编辑'"
    :width="500"
    center
    align-center
    :close-on-click-modal="false"
    @closed="handleBeforeClose"
  >
    <el-form :model="formData" ref="formRef" label-width="100px" :rules="formRules" class="mt20">
      <el-form-item label="知识元名称" prop="knowledgeName">
        <el-input v-model="formData.knowledgeName" placeholder="请输入知识元名称" />
      </el-form-item>
      <el-form-item label="注释" prop="annotation">
        <el-input v-model="formData.annotation" placeholder="请输入注释" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" class="ml30" v-throttle="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup name="editKnowledge">
import { ref, reactive, nextTick } from "vue";
import { FormInstance, FormRules, ElMessage } from "element-plus";

//* 接收注入
const dialogVisible = ref(false);
//* data
//* ref
const formRef = ref<FormInstance>();
const openPromise = ref<any>({});
const isAdd = ref(false);
const formData = reactive<FormData>(getFormDefaultValue());

interface FormData {
  [key: string]: any;
}

function getFormDefaultValue(): FormData {
  return {
    knowledgeId: undefined,
    parentId: 0,
    annotation: undefined
  };
}
//* 方法

// 校验规则
let formRules = reactive<FormRules>({
  knowledgeName: [{ required: true, message: "知识体名称不能为空", trigger: "blur" }]
});

// 取消
function handleCancel() {
  dialogVisible.value = false;
}
function handleBeforeClose() {
  dialogVisible.value = false;
  const defaultValue = getFormDefaultValue();
  for (const key of Object.keys(defaultValue)) {
    formData[key] = defaultValue[key];
  }
  nextTick(formRef.value?.clearValidate);
}
//提交
function handleSubmit() {
  console.log("提交");
  ElMessage.success("新增成功");
  openPromise.value.resolve();
  dialogVisible.value = false;
  // formRef.value?.validate(async valid => {
  //   if (!valid) return;
  //   const params = {
  //     ...formData
  //   };
  //   if (isAdd.value) {
  //     await addMenu(params);
  //     ElMessage.success("新增成功");
  //   } else {
  //     await editMenu(params);
  //     ElMessage.success("编辑成功");
  //   }
  //   openPromise.value.resolve();
  //   dialogVisible.value = false;
  // }
}
function open(params?: FormData) {
  isAdd.value = !params?.knowledgeId;
  dialogVisible.value = true;
  if (params) {
    if (params.knowledgeId) {
      for (const key of Object.keys(formData)) {
        formData[key] = params[key];
      }
    } else {
      formData.parentId = params.parentId;
    }
  }
  return new Promise(resolve => {
    openPromise.value.resolve = resolve;
  });
}
defineExpose({
  open
});
</script>
