<template>
  <div class="course-weight-manage">
    <div class="part-box part-box-pad">
      <p>说明：</p>
      <p>
        1.课程目标评价依据来源于平时成绩和期末考试成绩二部分，请录入平时成绩，期末成绩整体权重及各目标的权重；
      </p>
      <p>2.各课程目标下评价方式平时成绩部分总权重应等于100%；</p>
    </div>
    <div class="part-box part-box-pad">
      <el-table :data="tableSetData" style="max-width: 1000px" border>
        <el-table-column
          prop="courseTargetName"
          label="课程目标"
        ></el-table-column>
        <el-table-column label="平时成绩" width="160">
          <template slot-scope="scope">
            <div v-if="scope.row.type === 'sum'">
              <el-input-number
                v-model="customRate"
                class="width-80"
                size="small"
                :min="0"
                :max="100"
                :step="1"
                step-strictly
                :controls="false"
              >
              </el-input-number>
              <span style="margin-left: 5px">%</span>
            </div>
            <el-button
              v-else
              type="text"
              class="btn-act-primary"
              @click="toEdit(scope.row)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="期末成绩" width="160">
          <template slot-scope="scope">
            <div v-if="scope.row.type === 'sum'">
              <el-input-number
                v-model="defaultRate"
                class="width-80"
                size="small"
                :min="0"
                :max="100"
                :step="1"
                step-strictly
                :controls="false"
              >
              </el-input-number>
              <span style="margin-left: 5px">%</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="目标整体权重" width="160">
          <template slot-scope="scope">
            <div v-if="scope.row.type === 'sum'">100%</div>
            <div v-else>
              <el-input-number
                v-model="scope.row.totalWeight"
                class="width-50"
                size="small"
                :min="0"
                :max="100"
                :step="1"
                step-strictly
                :controls="false"
              >
              </el-input-number>
              <span style="margin-left: 5px">%</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="text-center" style="margin: 20px 0">
        <el-button type="primary" :loading="loading" @click="submit"
          >保存</el-button
        >
      </div>
      <el-table
        v-if="resultDataList.length && cwStatus.currentSettingStatus"
        :data="resultDataList"
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        :span-method="spanMethod"
      >
        <el-table-column
          prop="courseTargetName"
          label="课程目标"
          width="140"
        ></el-table-column>
        <el-table-column
          prop="degreeRequirement"
          label="支撑毕业要求"
          min-width="200"
        ></el-table-column>
        <el-table-column prop="totalWeight" label="目标整体权重" width="110">
          <template slot-scope="scope">{{ scope.row.totalWeight }}%</template>
        </el-table-column>
        <el-table-column label="考核/评价环节及目标分值">
          <el-table-column
            v-for="(item, eindex) in fullEvaluationList"
            :key="item.evaluationId"
            :label="item.evaluationName"
          >
            <template slot-scope="scope">
              {{
                scope.row.evaluationList[eindex].enable
                  ? scope.row.evaluationList[eindex].targetScore
                  : ""
              }}
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="目标分值统计" width="120">
          <template slot-scope="scope">
            {{ getEvaluationSumScore(scope.row.evaluationList) }}
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- ModifyTargetEvaluation -->
    <modify-target-evaluation
      ref="ModifyTargetEvaluation"
      :sources="evaluationSources"
      :target="curTarget"
      @modified="targetEvaluationModified"
    ></modify-target-evaluation>
  </div>
</template>

<script>
import { courseWeightDetail, courseWeightSave } from "../../api";
import { calcSum } from "@/plugins/utils";
import { mapState, mapActions } from "vuex";
import ModifyTargetEvaluation from "./ModifyTargetEvaluation.vue";

export default {
  name: "course-weight-manage",
  components: { ModifyTargetEvaluation },
  props: {
    course: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      defaultRate: 0,
      customRate: 0,
      tableSetData: [],
      evaluationList: [],
      fullEvaluationList: [],
      resultDataList: [],
      curTarget: {},
      evaluationSources: [],
      loading: false,
    };
  },
  computed: {
    ...mapState("base", ["cwStatus"]),
    lastNo() {
      return this.evaluationList.length - 1;
    },
  },
  mounted() {
    this.initData();
  },
  methods: {
    ...mapActions("base", ["updateCwStatus"]),
    async initData() {
      await this.updateCwStatus({
        teachCourseId: this.course.id,
      });
      await this.getList();
      if (this.cwStatus.currentSettingStatus) {
        this.updateResultDataList();
      }
    },
    async getList() {
      const res = await courseWeightDetail({
        teachCourseId: this.course.id,
      });
      this.defaultRate = res.defaultRate;
      this.customRate = res.customRate;
      this.transformData(res.submitForm || []);
    },
    transformData(data) {
      if (!data || !data.length) return [];

      this.evaluationList = data[0].evaluationList
        .filter((evaluation) => evaluation.evaluationType !== "DEFAULT")
        .map((evaluation) => {
          return { ...evaluation };
        });
      this.fullEvaluationList = data[0].evaluationList.map((evaluation) => {
        return { ...evaluation };
      });

      this.tableSetData = data;
      this.tableSetData.push({
        type: "sum",
        courseTargetId: "",
        courseTargetName: "合计",
      });
    },
    toEdit(row) {
      this.curTarget = row;
      this.updateEvaluationSources();
      this.$refs.ModifyTargetEvaluation.open();
    },
    updateEvaluationSources() {
      const unvalidEvaluations = [];
      this.tableSetData.forEach((item) => {
        if (item.type === "sum") return;
        if (item.courseTargetId === this.curTarget.courseTargetId) return;

        unvalidEvaluations.push(
          ...item.evaluationList
            .filter((elem) => elem.enable)
            .map((elem) => elem.evaluationId)
        );
      });

      this.evaluationSources = this.evaluationList.filter(
        (item) => !unvalidEvaluations.includes(item.evaluationId)
      );
    },
    targetEvaluationModified(data) {
      const valDict = {};
      data.forEach((item) => {
        valDict[item.evaluationId] = item.weight;
      });
      console.log(data, valDict);
      this.curTarget.evaluationList.forEach((evaluation, index) => {
        if (evaluation.evaluationType === "DEFAULT") return;
        evaluation.enable = valDict[evaluation.evaluationId] !== undefined;
        evaluation.weight = valDict[evaluation.evaluationId] || null;
      });
      console.log(this.curTarget);
    },
    getEvaluationSumScore(evaluationList) {
      const num = calcSum(
        evaluationList.map((item) => (item.enable ? item.targetScore : 0))
      );
      return num.toFixed(2);
    },
    spanMethod({ rowIndex, columnIndex }) {
      const lineCount = this.resultDataList.length - 1;
      if (rowIndex === lineCount) {
        if (columnIndex === 0) {
          return [1, 2];
        } else if (columnIndex === 1) {
          return [0, 0];
        }
      }
    },
    updateResultDataList() {
      // 更新合计
      const dataList = this.tableSetData.slice(0, -1);
      const tatolEvaluation = this.fullEvaluationList.map(
        (evaluation, eindex) => {
          const targetScore = calcSum(
            dataList.map((item) => item.evaluationList[eindex].targetScore || 0)
          );
          return {
            evaluationName: evaluation.evaluationName,
            enable: true,
            weight: null,
            targetScore,
          };
        }
      );
      this.resultDataList = [
        ...dataList,
        {
          courseTargetId: "total",
          courseTargetName: "合计",
          degreeRequirement: "",
          totalWeight: calcSum(dataList.map((item) => item.totalWeight || 0)),
          evaluationList: tatolEvaluation,
        },
      ];
    },
    checkDataList() {
      // 整体权重设置
      if (!this.customRate) {
        this.$message.error("请输入平时成绩权重");
        return;
      }
      if (!this.defaultRate) {
        this.$message.error("请输入期末成绩权重");
        return;
      }
      if (this.defaultRate + this.customRate !== 100) {
        this.$message.error("平均成绩权重与期末成绩权重合计不等于100%");
        return;
      }

      const dataList = this.tableSetData.slice(0, -1);

      // 目标整体权重
      if (dataList.some((item) => !item.totalWeight)) {
        this.$message.error("请设置所有目标的目标整体权重");
        return;
      }
      const totalWeight = calcSum(
        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 courseWeightSave({
        teachCourseId: this.course.id,
        defaultRate: this.defaultRate,
        customRate: this.customRate,
        submitForm: this.tableSetData.slice(0, -1),
      }).catch(() => {});
      this.loading = false;
      if (!res) return;

      this.initData();
      this.$message.success("保存成功！");
    },
  },
};
</script>
