<template>
  <div>
    <el-dialog
      :visible.sync="modalIsShow"
      title="设置试卷蓝图"
      top="10px"
      width="660px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      @open="visibleChange"
    >
      <div class="mb-2 box-justify">
        <div class="box-grow mr-2">
          <span v-for="(target, index) in treeData" :key="target.id">
            <span>{{ target.name }}占比</span>
            <span
              v-if="targetRates[target.id]"
              :class="[
                'mlr-1',
                targetRates[target.id].valid ? 'color-success' : 'color-danger',
              ]"
              >{{ targetRates[target.id].rate }}%</span
            >
            <span>({{ target.totalWeight || 0 }}%)</span>
            <span>{{ index === treeData.length - 1 ? "。" : "，" }}</span>
          </span>
        </div>
        <el-button type="primary" :loading="loading" @click="toSync"
          >同步</el-button
        >
      </div>
      <el-table :data="dataList" border height="400">
        <el-table-column
          prop="mainNumber"
          label="大题号"
          width="80px"
        ></el-table-column>
        <el-table-column
          prop="subNumber"
          label="小题号"
          width="80px"
        ></el-table-column>
        <el-table-column
          prop="score"
          label="小题满分"
          width="80px"
        ></el-table-column>
        <el-table-column prop="courseTargetName" label="所属课程目标">
        </el-table-column>
        <!-- <el-table-column prop="dimensionList" label="知识点">
          <template slot-scope="scope">
            <template v-for="target in scope.row.targetList">
              <p
                v-for="item in target.dimensionList"
                :key="`${target.targetId}_${item.dimensionId}`"
              >
                {{ item.dimensionName }}
              </p>
            </template>
          </template>
        </el-table-column> -->
        <el-table-column class-name="action-column" label="操作" width="110px">
          <template slot-scope="scope">
            <el-button
              class="btn-primary"
              type="text"
              @click="toLink(scope.row)"
              >关联知识点</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer">
        <el-button type="primary" :disabled="isSubmit" @click="submit"
          >确认</el-button
        >
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>

    <!-- 设置知识点 -->
    <select-blue-dimension-dialog
      ref="SelectBlueDimensionDialog"
      :tree-data="treeData"
      :selected-data="selectedData"
      @confirm="dimensionSelected"
    ></select-blue-dimension-dialog>
  </div>
</template>

<script>
import { calcSum } from "@/plugins/utils";
import { courseTargetList } from "../../base/api";
import {
  endScorePaperPositiveDetail,
  endScorePaperPositiveSave,
  endScorePaperPositiveSync,
} from "../api";
import SelectBlueDimensionDialog from "./SelectBlueDimensionDialog.vue";

export default {
  name: "SetBlueDialog",
  components: { SelectBlueDimensionDialog },
  props: {
    course: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      dataList: [],
      curRow: {},
      selectedData: [],
      treeData: [],
      targetRates: {},
      loading: false,
    };
  },
  watch: {
    course: {
      immediate: true,
      handler(val, oldVal) {
        if (!val) return;
        if (val !== oldVal) this.getTree();
      },
    },
  },
  methods: {
    async getTree() {
      const data = await courseTargetList({
        examId: this.course.examId,
        courseCode: this.course.courseCode,
        teachCourseId: this.course.teachCourseId,
      });
      this.treeData = (data || []).map((item) => {
        return {
          id: item.id,
          name: item.targetName,
          totalWeight: item.totalWeight,
          disabled: false,
          children: item.dimensionList.map((elem) => {
            return { ...elem, disabled: false };
          }),
        };
      });
    },
    async getBlueDetail() {
      const res = await endScorePaperPositiveDetail({
        examId: this.course.examId,
        courseCode: this.course.courseCode,
        teachCourseId: this.course.teachCourseId,
      });
      this.dataList = res || [];
      this.updateTargetRates();
    },
    visibleChange() {
      this.getBlueDetail();
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async toSync() {
      if (this.loading) return;
      this.loading = true;

      const res = await endScorePaperPositiveSync({
        examId: this.course.examId,
        courseCode: this.course.courseCode,
        teachCourseId: this.course.teachCourseId,
        paperNumber: this.dataList[0]?.paperNumber,
      }).catch(() => {});
      this.loading = false;
      if (!res) return;

      this.$message.success(`${res.success}，错误：${res.error}`);
      this.getBlueDetail();
    },
    checkData() {
      const valid = !this.dataList.some(
        (item) => !item.targetList || !item.targetList.length
      );

      if (!valid) {
        this.$message.error("还有小题未设置知识点，请完成设置！");
        return;
      }

      const unvalidTargets = [];
      Object.keys(this.targetRates).forEach((tid) => {
        const target = this.targetRates[tid];
        if (!target.valid) unvalidTargets.push(target.name);
      });
      if (unvalidTargets.length) {
        this.$message.error(`${unvalidTargets.join("、")}占比不符合要求`);
        return;
      }

      return true;
    },
    toLink(row) {
      this.curRow = row;
      this.selectedData = [];
      row.targetList.forEach((target) => {
        target.dimensionList.forEach((dimension) => {
          this.selectedData.push(dimension.dimensionId);
        });
      });
      this.$refs.SelectBlueDimensionDialog.open();
    },
    dimensionSelected(targetList) {
      this.curRow.targetList = targetList;
      this.curRow.courseTargetName = targetList[0].targetName;
      this.updateTargetRates();
    },
    updateTargetRates() {
      const scoreData = {};
      this.dataList.forEach((item) => {
        if (!item.targetList || !item.targetList.length) return;
        const targetId = item.targetList[0].targetId;
        if (!scoreData[targetId]) scoreData[targetId] = 0;
        scoreData[targetId] += item.score;
      });
      const totalScore = calcSum(this.dataList.map((item) => item.score));

      const targetRates = {};
      this.treeData.forEach((target) => {
        const targetScore = scoreData[target.id] || 0;
        const rate = !totalScore ? 0 : (100 * targetScore) / totalScore;
        targetRates[target.id] = {
          rate: Number.isInteger(rate) ? rate : rate.toFixed(2),
          valid: rate == target.totalWeight,
          name: target.name,
        };
      });
      this.targetRates = targetRates;
    },
    async submit() {
      if (!this.checkData()) {
        return;
      }

      if (this.isSubmit) return;
      this.isSubmit = true;
      const datas = {
        examId: this.course.examId,
        courseCode: this.course.courseCode,
        teachCourseId: this.course.teachCourseId,
        paperStruct: this.dataList,
      };
      const data = await endScorePaperPositiveSave(datas).catch(() => {});
      this.isSubmit = false;

      if (!data) return;

      this.$message.success("修改成功！");
      this.$emit("modified");
      this.cancel();
    },
  },
};
</script>
