<template>
  <div class="comment-config">
    <div class="mb-4 tab-btns">
      <el-button
        v-for="tab in tabs"
        :key="tab.val"
        size="medium"
        :type="curTab == tab.val ? 'primary' : 'default'"
        @click="selectMenu(tab.val)"
        >{{ tab.name }}
      </el-button>
    </div>

    <component
      :is="compName"
      :rates="curRates"
      @data-change="dataChange"
    ></component>
    <p v-if="errorMsg" class="tips-info tips-error">{{ errorMsg }}</p>

    <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 CommentKnowledge from "./CommentKnowledge.vue";
import CommentAbility from "./CommentAbility.vue";
import { initKnowledgeList, initAbilityList } from "./defaultComment";
import { updateModuleEvaluation } from "../../api";

export default {
  name: "comment-config",
  components: { CommentKnowledge, CommentAbility },
  data() {
    return {
      curTab: "knowledge",
      tabs: [
        {
          name: "知识维度",
          val: "knowledge"
        },
        {
          name: "能力维度",
          val: "ability"
        }
      ],
      loading: false,
      knowledgeList: [],
      abilityList: [],
      errorMsg: ""
    };
  },
  computed: {
    ...mapState("baseConfigs", ["evaluationList", "baseInfo"]),
    compName() {
      return `comment-${this.curTab}`;
    },
    curRates() {
      return this.curTab === "knowledge"
        ? this.knowledgeList
        : this.abilityList;
    }
  },
  created() {
    this.initData();
  },
  methods: {
    initData() {
      this.parseKnowledgeList();
      this.parseAbilityList();
    },
    parseKnowledgeList() {
      const rateList = this.evaluationList.filter(
        item => item.moduleType === "KNOWLEDGE"
      );
      if (rateList.length) {
        this.knowledgeList = rateList.map(item => {
          return {
            levelCode: item.levelCode,
            levelName: item.levelName,
            result: item.result,
            advice: item.advice,
            startRate: Math.floor(item.min * 100),
            endRate: Math.floor(item.max * 100)
          };
        });
      } else {
        this.knowledgeList = initKnowledgeList.map(item => {
          return { ...item };
        });
      }
    },
    parseAbilityList() {
      const rateList = this.evaluationList.filter(
        item => item.moduleType === "ABILITY"
      );
      if (rateList.length) {
        this.abilityList = rateList.map(item => {
          return {
            levelCode: item.levelCode,
            levelName: item.levelName,
            result: item.result,
            advice: item.advice,
            startRate: item.min * 1,
            endRate: item.max * 1
          };
        });
      } else {
        this.abilityList = initAbilityList.map(item => {
          return { ...item };
        });
      }
    },
    selectMenu(tab) {
      this.curTab = tab;
    },
    dataChange(data) {
      if (this.curTab === "knowledge") {
        this.knowledgeList = data;
      } else {
        this.abilityList = data;
      }
      this.checkData();
    },
    checkData() {
      this.errorMsg = "";
      return this.checkKnowledgeList() && this.checkAbilityList();
    },
    checkKnowledgeList() {
      const isEmpty = num => !num && num !== 0;

      if (
        this.knowledgeList.some(
          item => isEmpty(item.startRate) || isEmpty(item.endRate)
        )
      ) {
        this.errorMsg = "请完成知识维度划分规则";
        return;
      }

      for (let i = 0; i < this.knowledgeList.length; i++) {
        const item = this.knowledgeList[i];
        if (i) {
          const prevItem = this.knowledgeList[i - 1];
          if (prevItem.startRate !== item.endRate) {
            this.errorMsg = "请保证知识维度划分规则区间连续";
            return;
          }
        }
      }

      return true;
    },
    checkAbilityList() {
      const isEmpty = num => !num && num !== 0;

      if (
        this.abilityList.some(
          item => isEmpty(item.startRate) || isEmpty(item.endRate)
        )
      ) {
        this.errorMsg = "请完成能力维度划分规则";
        return;
      }

      for (let i = 0; i < this.abilityList.length; i++) {
        const item = this.abilityList[i];
        if (i) {
          const prevItem = this.abilityList[i - 1];
          if (prevItem.startRate !== item.endRate) {
            this.errorMsg = "请保证能力维度划分规则区间连续";
            return;
          }
        }
      }

      return true;
    },
    getData() {
      let data = [];
      this.knowledgeList.forEach(item => {
        const min = item.startRate / 100;
        const max = item.endRate / 100;
        let scopeStr = "";
        if (item.endRate === 100) {
          scopeStr = `[${min},${max}]`;
        } else if (item.startRate === 0) {
          scopeStr = `[${min},${max})`;
        } else {
          scopeStr = `[${min},${max})`;
        }

        data.push({
          advice: item.advice,
          formula: "PERSONAL_SCORE_RATE",
          scope: scopeStr,
          result: item.result,
          levelCode: item.levelCode,
          moduleType: "KNOWLEDGE",
          levelName: item.levelName
        });
      });

      this.abilityList.forEach(item => {
        let scopeStr = "";
        if (item.levelCode === "A") {
          scopeStr = `[${item.startRate},${item.endRate}]`;
        } else if (item.startRate === 0) {
          scopeStr = `[${item.startRate},${item.endRate})`;
        } else {
          scopeStr = `[${item.startRate},${item.endRate})`;
        }

        data.push({
          advice: item.advice,
          formula: "PERCENTILE_RANK",
          scope: scopeStr,
          result: item.result,
          levelCode: item.levelCode,
          moduleType: "ABILITY",
          levelName: item.levelName
        });
      });

      return data;
    },
    async toSubmit() {
      if (!this.checkData()) return;

      if (this.loading) return;
      this.loading = true;
      const gradeModuleEvaluationDatasourceList = this.getData();
      const data = await updateModuleEvaluation({
        paperNumber: this.baseInfo.paperNumber,
        paperName: this.baseInfo.paperName,
        paperType: this.baseInfo.paperType,
        gradeModuleEvaluationDatasourceList
      }).catch(() => {});
      this.loading = false;
      if (!data) return;
      this.$message.success("保存成功！");
      this.$emit("modified");
    }
  }
};
</script>
