<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.isMainFirstSub">
          <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.isMainFirstSub">
          <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="qType" label="类型" width="160">
        <template slot-scope="scope" v-if="scope.row.isMainFirstSub">
          <el-radio-group
            v-model="scope.row.qType"
            size="mini"
            @change="qTypeChange(scope.row)"
          >
            <el-radio-button
              v-for="(val, key) in Q_TYPE"
              :key="key"
              :label="key"
              >{{ val }}</el-radio-button
            >
          </el-radio-group>
        </template>
      </el-table-column>
      <el-table-column prop="mainNumber" label="大题号" width="80">
        <template slot-scope="scope" v-if="scope.row.isMainFirstSub">
          <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 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 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: "主观题"
      }
    };
  },
  computed: {
    paperTotalScore() {
      return calcSum(this.tableData.map(item => item.totalScore || 0));
    }
  },
  mounted() {
    this.initData();
  },
  methods: {
    initData() {
      this.tableData = this.datas.paperStructureInfo.map(item => {
        return { ...item };
      });
      if (!this.tableData.length) {
        this.createMain();
      }

      this.$emit("on-ready");
    },
    createMain() {
      this.tableData.push({
        id: this.$randomCode(),
        qType: "objective",
        mainId: this.$randomCode(),
        mainTitle: "",
        mainNumber: 1,
        subNumber: 1,
        totalScore: undefined,
        isMainFirstSub: true,
        expandSub: true
      });
    },
    getRowClassName({ row }) {
      let classNames = [];
      if (row.isMainFirstSub) {
        classNames.push("row-main-first-sub");
      }
      if (!row.isMainFirstSub && !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,
        isMainFirstSub: 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,
        isMainFirstSub: 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.isMainFirstSub = !index;
        });
      this.updateSubData(row.mainId);
      this.updateMainData();
    },
    switchExpandSub(row) {
      row.expandSub = !row.expandSub;
      this.tableData
        .filter(item => item.mainId === row.mainId && !item.isMainFirstSub)
        .forEach(item => (item.expandSub = row.expandSub));
    },
    mainTitleChange(row) {
      this.tableData
        .filter(item => item.mainId === row.mainId && !item.isMainFirstSub)
        .forEach(item => (item.mainTitle = row.mainTitle));
    },
    qTypeChange(row) {
      this.tableData
        .filter(item => item.mainId === row.mainId && !item.isMainFirstSub)
        .forEach(item => (item.qType = row.qType));
    },
    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.isMainFirstSub && 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.isMainFirstSub) {
          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>
