<template>
  <div class="mark-paper-structure">
    <p class="structure-desc">
      <span>课程名称：</span>
      <span class="mr-4">{{ datas.basicPaperInfo.courseName }}</span>
      <span>课程代码：</span>
      <span>{{ datas.basicPaperInfo.courseCode }}</span>
    </p>
    <el-table
      ref="TableList"
      :data="tableData"
      border
      :row-class-name="getRowClassName"
    >
      <el-table-column width="50" align="center">
        <template slot-scope="scope" v-if="scope.row.mainFirstSub">
          <div
            :class="[
              'expand-btn',
              { 'expand-btn-unexpand': !scope.row.expandSub },
            ]"
            @click="switchExpandSub(scope.row)"
          >
            <i
              :class="scope.row.expandSub ? 'el-icon-minus' : 'el-icon-plus'"
            ></i>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="mainTitle" label="大题名称">
        <span slot-scope="scope" v-if="scope.row.mainFirstSub">
          {{ scope.row.mainTitle }}
        </span>
      </el-table-column>
      <el-table-column prop="typeName" label="题型" width="160">
        <template slot-scope="scope" v-if="scope.row.mainFirstSub">
          {{ scope.row.typeName }}
        </template>
      </el-table-column>
      <el-table-column label="每题分值" width="160">
        <template slot-scope="scope" v-if="scope.row.mainFirstSub">
          <el-input-number
            v-model="scoresPerTopic[scope.row.mainId]"
            class="width-80"
            size="small"
            :min="0.5"
            :max="500"
            :step="0.5"
            step-strictly
            :controls="false"
            @change="(val) => scorePerTopicChange(val, scope.row)"
          ></el-input-number>
        </template>
      </el-table-column>
      <el-table-column prop="mainNumber" label="大题号" width="80">
        <template slot-scope="scope" v-if="scope.row.mainFirstSub">
          <span>{{ scope.row.mainNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="subNumber"
        label="小题号"
        width="80"
      ></el-table-column>
      <el-table-column prop="totalScore" label="小题满分" width="105">
        <template slot-scope="scope">
          <el-input-number
            v-model="scope.row.totalScore"
            class="width-80"
            size="small"
            :min="0.5"
            :max="500"
            :step="0.5"
            step-strictly
            :controls="false"
          ></el-input-number>
        </template>
      </el-table-column>
    </el-table>
    <div class="total-info">
      试卷总分：<span>{{ paperTotalScore }}</span
      >分
    </div>
  </div>
</template>

<script>
import { calcSum } from "@/plugins/utils";

export default {
  name: "mark-paper-structure",
  props: {
    datas: {
      type: Object,
      default() {
        return {
          basicPaperInfo: {},
          paperStructureInfo: [],
          groupInfo: [],
        };
      },
    },
  },
  data() {
    return {
      tableData: [],
      Q_TYPE: {
        objective: "客观题",
        subjective: "主观题",
      },
      scoresPerTopic: {},
    };
  },
  computed: {
    paperTotalScore() {
      return calcSum(this.tableData.map((item) => item.totalScore || 0));
    },
  },
  mounted() {
    this.initData();
  },
  methods: {
    initData() {
      let curMainId = null;
      let scoresPerTopic = {};
      this.tableData = this.datas.paperStructureInfo.map((item) => {
        if (curMainId !== item.mainId) {
          curMainId = item.mainId;
          scoresPerTopic[curMainId] = undefined;
        }
        return { ...item };
      });
      this.scoresPerTopic = scoresPerTopic;

      this.$emit("on-ready");
    },
    createMain() {
      this.tableData.push({
        id: this.$randomCode(),
        qType: "objective",
        mainId: this.$randomCode(),
        mainTitle: "",
        mainNumber: 1,
        subNumber: 1,
        totalScore: undefined,
        mainFirstSub: true,
        expandSub: true,
      });
    },
    getRowClassName({ row }) {
      let classNames = [];
      if (row.mainFirstSub) {
        classNames.push("row-main-first-sub");
      }
      if (!row.mainFirstSub && !row.expandSub) {
        classNames.push("row-unexpand-sub");
      }
      return classNames.join(" ");
    },
    getNextMainStartPos(startPos, curMainId) {
      let nextMainStartPos = null;
      for (let i = startPos, len = this.tableData.length; i < len; i++) {
        const element = this.tableData[i];
        if (element.mainId !== curMainId) {
          nextMainStartPos = i;
          return nextMainStartPos;
        }
      }
      if (nextMainStartPos === null) return this.tableData.length;
    },
    toAddMain(row) {
      const startPos = this.tableData.findIndex((item) => item.id === row.id);
      let nextMainStartPos = this.getNextMainStartPos(startPos, row.mainId);
      this.tableData.splice(nextMainStartPos, 0, {
        id: this.$randomCode(),
        qType: row.qType,
        mainId: this.$randomCode(),
        mainTitle: "",
        mainNumber: row.mainNumber + 1,
        subNumber: 1,
        totalScore: row.totalScore,
        mainFirstSub: true,
        expandSub: true,
      });
      this.updateMainData();
    },
    updateMainData() {
      let curMainNumber = 0,
        curMainId = null;
      this.tableData.forEach((item) => {
        if (item.mainId !== curMainId) {
          curMainId = item.mainId;
          curMainNumber++;
        }
        item.mainNumber = curMainNumber;
      });
    },
    toAddSub(row) {
      const subPos = this.tableData.findIndex((item) => item.id === row.id);
      this.tableData.splice(subPos + 1, 0, {
        id: this.$randomCode(),
        qType: row.qType,
        mainId: row.mainId,
        mainTitle: row.mainTitle,
        mainNumber: row.mainNumber,
        subNumber: row.subNumber + 1,
        totalScore: row.totalScore,
        mainFirstSub: false,
        expandSub: row.expandSub,
      });
      this.updateSubData(row.mainId);
    },
    updateSubData(mainId) {
      this.tableData
        .filter((item) => item.mainId === mainId)
        .forEach((item, index) => {
          item.subNumber = index + 1;
        });
    },
    toDeleteSub(row) {
      const subPos = this.tableData.findIndex((item) => item.id === row.id);
      this.tableData.splice(subPos, 1);

      this.tableData
        .filter((item) => item.mainId === row.mainId)
        .forEach((item, index) => {
          item.mainFirstSub = !index;
        });
      this.updateSubData(row.mainId);
      this.updateMainData();
    },
    switchExpandSub(row) {
      row.expandSub = !row.expandSub;
      this.tableData
        .filter((item) => item.mainId === row.mainId && !item.mainFirstSub)
        .forEach((item) => (item.expandSub = row.expandSub));
    },
    mainTitleChange(row) {
      this.tableData
        .filter((item) => item.mainId === row.mainId && !item.mainFirstSub)
        .forEach((item) => (item.mainTitle = row.mainTitle));
    },
    qTypeChange(row) {
      this.tableData
        .filter((item) => item.mainId === row.mainId && !item.mainFirstSub)
        .forEach((item) => (item.qType = row.qType));
    },
    scorePerTopicChange(val, row) {
      if (!val) return;
      this.tableData
        .filter((item) => item.mainId === row.mainId)
        .forEach((item) => (item.totalScore = val));
    },
    checkData() {
      // if (
      //   this.tableData.some(item => item.qType === "objective") &&
      //   this.tableData[0].qType !== "objective"
      // ) {
      //   this.$message.error("请保持客观题在前，主观题在后！");
      //   return;
      // }

      // const objectiveNos = this.tableData
      //   .filter(item => item.mainFirstSub && item.qType === "objective")
      //   .map(item => item.mainNumber);
      // const unValid = objectiveNos.some(
      //   (no, index) => objectiveNos[0] + index !== no
      // );
      // if (unValid) {
      //   this.$message.error("请保持主客观题题号连续");
      //   return;
      // }

      let errorMessages = [];
      this.tableData.forEach((item) => {
        let errorMsg = ``;
        if (item.mainFirstSub) {
          let errorFields = [];
          if (!item.mainTitle) {
            errorFields.push("大题名称");
          }
          if (!item.mainNumber) {
            errorFields.push("大题号");
          }
          if (errorFields.length) {
            errorMsg += `${errorFields.join("、")}不能为空，`;
          }
        }

        let errorFields = [];
        if (!item.subNumber) {
          errorFields.push("小题号");
        }
        if (!item.totalScore) {
          errorFields.push("小题满分");
        }
        if (errorFields.length) {
          errorMsg += `第${item.subNumber}小题，${errorFields.join(
            "、"
          )}不能为空，`;
        }

        if (errorMsg) {
          errorMsg = `第${item.mainNumber}大题，${errorMsg}`;
          errorMessages.push(errorMsg);
        }
      });

      if (errorMessages.length) {
        this.$message.error(errorMessages.join("。"));
        return;
      }

      this.updateData();
      this.$emit("next-step");
    },
    getData() {
      return this.tableData.map((item) => {
        return { ...item };
      });
    },
    updateData() {
      this.$emit("data-change", {
        paperStructureInfo: this.getData(),
      });
    },
  },
};
</script>
