<template>
  <el-dialog
    class="modify-knowledge-dim"
    :visible.sync="modalIsShow"
    :title="title"
    top="10vh"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @opened="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      label-width="140px"
    >
      <el-form-item prop="courseCode" label="课程代码：" required>
        <el-input
          v-model.trim="modalForm.courseCode"
          placeholder="请输入课程代码"
          readonly
        ></el-input>
      </el-form-item>
      <el-form-item prop="courseName" label="课程名称：" required>
        <el-input
          v-model.trim="modalForm.courseName"
          placeholder="请输入课程名称"
          readonly
        ></el-input>
      </el-form-item>
      <el-form-item prop="namePrimary" label="一级知识维度：">
        <el-input
          v-model.trim="modalForm.namePrimary"
          placeholder="请输入一级知识维度"
          clearable
          @change="dimValidate"
        ></el-input>
      </el-form-item>
      <el-form-item prop="codePrimary" label="一级维度编号：">
        <el-input
          v-model.trim="modalForm.codePrimary"
          placeholder="请输入一级维度编号"
          clearable
          @change="dimValidate"
        ></el-input>
      </el-form-item>
      <el-form-item prop="nameSecond" label="二级知识维度：">
        <el-input
          v-model.trim="modalForm.nameSecond"
          placeholder="请输入二级知识维度"
          clearable
          @change="dimValidate"
        ></el-input>
      </el-form-item>
      <el-form-item prop="codeSecond" label="二级维度编号：">
        <el-input
          v-model.trim="modalForm.codeSecond"
          placeholder="请输入二级维度编号"
          clearable
          @change="dimValidate"
        ></el-input>
      </el-form-item>
      <el-form-item label="一级维度术语解释：">
        <el-input
          v-model.trim="modalForm.interpretation"
          type="textarea"
          :autosize="{ minRows: 3, maxRows: 5 }"
          placeholder="请输入一级维度术语解释"
          maxlength="100"
          show-word-limit
        ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button type="primary" :disabled="isSubmit" @click="submit"
        >确认</el-button
      >
      <el-button type="danger" @click="cancel" plain>取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapState } from "vuex";

const initModalForm = {
  id: null,
  courseId: "",
  courseName: "",
  courseCode: "",
  namePrimary: "",
  codePrimary: "",
  nameSecond: "",
  codeSecond: "",
  interpretation: "",
  dimensionType: "KNOWLEDGE",
};

export default {
  name: "modify-knowledge-dim",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  computed: {
    ...mapState("baseConfigs", ["dimensionList"]),
    isEdit() {
      return !!this.instance.id;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "知识维度";
    },
  },
  data() {
    const namePrimaryValidator = (rule, value, callback) => {
      if (!this.modalForm.codePrimary || !value) return callback();

      let existFirstDim = this.dictData.find(
        (item) => item.code === this.modalForm.codePrimary
      );
      if (existFirstDim) {
        const existFirstDim1 = this.dictData.find(
          (item) => item.name === value && value !== existFirstDim.name
        );
        if (existFirstDim1) return callback(new Error("一级知识维度已存在"));
      } else {
        const existFirstDim1 = this.dictData.find(
          (item) => item.name === value
        );
        if (existFirstDim1 && !this.isEditOnlyOneDim)
          return callback(new Error("一级知识维度已存在"));
      }

      callback();
    };

    const nameSecondValidator = (rule, value, callback) => {
      if (
        !this.modalForm.codeSecond ||
        !value ||
        !this.modalForm.namePrimary ||
        !this.modalForm.codePrimary
      )
        return callback();

      const addValidator = () => {
        let existFirstDim = this.dictData.find(
          (item) => item.code === this.modalForm.codePrimary
        );
        if (existFirstDim) {
          const secondDimExist = this.dictData.some((item) =>
            item.children.some((elem) => elem.name === value)
          );
          if (secondDimExist) return callback(new Error("二级知识维度已存在"));
        }

        return callback();
      };

      const editValidator = () => {
        let existFirstDim = this.dictData.find(
          (item) => item.code === this.modalForm.codePrimary
        );
        if (existFirstDim) {
          const existSecondDim = existFirstDim.children.find(
            (item) =>
              item.name === value && item.name !== this.instance.nameSecond
          );
          if (existSecondDim) return callback(new Error("二级知识维度已存在"));
        }
        return callback();
      };

      return this.isEdit ? editValidator() : addValidator();
    };

    const codeSecondValidator = (rule, value, callback) => {
      if (
        !this.modalForm.codeSecond ||
        !value ||
        !this.modalForm.namePrimary ||
        !this.modalForm.codePrimary
      )
        return callback();

      if (value[0] !== this.modalForm.codePrimary) {
        return callback(new Error("二级维度编码首字母应该与一级维度编码一致"));
      }

      let existFirstDim = this.dictData.find(
        (item) => item.code === this.modalForm.codePrimary
      );

      if (existFirstDim) {
        let existSecondDim = existFirstDim.children.find(
          (item) => item.code === this.modalForm.codeSecond
        );
        if (this.isEdit) {
          if (
            existSecondDim &&
            existSecondDim.code !== this.instance.codeSecond
          ) {
            return callback(new Error("二级维度编号已存在"));
          }
        } else {
          if (existSecondDim) return callback(new Error("二级维度编号已存在"));
        }
      }

      callback();
    };

    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: {},
      dictData: [],
      isEditOnlyOneDim: false,
      rules: {
        namePrimary: [
          {
            required: true,
            message: "请输入一级知识维度",
            trigger: "change",
          },
          {
            max: 30,
            message: "一级知识维度字数不能超过30",
            trigger: "change",
          },
          {
            validator: namePrimaryValidator,
            trigger: "change",
          },
        ],
        codePrimary: [
          {
            required: true,
            pattern: /^[A-Z]{1}$/,
            message: "一级维度编号只能是大写字母A-Z，长度为1",
            trigger: "change",
          },
        ],
        nameSecond: [
          {
            required: true,
            message: "请输入二级知识维度",
            trigger: "change",
          },
          {
            max: 30,
            message: "二级知识维度字数不能超过30",
            trigger: "change",
          },
          {
            validator: nameSecondValidator,
            trigger: "change",
          },
        ],
        codeSecond: [
          {
            required: true,
            pattern: /^[A-Z][0-9]{1,4}$/,
            message: "二级维度编号只能是大写字母+数字，长度不能超过5",
            trigger: "change",
          },
          {
            validator: codeSecondValidator,
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    initData(val) {
      this.modalForm = this.$objAssign(initModalForm, val);
    },
    visibleChange() {
      this.getDict();
      const existPrimaryDim = this.dictData.find(
        (item) => item.code === this.instance.codePrimary
      );
      this.isEditOnlyOneDim =
        existPrimaryDim && existPrimaryDim.children.length === 1;

      this.initData(this.instance);
      this.$nextTick(() => {
        this.$refs.modalFormComp.clearValidate();
      });
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    getDict() {
      let dictData = {};

      this.dimensionList
        .filter((item) => item.dimensionType === "KNOWLEDGE")
        .forEach((item) => {
          if (!dictData[item.codePrimary]) {
            dictData[item.codePrimary] = {
              name: item.namePrimary,
              code: item.codePrimary,
              children: [],
            };
          }
          dictData[item.codePrimary].children.push({
            name: item.nameSecond,
            code: item.codeSecond,
          });
        });
      this.dictData = Object.values(dictData);
    },
    dimValidate() {
      this.$refs.modalFormComp.validateField([
        "namePrimary",
        "codePrimary",
        "nameSecond",
        "codeSecond",
      ]);
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      this.$emit("modified", {
        ...this.modalForm,
        isLastSec: false,
        secondInd: this.modalForm.codeSecond.substring(1) * 1,
      });
      this.cancel();
    },
  },
};
</script>
