<template>
  <el-dialog
    class="modify-objective-answer modify-mark-params"
    :visible.sync="modalIsShow"
    top="0"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    append-to-body
    fullscreen
    destroy-on-close
    @open="visibleChange"
  >
    <div class="box-justify" slot="title">
      <h2 class="el-dialog__title">
        设置客观题标答
        <span>-{{ instance.courseName }}（{{ instance.courseCode }}）</span>
      </h2>
      <div>
        <el-button type="success" :disabled="isSubmit" @click="submit"
          >确定</el-button
        >
        <el-button @click="cancel">取消</el-button>
      </div>
    </div>

    <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">
          {{ scope.row.mainTitle }}
        </span>
      </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">
      </el-table-column>
      <el-table-column label="答案" width="200px">
        <template slot-scope="scope">
          <el-input
            v-model.trim="scope.row.answer"
            placeholder="请输入答案"
            maxlength="16"
            clearable
          ></el-input>
        </template>
      </el-table-column>
    </el-table>

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

<script>
import { updateObjectiveAnswer } from "../../api";

export default {
  name: "modify-objective-answer",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      tableData: []
    };
  },
  methods: {
    initData() {
      let objectiveStructure = JSON.parse(
        this.instance.objectiveStructure || "[]"
      );
      objectiveStructure.sort((a, b) => {
        if (a.mainNumber === b.mainNumber) {
          return a.subNumber - b.subNumber;
        } else {
          return a.mainNumber - b.mainNumber;
        }
      });

      let curMainNumber = null,
        curMainId = null;
      this.tableData = objectiveStructure.map(item => {
        let nitem = { ...item };
        if (nitem.mainNumber !== curMainNumber) {
          curMainId = this.$randomCode();
          curMainNumber = nitem.mainNumber;
          nitem.isMainFirstSub = true;
        }
        nitem.id = this.$randomCode();
        nitem.mainId = curMainId;
        nitem.expandSub = true;
        nitem.answer = item.answer || "";
        return nitem;
      });
    },
    visibleChange() {
      this.initData();
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = 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(" ");
    },
    switchExpandSub(row) {
      row.expandSub = !row.expandSub;
      this.tableData
        .filter(item => item.mainId === row.mainId && !item.isMainFirstSub)
        .forEach(item => (item.expandSub = row.expandSub));
    },
    checkData() {
      let errorMessages = [];
      this.tableData.forEach(item => {
        let errorMsg = "";
        if (item.answer) {
          if (!/^[A-Z]{1,26}$/.test(item.answer)) {
            errorMsg += `答案只能输入英文大写字母`;
          } else {
            const ansSet = new Set(item.answer.split(""));
            if (ansSet.size !== item.answer.length) {
              errorMsg += `答案不能重复`;
            }
          }
        } else {
          errorMsg += `答案不能为空`;
        }

        if (errorMsg) {
          errorMessages.push(
            `第${item.mainNumber}大题，第${item.subNumber}小题，${errorMsg}`
          );
        }
      });
      if (errorMessages.length) {
        this.$message.error(errorMessages.join("。"));
        return;
      }

      return true;
    },
    async submit() {
      if (!this.checkData()) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      const datas = {
        id: this.instance.id,
        objectiveStructure: this.tableData
      };
      const data = await updateObjectiveAnswer(datas).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

      this.$message.success("编辑成功！");
      this.$emit("modified");
      this.cancel();
    }
  }
};
</script>
