<template>
  <div class="diagnose-config">
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      label-width="180px"
    >
      <el-form-item prop="knowledgeInterpret" label="知识：">
        <el-input
          v-model.trim="modalForm.knowledgeInterpret"
          placeholder="知识"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item
        prop="gradeModuleDefineParamList"
        label="二级维度的精熟度定义："
      >
        <div class="part-box part-box-pad part-box-border-bold">
          <proficiency-edit
            :rates="modalForm.gradeModuleDefineParamList"
            @data-change="paramChange"
          ></proficiency-edit>
        </div>
      </el-form-item>
      <el-form-item prop="abilityInterpret" label="能力：">
        <el-input
          v-model.trim="modalForm.abilityInterpret"
          placeholder="能力"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="totalScore" label="满分：">
        <el-input-number
          v-model="modalForm.totalScore"
          placeholder="请输入满分，如100"
          :min="1"
          :max="9999"
          :step="1"
          step-strictly
          :controls="false"
        ></el-input-number>
        <p class="tips-info">
          说明：若显示赋分，则填写赋分满分分值，否则填写卷面原始分满分分值。
        </p>
      </el-form-item>
      <el-form-item prop="passScore" label="及格分：">
        <el-input-number
          v-model="modalForm.passScore"
          placeholder="请输入及格分，如60"
          :min="1"
          :max="9999"
          :step="1"
          step-strictly
          :controls="false"
        ></el-input-number>
        <p class="tips-info">
          说明：成绩分数≥及格分数线，报告中的结果显示“通过”，否则为“不通过”。
        </p>
      </el-form-item>
    </el-form>

    <div class="config-footer">
      <el-button
        class="width-200"
        type="primary"
        :loading="loading"
        @click="toSubmit"
        >保存</el-button
      >
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import ProficiencyEdit from "./ProficiencyEdit.vue";
import { updatePaperDefine } from "../../api";
import { deepCopy } from "@/plugins/utils";

const initModalForm = {
  knowledgeInterpret: "课程标准规定的学科内容",
  abilityInterpret: "经学习与训练内化而成的心理结构",
  totalScore: 100,
  passScore: 60,
  gradeModuleDefineParamList: [
    {
      level: "A",
      title: "熟练掌握",
      startRate: 90,
      endRate: 100
    },
    {
      level: "B",
      title: "较好掌握",
      startRate: 75,
      endRate: 90
    },
    {
      level: "C",
      title: "基本掌握",
      startRate: 55,
      endRate: 75
    },
    {
      level: "D",
      title: "部分掌握",
      startRate: 40,
      endRate: 55
    },
    {
      level: "E",
      title: "没有掌握，需从头再学",
      startRate: 0,
      endRate: 40
    }
  ]
};

export default {
  name: "diagnose-config",
  components: { ProficiencyEdit },
  data() {
    const isEmpty = num => !num && num !== 0;

    const rateSetValidator = (rule, value, callback) => {
      if (
        value.some(item => isEmpty(item.startRate) || isEmpty(item.endRate))
      ) {
        return callback(new Error("请完成精熟度定义"));
      }

      for (let i = 0; i < value.length; i++) {
        const item = value[i];
        if (i) {
          const prevItem = value[i - 1];
          if (prevItem.startRate !== item.endRate)
            return callback(new Error("请保证区间连续"));
        }
      }

      callback();
    };
    return {
      modalForm: { ...initModalForm },
      rules: {
        knowledgeInterpret: [
          {
            required: true,
            message: "请输入知识",
            trigger: "change"
          },
          {
            max: 100,
            message: "知识字数不能超过100",
            trigger: "change"
          }
        ],
        abilityInterpret: [
          {
            required: true,
            message: "请输入能力",
            trigger: "change"
          },
          {
            max: 100,
            message: "能力字数不能超过100",
            trigger: "change"
          }
        ],
        totalScore: [
          {
            required: true,
            message: "请输入满分",
            trigger: "change"
          }
        ],
        passScore: [
          {
            required: true,
            message: "请输入及格分",
            trigger: "change"
          }
        ],
        gradeModuleDefineParamList: [
          {
            validator: rateSetValidator,
            trigger: "change"
          }
        ]
      },
      loading: false
    };
  },
  computed: {
    ...mapState("baseConfigs", ["defineList", "baseInfo"])
  },
  created() {
    this.initData();
  },
  methods: {
    initData() {
      if (this.defineList) {
        this.modalForm = this.$objAssign(initModalForm, this.defineList);
        this.modalForm.gradeModuleDefineParamList = this.defineList.gradeModuleKnowledgeDefineParamList.map(
          item => {
            return {
              level: item.level,
              title: item.define.split("：")[0],
              startRate: item.min * 100,
              endRate: item.max * 100
            };
          }
        );
      } else {
        this.modalForm = deepCopy(initModalForm);
      }
    },
    paramChange(data) {
      this.modalForm.gradeModuleDefineParamList = data;
      this.$refs.modalFormComp.validateField("gradeModuleDefineParamList");
    },
    async toSubmit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.loading) return;
      this.loading = true;
      const datas = {
        ...this.modalForm,
        paperNumber: this.baseInfo.paperNumber,
        paperName: this.baseInfo.paperName,
        paperType: this.baseInfo.paperType
      };
      datas.gradeModuleDefineParamList = this.modalForm.gradeModuleDefineParamList.map(
        item => {
          const min = item.startRate / 100;
          const max = item.endRate / 100;
          let scopeStr = "",
            defineStr = "";
          if (item.endRate === 100) {
            scopeStr = `[${min},${max}]`;
            defineStr = `${item.title}：个人得分率≥${item.startRate}%`;
          } else if (item.min === 0) {
            scopeStr = `[${min},${max})`;
            defineStr = `${item.title}：个人得分率<${item.endRate}%`;
          } else {
            scopeStr = `[${min},${max})`;
            defineStr = `${item.title}：${item.startRate}%≤个人得分率<${item.endRate}%`;
          }

          return {
            level: item.level,
            min,
            max,
            scope: scopeStr,
            define: defineStr
          };
        }
      );
      const data = await updatePaperDefine(datas).catch(() => {});
      this.loading = false;
      if (!data) return;
      this.$message.success("保存成功！");
      this.$emit("modified");
    }
  }
};
</script>
