<template>
  <div class="course-weight-manage">
    <div class="part-box part-box-pad">
      <p>说明：</p>
      <p>
        1.请在课程目标考核对应的评价方式表格中打√，并录入权重占比及目标分值；
      </p>
      <p>2.所有课程目标的总目标分值等于100分；</p>
      <p>3.各课程目标下评价方式的总权重应等于100%；</p>
      <p>4.目标整体权重应等于100%，用于计算课程整体达成度。</p>
    </div>
    <div class="part-box part-box-pad">
      <el-table :data="tableSetData">
        <el-table-column
          prop="evaluationName"
          label="评价方式"
          width="140"
          fixed="left"
        ></el-table-column>
        <el-table-column v-for="(target, tindex) in dataList" :key="tindex">
          <template slot="header">
            <el-row type="flex" align="middle">
              <el-col :span="10" :offset="2">
                {{ target.courseTargetName }}
              </el-col>
              <el-col :span="12">
                <span style="margin-right: 5px">目标整体权重</span>
                <el-input-number
                  v-model="targetTotalWeight[target.courseTargetId]"
                  class="width-50"
                  size="small"
                  :min="0"
                  :max="100"
                  :step="1"
                  step-strictly
                  :controls="false"
                >
                </el-input-number>
                <span style="margin-left: 5px">%</span>
              </el-col>
            </el-row>
          </template>
          <el-table-column min-width="340">
            <template slot="header">
              <el-row>
                <el-col :span="10" :offset="2"> 权重 </el-col>
                <el-col :span="12"> 目标分值 </el-col>
              </el-row>
            </template>
            <template slot-scope="scope">
              <el-row type="flex" align="middle">
                <el-col :span="2">
                  <el-checkbox
                    v-model="scope.row.targets[tindex].used"
                    @change="usedChange(scope.$index, tindex)"
                  ></el-checkbox>
                </el-col>
                <el-col :span="10">
                  <el-input-number
                    v-model="scope.row.targets[tindex].weight"
                    :disabled="!scope.row.targets[tindex].used"
                    class="width-80"
                    size="small"
                    :min="0"
                    :max="100"
                    :step="1"
                    step-strictly
                    :controls="false"
                  >
                  </el-input-number>
                  <span style="margin-left: 5px">%</span>
                </el-col>
                <el-col :span="12">
                  <el-input-number
                    v-model="scope.row.targets[tindex].targetScore"
                    :disabled="!scope.row.targets[tindex].used"
                    class="width-80"
                    size="small"
                    :min="0"
                    :max="1000"
                    :step="1"
                    step-strictly
                    :controls="false"
                  >
                  </el-input-number>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
        </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
        :data="dataList"
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
      >
        <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="(ename, eindex) in evaluationData"
            :key="ename"
            :label="ename"
          >
            <template slot-scope="scope">
              {{
                scope.row.evaluation[eindex].used
                  ? scope.row.evaluation[eindex].targetScore
                  : ""
              }}
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="目标分值统计" width="120">
          <template slot-scope="scope">
            {{ getEvaluationSumScore(scope.row.evaluation) }}
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { courseWeightDetail, courseWeightSave } from "../../api";
import { weightList } from "./targetData";
import { omit, pick } from "lodash";
import { calcSum } from "@/plugins/utils";

export default {
  name: "course-weight-manage",
  props: {
    course: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      dataList: [],
      tableSetData: [],
      targetTotalWeight: {},
      evaluationData: [],
      loading: false,
    };
  },
  mounted() {
    // this.getList();
    this.dataList = weightList;
    this.transformData(this.dataList);
  },
  methods: {
    async getList() {
      const res = await courseWeightDetail(this.course.courseCode);
      this.dataList = res.submitForm || [];
      this.transformData(this.dataList);
    },
    transformData(data) {
      if (!data || !data.length) return [];

      const evaluationList = [];
      const evaluationMap = {};
      const targetTotalWeight = {};
      data[0].evaluation.forEach((item, index) => {
        evaluationMap[item.evaluationName] = index;
      });

      this.evaluationData = data[0].evaluation.map(
        (item) => item.evaluationName
      );

      data.forEach((target) => {
        targetTotalWeight[target.courseTargetId] = target.totalWeight;
        const targetData = {
          ...omit(target, ["evaluation"]),
          totalWeight: target.totalWeight || undefined,
        };

        target.evaluation.forEach((item) => {
          const index = evaluationMap[item.evaluationName];
          if (!evaluationList[index]) {
            evaluationList[index] = {
              evaluationName: item.evaluationName,
              targets: [],
            };
          }
          evaluationList[index].targets.push({
            ...targetData,
            used: item.used,
            weight: item.weight || undefined,
            targetScore: item.targetScore || undefined,
          });
        });
      });

      this.targetTotalWeight = targetTotalWeight;
      this.tableSetData = evaluationList;
    },
    usedChange(rowIndex, tindex) {
      const target = this.tableSetData[rowIndex].targets[tindex];
      if (!target.used) {
        target.weight = undefined;
        target.targetScore = undefined;
      }
    },
    getEvaluationSumScore(evaluation) {
      return calcSum(
        evaluation.map((item) => (item.used ? item.targetScore : 0))
      );
    },
    updateDataList() {
      const evaluationData = {};
      this.tableSetData.forEach((item) => {
        item.targets.forEach((elem) => {
          const key = `${item.evaluationName}_${elem.courseTargetId}`;
          evaluationData[key] = pick(elem, ["used", "weight", "targetScore"]);
        });
      });

      this.dataList.forEach((target) => {
        target.totalWeight = this.targetTotalWeight[target.courseTargetId];
        target.evaluation.forEach((item) => {
          const key = `${item.evaluationName}_${target.courseTargetId}`;
          Object.assign(item, evaluationData[key]);
        });
      });
    },
    checkDataList() {
      if (!this.dataList.length) return;
      //  TODO:

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

      if (!this.checkDataList()) return;

      this.loading = true;
      const res = await courseWeightSave({
        courseCode: this.course.courseCode,
        submitForm: this.dataList,
      }).catch(() => {});
      this.loading = false;
      if (!res) return;
      this.$message.success("保存成功！");
    },
  },
};
</script>
