<template>
  <el-form style="max-width: 1000px" :model="formData" ref="formRef" label-width="90px" :rules="formRules" v-bind="$attrs">
    <el-form-item label="条文内容" prop="articleContent">
      <el-input
        v-model="formData.articleContent"
        placeholder="请输入条文内容"
        :disabled="!editable || disabledContent"
        :maxlength="1000"
      />
    </el-form-item>
    <el-form-item label="所属疾病" prop="diseaseName">
      <el-input v-model="formData.diseaseName" placeholder="请输入所属疾病" :disabled="!editable" :maxlength="50" />
    </el-form-item>
    <el-form-item label="书名" prop="bookName">
      <el-input v-model="formData.bookName" placeholder="请输入书名" :disabled="!editable" :maxlength="50" />
    </el-form-item>
    <el-form-item label="卷名" prop="chapter">
      <el-input v-model="formData.chapter" placeholder="请输入卷名" :disabled="!editable" :maxlength="50" />
    </el-form-item>
    <el-form-item label="版本信息" prop="version">
      <el-input v-model="formData.version" placeholder="请输入版本信息" :disabled="!editable" :maxlength="50" />
    </el-form-item>
    <el-form-item label="朝代" prop="startDynastySort">
      <div style="display: flex; flex-direction: column">
        <div>
          <el-select
            :disabled="!editable"
            v-model="formData.startDynastySort"
            :placeholder="dynastyIsRange ? '请选择开始朝代' : '请选择朝代'"
            style="width: 250px"
            clearable
          >
            <!-- 其他（99） -->
            <template v-for="item in dynastyOptions">
              <el-option
                v-if="item.dictSort !== 99 || !dynastyIsRange"
                :key="item.dictSort"
                :label="item.dictLabel"
                :value="item.dictSort"
                :disabled="dynastyIsRange && !!formData.endDynastySort && item.dictSort >= formData.endDynastySort"
              >
              </el-option>
            </template>
          </el-select>
          <el-checkbox
            :disabled="!editable"
            class="ml30"
            v-model="dynastyIsRange"
            label="范围"
            size="large"
            @change="dynastyCheckboxChange"
          ></el-checkbox>
        </div>
        <template v-if="dynastyIsRange">
          <el-select
            v-model="formData.endDynastySort"
            class="mt10"
            style="width: 250px"
            placeholder="请选择结束朝代"
            :disabled="!editable"
            clearable
          >
            <!-- 其他（99） -->
            <template v-for="item in dynastyOptions">
              <el-option
                v-if="item.dictSort !== 99"
                :key="item.dictSort"
                :label="item.dictLabel"
                :value="item.dictSort"
                :disabled="!!formData.startDynastySort && item.dictSort <= formData.startDynastySort"
              ></el-option>
            </template>
          </el-select>
        </template>
      </div>
    </el-form-item>
    <el-form-item label="成书年代" prop="publicationDate">
      <grace-year-input v-model="formData.publicationDate" placeholder="请输入成书年代" :disabled="!editable" />
    </el-form-item>
    <el-form-item label="作者" prop="author">
      <el-input v-model="formData.author" placeholder="请输入作者" :disabled="!editable" :maxlength="50" />
    </el-form-item>
    <el-form-item label="体裁" prop="styleId">
      <el-radio-group v-model="formData.styleId" :disabled="!editable">
        <el-radio v-for="item in StyleId.getAllEnumValues()" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item v-if="mode === Mode.Add" label="设置条文类型：" prop="articleType">
      <ClauseSetting
        :publication-date="formData.publicationDate"
        v-model="formData.articleType"
        v-model:relatedPid="formData.relatedPid"
      />
    </el-form-item>
  </el-form>
</template>
<script lang="ts" setup>
import { reactive, ref, defineExpose, defineProps, withDefaults } from "vue";
import { FormInstance, FormRules, ElMessage, CheckboxValueType } from "element-plus";
import { editClause } from "@/api/modules/corpus/first-clause";
import { addClause } from "@/api/modules/corpus/trace-origin";
import { Common, Clause } from "@/api/interface";
import { getDictOptions } from "@/api/modules/common";
import { StyleId, ArticleEnum } from "@/enums";
import ClauseSetting from "@/components/ClauseSetting/index.vue";

enum Mode {
  View = "view",
  Edit = "edit",
  Add = "add"
}
interface Props {
  editable?: "" | boolean;
  mode: "view" | "edit" | "add";
  disabledContent?: boolean;
}

// prop
const props = withDefaults(defineProps<Props>(), {
  editable: false,
  mode: Mode.View,
  disabledContent: false
});

//* data
//* ref
const formRef = ref<FormInstance>();
interface FormData extends Partial<Clause.ClauseInfo> {
  relatedPid?: number;
}
const formData = ref<FormData>(getFormDefaultValue());
const dynastyOptions = ref<Common.DictOptions[]>([]);
const dynastyIsRange = ref(false);
//* 方法

// 校验规则
let formRules = reactive<FormRules>({
  articleContent: [{ required: true, message: "条文内容不能为空", trigger: "blur" }],
  diseaseName: [{ required: true, message: "所属疾病不能为空", trigger: "blur" }],
  bookName: [{ required: true, message: "书名不能为空", trigger: "blur" }],
  startDynastySort: [
    {
      required: true,
      validator(_, value, callback) {
        if (dynastyIsRange.value) {
          if (!formData.value.startDynastySort) return callback(new Error("请选择开始朝代"));
          if (!formData.value.endDynastySort) return callback(new Error("请选择结束朝代"));
        } else {
          if (!formData.value.startDynastySort) return callback(new Error("请选择朝代"));
        }
        return callback();
      },
      trigger: "change"
    }
  ],
  styleId: [{ required: true, message: "体裁不能为空", trigger: "change" }],
  articleType: [
    { required: true, message: "请选择一个类型", trigger: "blur" },
    {
      //校验相关条文，相关条文必须要选一个首见条文类型
      validator(_, value, callback) {
        if (value === ArticleEnum.RELATED && !formData.value.relatedPid) {
          return callback(new Error("请选择关联首见条文"));
        }
        return callback();
      },
      trigger: "change"
    }
  ]
});

loadDictOptions();
async function loadDictOptions() {
  const res = await getDictOptions("dynasty");
  dynastyOptions.value = res.data;
}

function dynastyCheckboxChange(val: CheckboxValueType) {
  if (!val) {
    formData.value.endDynastySort = undefined;
  } else if (formData.value.startDynastySort === 99) {
    formData.value.startDynastySort = undefined;
  }
}
function getFormDefaultValue(): FormData {
  return {
    id: undefined,
    articleContent: undefined,
    diseaseName: undefined,
    bookName: undefined,
    chapter: undefined,
    version: undefined,
    author: undefined,
    startDynastySort: undefined,
    endDynastySort: undefined,
    publicationDate: undefined,
    styleId: undefined,
    relatedPid: undefined,
    articleType: undefined
  };
}
// 重置
function reset() {
  formRef.value?.resetFields();
  dynastyIsRange.value = !!formData.value.endDynastySort;
}

function cancel() {
  formData.value = getFormDefaultValue();
  clearValidate();
}

// 清除校验
function clearValidate() {
  formRef.value?.clearValidate();
}
//提交
function submit() {
  if (!props.editable) {
    return Promise.resolve();
  }
  return new Promise<void>((resolve, reject) => {
    formRef.value?.validate(async valid => {
      if (!valid) return reject();
      try {
        const params = {
          ...formData.value
        };
        if (params.startDynastySort) {
          params.startDynastyName = dynastyOptions.value.find(
            (item: Common.DictOptions) => item.dictSort === params.startDynastySort
          )?.dictLabel;
        }
        if (params.endDynastySort) {
          params.endDynastyName = dynastyOptions.value.find(
            (item: Common.DictOptions) => item.dictSort === params.endDynastySort
          )?.dictLabel;
        }
        if (params.id) {
          await editClause(params);
          ElMessage.success("编辑成功");
        } else {
          await addClause(params);
          ElMessage.success("新增成功");
        }
        resolve();
      } catch (err) {
        reject(err);
      }
    });
  });
}

function setFormValue(params: FormData) {
  if (params) {
    const defaultValue: FormData = {};
    for (const key of Object.keys(formData.value) as Array<keyof FormData>) {
      defaultValue[key] = params[key] as any;
    }
    if (defaultValue.endDynastySort && defaultValue.startDynastySort === defaultValue.endDynastySort) {
      defaultValue.endDynastySort = undefined;
    }
    formData.value = defaultValue;
    if (defaultValue.endDynastySort) {
      dynastyIsRange.value = true;
    }
  }
}
defineExpose({
  setFormValue,
  clearValidate,
  reset,
  cancel,
  submit
});
</script>

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