<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"></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 v-if="totalInfo" class="mt-2">{{ totalInfo }}</div>
      <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"
      :unuse-targets="unuseTargets"
      @confirm="dimensionSelected"
    ></select-blue-dimension-dialog>
  </div>
</template>

<script>
import {
  endScorePaperPositiveDetail,
  endScorePaperPositiveSave,
  endScorePaperPositiveSync,
  courseOutlineTargetListPage,
  courseExamineWeightDetail,
} 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: [],
      loading: false,
      totalInfo: "",
      unuseTargets: [],
    };
  },
  watch: {
    "course.obeCourseOutlineId": {
      immediate: true,
      handler(val, oldVal) {
        if (!val) return;
        if (val !== oldVal) this.getTree();
      },
    },
  },
  methods: {
    async getTree() {
      await this.getUnuseTarget();
      const data = await courseOutlineTargetListPage({
        obeCourseOutlineId: this.course.obeCourseOutlineId,
      });
      this.treeData = (data || []).map((item) => {
        return {
          id: item.id,
          kid: item.id,
          name: item.targetName,
          totalWeight: item.totalWeight,
          disabled: false,
          children: item.dimensionList.map((elem) => {
            return {
              ...elem,
              kid: `${item.id}_${elem.id}`,
              disabled: false,
            };
          }),
        };
      });
    },
    async getUnuseTarget() {
      const res = await courseExamineWeightDetail({
        obeCourseOutlineId: this.course.obeCourseOutlineId,
      });
      const dataList = res.submitForm || [];

      this.unuseTargets = dataList
        .filter((item) => {
          return !item.evaluationList[0].weight;
        })
        .map((item) => item.courseTargetId);
    },
    async getBlueDetail() {
      const res = await endScorePaperPositiveDetail({
        cultureProgramId: this.course.cultureProgramId,
        courseId: this.course.courseId,
        examId: this.course.examId,
        paperNumber: this.course.paperNumber,
      });
      this.dataList = res || [];
      this.updateTotalInfo();
    },
    visibleChange() {
      this.getBlueDetail();
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async toSync() {
      if (this.loading) return;
      this.loading = true;

      const res = await endScorePaperPositiveSync({
        cultureProgramId: this.course.cultureProgramId,
        courseId: this.course.courseId,
        paperNumber: this.dataList[0]?.paperNumber,
        examId: this.dataList[0]?.examId,
      }).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;
      }

      return true;
    },
    toLink(row) {
      this.curRow = row;
      this.selectedData = [];
      row.targetList.forEach((target) => {
        target.dimensionList.forEach((dimension) => {
          this.selectedData.push(`${target.targetId}_${dimension.dimensionId}`);
        });
      });
      this.$refs.SelectBlueDimensionDialog.open();
    },
    dimensionSelected(targetList) {
      this.curRow.targetList = targetList;
      this.curRow.courseTargetName = targetList[0].targetName;
      this.updateTotalInfo();
    },
    updateTotalInfo() {
      const data = {};
      this.dataList.forEach((item) => {
        const target = item.targetList[0];
        if (!target) return;

        if (!data[target.targetName]) data[target.targetName] = 0;
        data[target.targetName] += item.score;
      });
      this.totalInfo = Object.keys(data)
        .map((key) => `${key}共${data[key]}分`)
        .join("，");
    },
    async submit() {
      if (!this.checkData()) {
        return;
      }

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

      if (!data) return;

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