<template>
  <el-dialog
    v-model="dialogVisible"
    title="条文设置"
    :width="600"
    center
    align-center
    :close-on-click-modal="false"
    @closed="closed"
  >
    <el-form :model="formData" ref="formRef" label-width="130px" :rules="formRules">
      <el-form-item label="设置条文类型：" prop="articleType">
        <ClauseSetting
          :publication-date="formData.publicationDate"
          v-model="formData.articleType"
          v-model:relatedPid="formData.firstArticleNo"
        />
      </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>
import { ref, defineExpose, nextTick } from "vue";
import { FormInstance, FormRules, ElMessage } from "element-plus";
import { setArticelType } from "@/api/modules/corpus/clause-trash";
import { ClauseTrash } from "@/api/interface";
import ClauseSetting from "@/components/ClauseSetting/index.vue";
import { ArticleEnum } from "@/enums";

//* 接收注入
const dialogVisible = ref(false);
//* data
//* ref
const formRef = ref<FormInstance>();
const openPromise = ref<any>({});
interface FormData extends Partial<ClauseTrash.ReqSetArticleTypeParams>, Record<string, any> {}
const formData = ref<FormData>(getFormDefaultValue());
//* 方法

// 校验规则
let formRules: FormRules = {
  articleType: [
    { required: true, message: "请选择一个类型", trigger: "blur" },
    {
      //校验相关条文，相关条文必须要选一个首见条文类型
      validator(_, value, callback) {
        if (value === ArticleEnum.RELATED && !formData.value.firstArticleNo) {
          return callback(new Error("关联首见条文不能为空"));
        }
        return callback();
      },
      trigger: "change"
    }
  ]
};

function getFormDefaultValue(): FormData {
  return {
    articleId: undefined,
    articleType: undefined,
    firstArticleNo: undefined,
    publicationDate: undefined
  };
}

function closed() {
  formData.value = getFormDefaultValue();
  nextTick(formRef.value?.clearValidate);
}
// 取消
function handleCancel() {
  dialogVisible.value = false;
}
//提交
function handleSubmit() {
  formRef.value?.validate(async valid => {
    if (!valid) return;
    const params = {
      ...formData.value
    };
    await setArticelType(params as ClauseTrash.ReqSetArticleTypeParams);
    ElMessage.success("设置成功");
    openPromise.value.resolve();
    dialogVisible.value = false;
  });
}

function open(params: FormData) {
  formData.value.articleId = params.id;
  formData.value.publicationDate = params.publicationDate;
  dialogVisible.value = true;
  return new Promise(resolve => {
    openPromise.value.resolve = resolve;
  });
}
defineExpose({
  open
});
</script>

<style lang="scss"></style>
