<template>
  <div class="mark-paper-marker">
    <div class="mark-body">
      <div class="box-justify part-box part-box-pad">
        <div>
          <p class="tips-info">
            1.评卷过程中需要增加评卷员，可以在需要增加分组下绑定评卷员
          </p>
        </div>
        <div>
          <mark-status field="marker"></mark-status>
        </div>
      </div>

      <div class="part-box part-box-pad">
        <el-table :data="groupInfo" border>
          <el-table-column type="index" width="50"> </el-table-column>
          <el-table-column label="评卷员">
            <template slot-scope="scope">
              <el-tag
                v-for="user in scope.row.markerList"
                :key="user.id"
                class="tag-spin"
                size="medium"
              >
                {{ user.name }}（{{ user.orgName }}）
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="评阅题目">
            <template slot-scope="scope">
              {{ scope.row.questions | questionsFilter }}
            </template>
          </el-table-column>
          <el-table-column
            class-name="action-column"
            label="操作"
            width="160px"
          >
            <template slot-scope="scope">
              <el-button
                class="btn-primary"
                type="text"
                @click="toEdit(scope.row)"
                >编辑</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <mark-paper-class
        v-if="
          checkPrivilege('button', 'OpenClassReading', 'UploadStructure') &&
          dataReady
        "
        ref="MarkPaperClass"
        :datas="{
          groupInfo,
          classInfo: markParamInfos.classInfo,
          basicPaperInfo: markParamInfos.basicPaperInfo,
        }"
      ></mark-paper-class>
    </div>

    <div class="text-center mt-2">
      <el-button type="primary" :disabled="loading" @click="submit"
        >提交</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </div>

    <!-- ModifyMarkerQuestion -->
    <modify-marker-question
      ref="ModifyMarkerQuestion"
      :course-code="markParamInfos.basicPaperInfo.courseCode"
      :instance="curGroupInfo"
      :disabled-question-ids="disabledQuestionIds"
      :paper-structure="subjectiveQuestionList"
      :can-select-question="false"
      @modified="groupModified"
    ></modify-marker-question>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import ModifyMarkerQuestion from "./ModifyMarkerQuestion";
import MarkStatus from "./MarkStatus.vue";
import markPaperClass from "./markPaperClass.vue";
import { examBindMarker } from "../../api";

export default {
  name: "mark-paper-marker",
  components: { ModifyMarkerQuestion, MarkStatus, markPaperClass },
  data() {
    return {
      questionCount: 0,
      groupQuestionCount: 0,
      groupInfo: [],
      disabledQuestionIds: [],
      curGroupInfo: {},
      subjectiveQuestionList: [],
      subjectiveQuestionCount: 0,
      objectiveQuestionCount: 0,
      MARK_TYPE: {
        0: "单评",
        1: "双评",
      },
      paperList: [],
      cardPages: [],
      loading: false,
      dataReady: false,
    };
  },
  filters: {
    questionsFilter(val) {
      return val
        .map((item) => `${item.mainNumber}-${item.subNumber}`)
        .join(",");
    },
  },
  computed: {
    ...mapState("markParam", ["markParamInfos"]),
  },
  mounted() {
    this.initData();
  },
  methods: {
    ...mapMutations("markParam", ["setMarkParamInfos"]),
    initData() {
      this.groupInfo = this.markParamInfos.groupInfo.map((item, index) => {
        return { ...item, groupNumber: index + 1 };
      });
      this.questionCount = this.markParamInfos.paperStructureInfo.length;
      this.updateDisableQuestionIds();

      this.subjectiveQuestionList =
        this.markParamInfos.paperStructureInfo.filter(
          (item) => item.qType === "subjective"
        );
      this.subjectiveQuestionCount = this.subjectiveQuestionList.length;
      this.objectiveQuestionCount =
        this.questionCount - this.subjectiveQuestionCount;
      this.dataReady = true;
    },
    updateDisableQuestionIds(filterId) {
      let groupInfo = this.groupInfo;
      if (filterId)
        groupInfo = this.groupInfo.filter((item) => item.id !== filterId);
      let disabledQuestionIds = [];
      groupInfo.forEach((item) => {
        disabledQuestionIds = [
          ...disabledQuestionIds,
          ...item.questions.map((item) => item.id),
        ];
      });
      this.disabledQuestionIds = disabledQuestionIds;
      if (!filterId) this.groupQuestionCount = disabledQuestionIds.length;
    },
    updateGroupNumber() {
      this.groupInfo.forEach((group, index) => {
        group.groupNumber = index + 1;
      });
    },
    toEdit(row) {
      this.curGroupInfo = row;
      this.updateDisableQuestionIds(row.id);
      this.$refs.ModifyMarkerQuestion.open();
    },
    async groupModified(row) {
      const pos = this.groupInfo.findIndex((item) => item.id === row.id);
      if (pos === -1) return;
      this.groupInfo.splice(pos, 1, row);

      this.updateDisableQuestionIds();
      this.updateGroupNumber();

      // 分班阅卷相关
      this.$refs.MarkPaperClass && this.$refs.MarkPaperClass.groupChange();
    },
    async submit() {
      if (!this.checkData()) return;

      if (this.loading) return;
      this.loading = true;

      let datas = {
        paperStructureId: this.markParamInfos.basicPaperInfo.id,
        groupInfo: this.groupInfo,
      };
      if (this.$refs.MarkPaperClass) {
        const { openClassReading, classInfo } =
          this.$refs.MarkPaperClass.getData();
        datas.classInfo = classInfo;
        datas.openClassReading = openClassReading;
      }
      const res = await examBindMarker(datas).catch(() => {});
      this.loading = false;
      if (!res) return;

      let ndata = {
        groupInfo: this.groupInfo,
      };
      if (datas["classInfo"]) {
        ndata.classInfo = datas.classInfo;
        ndata.basicPaperInfo = Object.assign(
          this.markParamInfos.basicPaperInfo,
          {
            openClassReading: datas.openClassReading,
          }
        );
      }
      this.setMarkParamInfos(ndata);
      this.$message.success("提交成功！");
      this.$emit("confirm");
    },
    checkData() {
      let errorMessages = [];

      if (this.subjectiveQuestionCount > this.groupQuestionCount) {
        errorMessages.push("当前还有题目未设置评卷员");
      }

      // if (this.$refs.MarkPaperClass) {
      //   errorMessages.push(...this.$refs.MarkPaperClass.checkData());
      // }
      if (errorMessages.length) {
        this.$message.error(errorMessages.join("。"));
        return;
      }

      return true;
    },
    cancel() {
      this.$emit("cancel");
    },
  },
};
</script>
