<template>
  <div class="part-box part-box-pad course-matrix">
    <el-table
      :data="dataList"
      border
      :cell-style="cellStyleHandle"
      :summary-method="getSummaries"
      show-summary
    >
      <el-table-column label="课程信息" align="center" fixed="left" width="300">
        <el-table-column
          label="课程名称（代码）"
          width="240"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            {{ scope.row.courseName }}（{{ scope.row.courseCode }}）
          </template>
        </el-table-column>
        <el-table-column
          label="学分"
          prop="credit"
          width="60"
          align="center"
        ></el-table-column>
      </el-table-column>
      <el-table-column label="毕业要求" align="center">
        <template v-if="hasSubRequirements">
          <el-table-column
            v-for="(column, cindex) in columns"
            :key="cindex"
            :label="column.name"
            align="center"
          >
            <el-table-column
              v-for="subr in column.subRequirements"
              :key="subr.name"
              align="center"
              :prop="`${column.name}_${subr.name}`"
            >
              <template slot="header">
                <span v-if="subr.name === 'null'"></span>
                <template v-else>
                  <span>{{ subr.name }}</span>
                  <el-tooltip v-if="subr.content" effect="dark" placement="top">
                    <div slot="content" class="tooltip-area">
                      {{ subr.content }}
                    </div>
                    <i class="el-icon-info ml-1 tooltip-info-icon"></i>
                  </el-tooltip>
                </template>
              </template>
              <template slot-scope="scope">
                <el-input-number
                  v-if="scope.row.canEdit"
                  v-model="scope.row[`${column.name}_${subr.name}`].value"
                  class="width-50"
                  :min="0"
                  :max="1"
                  :step="0.01"
                  step-strictly
                  :controls="false"
                  size="mini"
                  @change="
                    () =>
                      unitChange(
                        scope.row,
                        `${column.name}_${subr.name}`,
                        subr.columnIndex
                      )
                  "
                ></el-input-number>
                <span v-else>{{
                  scope.row[`${column.name}_${subr.name}`].value
                }}</span>
              </template>
            </el-table-column>
          </el-table-column>
        </template>

        <template v-else>
          <el-table-column
            v-for="(column, cindex) in columns"
            :key="cindex"
            :label="column.name"
            align="center"
            :prop="`${column.name}_null`"
          >
            <template slot-scope="scope">
              <el-input-number
                v-if="scope.row.canEdit"
                v-model="scope.row[`${column.name}_null`].value"
                class="width-50"
                :min="0"
                :max="1"
                :step="0.01"
                step-strictly
                :controls="false"
                size="mini"
                @change="
                  () =>
                    unitChange(
                      scope.row,
                      `${column.name}_null`,
                      column.columnIndex
                    )
                "
              ></el-input-number>
              <span v-else>{{ scope.row[`${column.name}_null`].value }}</span>
            </template>
          </el-table-column>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import {
  trainingPlanCourseMatrixDetail,
  trainingPlanCourseMatrixSave,
} from "../../api";
import { calcSum } from "@/plugins/utils";

export default {
  name: "training-plan-course-matrix",
  props: {
    rowData: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      dataList: [],
      columns: [],
      hasSubRequirements: false,
      loading: false,
      errorIndexs: [],
      warningColumnIndexs: [],
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    async getList() {
      const res = await trainingPlanCourseMatrixDetail({
        cultureProgramId: this.rowData.id,
      });
      const tableData = res || [];
      this.dataList = tableData.map((item, index) => {
        if (!index) this.parseColumns(item.requirements);

        const nitem = {
          courseId: item.courseId,
          courseCode: item.courseCode,
          courseName: item.courseName,
          canEdit: item.canEdit,
        };
        item.requirements.forEach((requirement) => {
          requirement.subRequirements.forEach((subr) => {
            nitem[`${requirement.name}_${subr.name + ""}`] = {
              id: subr.id,
              value: subr.scale || undefined,
            };
          });
        });

        return nitem;
      });
      this.initWarningColumnIndexs();
    },
    parseColumns(requirements) {
      this.hasSubRequirements = requirements.some(
        (item) => item.subRequirements[0].name !== null
      );
      if (!this.hasSubRequirements) {
        this.columns = requirements.map((item, index) => {
          return { name: item.name, columnIndex: index + 1 };
        });
        return;
      }

      let cindex = 1;
      this.columns = requirements.map((item) => {
        return {
          name: item.name,
          subRequirements: item.subRequirements.map((subr) => {
            return {
              name: subr.name + "",
              columnIndex: ++cindex,
              content: subr.content,
            };
          }),
        };
      });
    },
    updateErrorIndexs([rowIndex, columnIndex]) {
      const pos = this.errorIndexs.findIndex((item) => item[1] === columnIndex);
      if (pos !== -1) {
        this.errorIndexs.splice(pos, 1);
      }

      this.errorIndexs.push([rowIndex, columnIndex]);
    },
    clearErrorIndexs(columnIndex) {
      this.errorIndexs = this.errorIndexs.filter(
        (item) => item[1] !== columnIndex
      );
    },
    initWarningColumnIndexs() {
      const warningColumnIndexs = [];
      this.columns.forEach((column) => {
        column.subRequirements.forEach((subr) => {
          const key = `${column.name}_${subr.name}`;
          const totalVal = calcSum(
            this.dataList.map((item) =>
              item[key].value ? Math.floor(item[key].value * 100) : 0
            )
          );
          if (totalVal < 100) warningColumnIndexs.push(subr.columnIndex);
        });
      });
      this.warningColumnIndexs = warningColumnIndexs;
    },
    updateWarningColumnIndexs(columnIndex, type) {
      const pos = this.warningColumnIndexs.findIndex(
        (item) => item === columnIndex
      );
      if (pos !== -1) {
        if (type === "remove") {
          this.warningColumnIndexs.splice(pos, 1);
        }
      } else {
        if (type === "add") {
          this.warningColumnIndexs.push(columnIndex);
        }
      }
    },
    async unitChange(row, key, columnIndex) {
      const [fieldName, nodeName] = key.split("_");
      const totalVal = calcSum(
        this.dataList.map((item) =>
          item[key].value ? Math.floor(item[key].value * 100) : 0
        )
      );
      if (totalVal < 100) {
        this.updateWarningColumnIndexs(columnIndex, "add");
      } else {
        this.updateWarningColumnIndexs(columnIndex, "remove");
      }

      if (totalVal > 100) {
        const columnName =
          nodeName === "null" ? fieldName : `${fieldName}:${nodeName}`;
        this.$message.error(`${columnName}列总和大于1，当前修改值将不会保存！`);

        const rowIndex = this.dataList.findIndex(
          (item) => item.courseCode === row.courseCode
        );

        this.updateErrorIndexs([rowIndex, columnIndex]);
        return;
      }

      let saveData = [];
      const curColumnHasError = this.errorIndexs.some(
        (item) => item[1] === columnIndex
      );
      if (curColumnHasError) {
        saveData = this.dataList.map((item) => {
          return {
            id: item[key].id,
            scale: item[key].value,
          };
        });
      } else {
        saveData = [
          {
            id: row[key].id,
            scale: row[key].value,
          },
        ];
      }

      this.clearErrorIndexs(columnIndex);
      await trainingPlanCourseMatrixSave(saveData);
    },
    cellStyleHandle({ rowIndex, columnIndex }) {
      let style = undefined;
      if (this.warningColumnIndexs.includes(columnIndex)) {
        style = {
          backgroundColor: "#fdecdc",
        };
      }
      if (!this.errorIndexs.length) return style;

      if (
        this.errorIndexs.some(
          (item) => rowIndex === item[0] && columnIndex === item[1]
        )
      ) {
        style = {
          backgroundColor: "#fde2e2",
        };
      }

      return style;
    },

    // spanMethod({ rowIndex, columnIndex }) {
    //   if (rowIndex === 0 && columnIndex === 0) {
    //     return { rowspan: 2, colspan: this.hasSubRequirements ? 2 : 1 };
    //   }
    // },
    getSummaries(param) {
      const { columns } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        if (index === 1) {
          sums[index] = "";
          return;
        }

        const total = calcSum(
          this.dataList.map((item) =>
            item[column.property].value ? item[column.property].value * 100 : 0
          )
        );
        sums[index] = (total / 100).toFixed(2);
      });
      return sums;
    },
  },
};
</script>
