<template>
  <div class="mark-paper-structure">
    <div class="box-justify part-box part-box-pad">
      <div>
        <p class="tips-info">
          1.请确认展示的试卷结构与提交的试卷、答题卡是否一致？
        </p>
        <p class="tips-info">2.请补充所有题目的小题分值，并确认试卷总分！</p>
        <p class="tips-info tips-error">
          3.开始阅卷后不允许修改试卷结构，请确认清楚后再提交！
        </p>
      </div>
      <div>
        <mark-status field="structure"></mark-status>
      </div>
    </div>

    <div class="part-box part-box-pad mb-0">
      <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>
        <template v-if="structureCanEdit">
          <el-table-column prop="mainTitle" label="大题名称">
            <span slot-scope="scope" v-if="scope.row.mainFirstSub">
              <el-input
                v-model.trim="scope.row.mainTitle"
                size="small"
                :maxlength="32"
                clearable
                @change="mainTitleChange(scope.row)"
              ></el-input>
            </span>
          </el-table-column>
          <el-table-column prop="type" label="题型" width="120">
            <template slot-scope="scope" v-if="scope.row.mainFirstSub">
              <el-select
                v-model="scope.row.type"
                placeholder="请选择"
                class="width-full"
                @change="qTypeChange(scope.row)"
              >
                <el-option
                  v-for="item in QUESTION_TYPE_LIST"
                  :key="item.code"
                  :value="item.code"
                  :label="item.name"
                >
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="选项个数" width="100">
            <template
              slot-scope="scope"
              v-if="scope.row.type <= 2 && scope.row.mainFirstSub"
            >
              <el-input-number
                v-model="scope.row.optionCount"
                class="width-full"
                size="small"
                :min="2"
                :max="26"
                :step="1"
                step-strictly
                :controls="false"
                @change="optionCountChange(scope.row)"
              ></el-input-number>
            </template>
          </el-table-column>
        </template>
        <template v-else>
          <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="120">
            <template slot-scope="scope" v-if="scope.row.mainFirstSub">
              {{ scope.row.typeName }}
            </template>
          </el-table-column>
        </template>
        <el-table-column label="每题分值" width="100">
          <template slot-scope="scope" v-if="scope.row.mainFirstSub">
            <el-input-number
              v-model="scoresPerTopic[scope.row.mainId]"
              class="width-full"
              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-column
          v-if="structureCanEdit"
          class-name="action-column"
          label="操作"
          width="200px"
        >
          <template slot-scope="scope">
            <el-button
              class="btn-primary"
              type="text"
              @click="toAddMain(scope.row)"
              >新增大题</el-button
            >
            <el-button
              class="btn-primary"
              type="text"
              @click="toAddSub(scope.row)"
              >新增小题</el-button
            >
            <el-button
              :disabled="tableData.length <= 1"
              class="btn-danger"
              type="text"
              @click="toDeleteSub(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="total-info">
      试卷总分：<span>{{ paperTotalScore }}</span
      >分
    </div>
  </div>
</template>

<script>
import { calcSum } from "@/plugins/utils";
import { QUESTION_TYPE_LIST } from "@/constants/enumerate";
import MarkStatus from "./MarkStatus.vue";

export default {
  name: "mark-paper-structure",
  components: { MarkStatus },
  props: {
    datas: {
      type: Object,
      default() {
        return {
          structureCanEdit: true,
          basicPaperInfo: {},
          paperStructureInfo: [],
          groupInfo: [],
        };
      },
    },
  },
  data() {
    return {
      tableData: [],
      QUESTION_TYPE_LIST,
      Q_TYPE: {
        objective: "客观题",
        subjective: "主观题",
      },
      scoresPerTopic: {},
    };
  },
  computed: {
    paperTotalScore() {
      return calcSum(this.tableData.map((item) => item.totalScore || 0));
    },
    structureCanEdit() {
      return !!this.datas.structureCanEdit;
    },
  },
  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;

      if (!this.tableData.length && this.structureCanEdit) {
        this.createMain();
      }

      this.$emit("on-ready");
    },
    createMain() {
      this.tableData.push({
        id: this.$randomCode(),
        qType: "objective",
        mainId: this.$randomCode(),
        mainTitle: "",
        mainNumber: 1,
        subNumber: 1,
        type: null,
        typeName: "",
        optionCount: undefined,
        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,
        type: null,
        typeName: "",
        optionCount: undefined,
        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,
        type: row.type,
        typeName: row.typeName,
        optionCount: row.optionCount,
        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) {
      const curQt = this.QUESTION_TYPE_LIST.find(
        (item) => item.code === row.type
      );
      if (!curQt) return;

      this.tableData
        .filter((item) => item.mainId === row.mainId)
        .forEach((item) => {
          item.type = curQt.code;
          item.typeName = curQt.name;
          item.qType = curQt.qType;
          item.optionCount = curQt.optionCount;
        });
    },
    optionCountChange(row) {
      if (!row.optionCount) return;

      this.tableData
        .filter((item) => item.mainId === row.mainId && !item.mainFirstSub)
        .forEach((item) => {
          item.optionCount = row.optionCount;
        });
    },
    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 (!item.optionCount && item.type <= 2) {
            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>
