<template>
  <div class="course-weight-manage course-matrix">
    <div class="part-box part-box-pad">
      <el-table :data="dataList" :summary-method="getSummaries" show-summary>
        <el-table-column
          prop="courseTargetName"
          label="课程目标"
          width="200"
          fixed="left"
        ></el-table-column>
        <el-table-column label="考核项目及比例（%）" align="center">
          <el-table-column
            v-for="(column, cindex) in columns"
            :key="cindex"
            :label="column"
            align="center"
            min-width="80"
          >
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.evaluationList[cindex].weight"
                class="width-80"
                size="small"
                :min="0"
                :max="100"
                :step="0.01"
                step-strictly
                :controls="false"
                @blur="weightChange(scope.$index, cindex)"
              >
              </el-input-number>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="权重（%）" prop="totalWeight" align="center">
        </el-table-column>
      </el-table>
      <div class="text-center mt-2">
        <el-button
          class="width-200"
          type="primary"
          :loading="loading"
          @click="submit"
          >保存</el-button
        >
      </div>

      <div>
        <p>说明：</p>
        <p>
          1.课程目标评价依据来源于平时成绩和期末考试成绩二部分，请录入各考核项目的权重；
        </p>
        <p>2.各考核项目整体权重应等于100%，用于计算课程整体达成度；</p>
        <p>
          3.期末考试可以分布在不同课程目标下，其他过程性考核项目一个仅能支持一个课程目标。
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import { courseExamineWeightDetail, courseExamineWeightSave } from "../../api";
import { calcSum, toPrecision } from "@/plugins/utils";

export default {
  name: "course-examine-weight",
  props: {
    rowData: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      dataList: [],
      columns: [],
      loading: false,
    };
  },
  mounted() {
    this.initData();
  },
  methods: {
    async initData() {
      this.dataList = [];
      this.columns = [];
      await this.getList();
    },
    calcSumPrecision(dList) {
      return toPrecision(calcSum(dList), 2);
    },
    async getList() {
      const res = await courseExamineWeightDetail({
        obeCourseOutlineId: this.rowData.id,
      });
      const dataList = res.submitForm || [];

      if (!dataList[0]) return;

      this.columns = dataList[0].evaluationList.map(
        (item) => item.evaluationName
      );

      this.columns.forEach((column, cindex) => {
        dataList.forEach((item, eindex) => {
          const node = item.evaluationList[cindex];
          node.weight = node.weight || undefined;
        });
      });

      this.dataList = dataList;
    },
    weightChange(rowIndex, cindex) {
      this.dataList.forEach((item, tindex) => {
        item.totalWeight = this.calcSumPrecision(
          item.evaluationList.map((elem) => elem.weight || 0)
        );
      });
    },
    checkDataList() {
      if (!this.dataList.length) return;

      // 所有课程目标都应该有设置权重
      this.dataList.forEach((item, tindex) => {
        item.totalWeight = this.calcSumPrecision(
          item.evaluationList.map((elem) => elem.weight || 0)
        );
      });
      const unvalidData = this.dataList
        .filter((item) => !item.totalWeight)
        .map((item) => item.courseTargetName);

      if (unvalidData.length) {
        this.$message.error(`请设置${unvalidData.join("，")}的权重`);
        return;
      }

      // 目标整体权重
      const totalWeight = this.calcSumPrecision(
        this.dataList.map((item) => item.totalWeight || 0)
      );
      if (totalWeight !== 100) {
        this.$message.error("目标整体权重合计不等于100%");
        return;
      }

      return true;
    },
    async submit() {
      if (this.loading) return;
      if (!this.checkDataList()) return;

      this.loading = true;
      const res = await courseExamineWeightSave({
        obeCourseOutlineId: this.rowData.id,
        submitForm: this.dataList,
      }).catch(() => {});
      this.loading = false;
      if (!res) return;

      this.initData();
      this.$message.success("保存成功！");
    },
    getSummaries(param) {
      const { columns } = param;
      const sums = [];
      const lastNo = columns.length - 1;
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }

        if (index === lastNo) {
          sums[index] = this.calcSumPrecision(
            this.dataList.map((item) => item.totalWeight || 0)
          );
          return;
        }

        sums[index] = this.calcSumPrecision(
          this.dataList.map(
            (item) => item.evaluationList[index - 1].weight || 0
          )
        );
      });
      return sums;
    },
  },
};
</script>
