<template>
  <el-dialog
    class="page-dialog"
    :visible.sync="modalIsShow"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    fullscreen
    @opened="openedHandle"
  >
    <div slot="title">{{ rowData.studentName }}毕业要求达成情况</div>

    <div class="part-box part-box-pad">
      <div class="part-box-head">
        <h3>个人与本院对比情况</h3>
      </div>
      <div class="chart-box" style="height: 360px">
        <v-chart v-if="chartOption" :option="chartOption" autoresize></v-chart>
      </div>
    </div>

    <div class="part-box part-box-pad">
      <div class="part-box-head">
        <h3>个人毕业要求达成度情况</h3>
      </div>

      <el-form ref="FilterForm" label-position="left" inline>
        <el-form-item label-width="0px">
          <semester-select
            v-model="filter.semesterId"
            :style="{ width: '220px' }"
          ></semester-select>
        </el-form-item>
        <el-form-item label-width="0px">
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>
      </el-form>

      <el-table
        ref="TableList"
        :data="dataList"
        border
        :span-method="spanMethod"
        :max-height="600"
      >
        <el-table-column
          label="课程名称（代码）"
          width="240"
          show-overflow-tooltip
          fixed="left"
        >
          <template slot-scope="scope">
            <span>
              {{ scope.row.courseName }}
            </span>
            <span v-if="scope.row.courseCode">
              （{{ scope.row.courseCode }}）
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="semesterName"
          label="所属学期"
          width="200"
          fixed="left"
        >
        </el-table-column>
        <el-table-column
          prop="score"
          label="综合成绩"
          width="85"
          align="center"
          fixed="left"
        >
        </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, sindex) in column.subRequirements"
                :key="sindex"
                align="center"
                min-width="75"
              >
                <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">
                  {{
                    scope.row.requirementDetailList[cindex]
                      .subRequirementDetailList[sindex].studentDegree
                      | defaultFieldFilter
                  }}
                </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"
              min-width="60"
            >
              <template slot-scope="scope">
                {{
                  scope.row.requirementDetailList[cindex].studentDegree
                    | defaultFieldFilter
                }}
              </template>
            </el-table-column>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div slot="footer"></div>
  </el-dialog>
</template>

<script>
import {
  splitContent,
  calcSum,
  minNum,
  toPrecision,
  listFilterEmpty,
} from "@/plugins/utils";
import { studentTargetDetail } from "../../api";

export default {
  name: "detail-requirement-statistics",
  props: {
    rowData: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      chartData: [],
      chartOption: null,
      filter: { semesterId: "" },
      columns: [],
      dataList: [],
      hasSubRequirements: false,
      rowCount: 0,
      totalRowColMap: {},
    };
  },
  methods: {
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    openedHandle() {
      this.search();
    },
    async search() {
      const res = await studentTargetDetail({
        cultureProgramId: this.rowData.cultureProgramId,
        studentCode: this.rowData.studentCode,
        ...this.filter,
      });
      this.chartData = res.studentTotalRequirementList || [];

      this.dataList = res.studentCourseRequirementList || [];
      if (this.dataList[0])
        this.parseColumns(this.dataList[0].requirementDetailList);

      this.updateTotalInfo();
      this.rowCount = this.dataList.length;

      this.updateChartOption();
    },
    parseColumns(requirements) {
      this.hasSubRequirements = requirements.some(
        (item) => item.subRequirementDetailList[0].name !== null
      );
      if (!this.hasSubRequirements) {
        this.columns = requirements.map((item) => {
          return { name: item.requirementName };
        });
        return;
      }

      this.columns = requirements.map((item) => {
        return {
          name: item.requirementName,
          subRequirements: item.subRequirementDetailList.map((subr) => {
            return {
              name: subr.requirementName,
              content: subr.requirementContent,
            };
          }),
        };
      });
    },
    updateTotalInfo() {
      const totalRowColMap = {};
      let columnIndex = 3;
      const totalObeRequirements = this.columns.map((column, cindex) => {
        const subRequirementDetailList = column.subRequirements.map(
          (subr, sindex) => {
            const dList = listFilterEmpty(
              this.dataList.map(
                (item) =>
                  item.requirementDetailList[cindex].subRequirementDetailList[
                    sindex
                  ].studentDegree
              )
            );
            const studentDegree = dList.length
              ? toPrecision(calcSum(dList), 2)
              : null;

            return {
              name: subr.name,
              studentDegree,
            };
          }
        );
        totalRowColMap[columnIndex] = column.subRequirements.length;
        columnIndex += column.subRequirements.length;

        const validVals = listFilterEmpty(
          subRequirementDetailList.map((subr) => subr.studentDegree)
        );
        const minStudentDegree = validVals.length ? minNum(validVals) : null;
        // 更新图表中个人达成情况
        this.chartData[cindex].studentDegree = minStudentDegree || 0;

        return {
          name: column.name,
          subRequirementDetailList,
          studentDegree: minStudentDegree,
        };
      });
      this.totalRowColMap = totalRowColMap;

      const totalRequirementColumn = {
        courseName: "毕业要求指标达成度",
        semesterName: "",
        credit: "",
        requirementDetailList: totalObeRequirements,
      };
      this.dataList.push(totalRequirementColumn);

      const totalColumn = {
        courseName: "毕业要求达成度",
        semesterName: "",
        credit: "",
        requirementDetailList: totalObeRequirements.map((item) => {
          const nitem = { ...item };
          nitem.subRequirementDetailList = item.subRequirementDetailList.map(
            (elem, eindex) => {
              const nelem = { ...elem };
              nelem.studentDegree = item.studentDegree;
              return nelem;
            }
          );
          return nitem;
        }),
      };
      this.dataList.push(totalColumn);
    },
    spanMethod({ rowIndex, columnIndex, column }) {
      if (rowIndex === this.rowCount - 2) {
        if (columnIndex === 0) {
          return { rowspan: 1, colspan: 3 };
        } else if (columnIndex <= 2) {
          return [0, 0];
        }
      }

      if (rowIndex === this.rowCount - 1) {
        if (columnIndex === 0) {
          return { rowspan: 1, colspan: 3 };
        } else if (columnIndex <= 2) {
          return [0, 0];
        } else {
          return this.totalRowColMap[columnIndex]
            ? [1, this.totalRowColMap[columnIndex]]
            : [0, 0];
        }
      }
    },
    updateChartOption() {
      const option = {
        color: ["#3a5ae5", "#fe5d4e"],
        tooltip: { show: true },
        grid: {
          left: 30,
          top: 60,
          right: 20,
          bottom: 20,
          containLabel: true,
        },
        legend: {
          top: 0,
          data: ["个人达成情况", "专业达成情况"],
          itemWidth: 16,
          itemHeight: 4,
          itemGap: 22,
          left: 30,
          textStyle: {
            fontSize: 14,
          },
        },
        xAxis: {
          type: "category",
          nameTextStyle: {
            color: "#363D59",
          },
          data: this.chartData.map((item) => item.requirementName),
          axisLabel: {
            color: "#6F7482",
            interval: 0,
            fontSize: 14,
            formatter: function (value, index) {
              const vals = splitContent(value, 6);
              vals[0] = `${index + 1}.${vals[0]} `;
              return vals.join("\n");
            },
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: "#EFF0F5",
            },
          },
          splitLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          axisPointer: {
            type: "shadow",
          },
        },
        yAxis: {
          type: "value",
          min: 0,
          max: 1,
          interval: 0.1,
          nameTextStyle: {
            color: "#363D59",
          },
          axisLabel: {
            color: "#6F7482",
          },
          axisLine: {
            lineStyle: {
              color: "#EFF0F5",
            },
          },
          splitLine: {
            lineStyle: {
              color: "#EFF0F5",
            },
          },
        },
        series: [
          {
            name: "个人达成情况",
            type: "bar",
            barWidth: 20,
            data: this.chartData.map((item) => item.studentDegree),
          },
          {
            name: "专业达成情况",
            type: "bar",
            barWidth: 20,
            data: this.chartData.map((item) => item.professionalDegree),
          },
        ],
      };

      this.chartOption = option;
    },
  },
};
</script>
