<template>
  <div class="mark-paper-marker">
    <div class="marker-header">
      <p
        class="marker-desc color-danger"
        v-if="subjectiveQuestionCount > groupQuestionCount"
      >
        本试卷共<span class="mlr-1">{{ questionCount }}</span
        >道小题，客观题<span class="mlr-1">{{ objectiveQuestionCount }}</span
        >道，主观题<span class="mlr-1">{{ subjectiveQuestionCount }}</span
        >道，已经设置<span class="mlr-1">{{ groupQuestionCount }}</span
        >道主观题，还有<span class="mlr-1">{{
          subjectiveQuestionCount - groupQuestionCount
        }}</span
        >道主观题未设置评卷员，请继续设置，确保全部主观题均已分配评卷员！
      </p>
      <p class="marker-desc color-success" v-else>
        本试卷共<span class="mlr-1">{{ questionCount }}</span
        >道小题，客观题<span class="mlr-1">{{ objectiveQuestionCount }}</span
        >道，主观题<span class="mlr-1">{{ subjectiveQuestionCount }}</span
        >道，主观题已全部设置评卷员！
      </p>
      <el-button type="primary" @click="toAdd">新增</el-button>
    </div>

    <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.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="评卷方式">
        <template slot-scope="scope">
          <el-radio-group v-model="scope.row.doubleRate">
            <el-radio
              v-for="(val, key) in MARK_TYPE"
              :key="key"
              :label="key * 1"
              >{{ val }}</el-radio
            >
          </el-radio-group>
          <span v-if="scope.row.doubleRate === 1">
            仲裁阀值：<el-input-number
              v-model="scope.row.arbitrateThreshold"
              class="width-80"
              size="small"
              :min="0"
              :max="999999"
              :step="0.01"
              step-strictly
              :controls="false"
            >
            </el-input-number>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="评阅题目">
        <template slot-scope="scope">
          {{ scope.row.questions | questionsFilter }}
        </template>
      </el-table-column>
      <el-table-column label="评卷区" width="80" align="center">
        <template slot-scope="scope">
          <i
            v-if="scope.row.pictureConfigList.length"
            class="el-icon-success color-success"
          ></i>
        </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
          >
          <el-button
            class="btn-primary"
            type="text"
            :disabled="!paperList.length"
            @click="toSetArea(scope.row)"
            >评卷区</el-button
          >
          <el-button class="btn-danger" type="text" @click="toDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- ModifyMarkerQuestion -->
    <modify-marker-question
      ref="ModifyMarkerQuestion"
      :instance="curGroupInfo"
      :disabled-question-ids="disabledQuestionIds"
      :paper-structure="subjectiveQuestionList"
      @modified="groupModified"
    ></modify-marker-question>
    <!-- ModifyMarkArea -->
    <modify-mark-area
      ref="ModifyMarkArea"
      :base-info="datas.basicPaperInfo"
      :group="curGroupInfo"
      :paper-list="paperList"
      @modified="areaModified"
    ></modify-mark-area>
  </div>
</template>

<script>
import ModifyMarkerQuestion from "./ModifyMarkerQuestion";
import ModifyMarkArea from "./ModifyMarkArea.vue";
import { examStructureFindJpg } from "../../api";

export default {
  name: "mark-paper-marker",
  components: { ModifyMarkerQuestion, ModifyMarkArea },
  props: {
    datas: {
      type: Object,
      default() {
        return {
          basicPaperInfo: {},
          paperStructureInfo: [],
          groupInfo: []
        };
      }
    }
  },
  data() {
    return {
      questionCount: 0,
      groupQuestionCount: 0,
      groupInfo: [],
      disabledQuestionIds: [],
      curGroupInfo: {},
      subjectiveQuestionList: [],
      subjectiveQuestionCount: 0,
      objectiveQuestionCount: 0,
      MARK_TYPE: {
        0: "单评",
        1: "双评"
      },
      paperList: []
    };
  },
  filters: {
    questionsFilter(val) {
      return val.map(item => `${item.mainNumber}-${item.subNumber}`).join(",");
    }
  },
  mounted() {
    this.initData();
    this.getPaperList();
  },
  methods: {
    async getPaperList() {
      this.paperList = [];
      const data = await examStructureFindJpg({
        examId: this.datas.basicPaperInfo.examId,
        courseCode: this.datas.basicPaperInfo.courseCode,
        paperNumber: this.datas.basicPaperInfo.paperNumber,
        paperType: this.datas.basicPaperInfo.paperType
      });
      const papers = data || [];
      papers.sort((a, b) => a.index - b.index);
      this.paperList = papers.map(paper => {
        return {
          imgUrl: paper.path,
          areas: []
        };
      });
    },
    initData() {
      this.groupInfo = this.datas.groupInfo.map(item => {
        return { ...item };
      });
      this.questionCount = this.datas.paperStructureInfo.length;
      this.updateDisableQuestionIds();

      this.subjectiveQuestionList = this.datas.paperStructureInfo.filter(
        item => item.qType === "subjective"
      );
      this.subjectiveQuestionCount = this.subjectiveQuestionList.length;
      this.objectiveQuestionCount =
        this.questionCount - this.subjectiveQuestionCount;

      this.$emit("on-ready");
    },
    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;
    },
    toAdd() {
      this.updateDisableQuestionIds();
      if (this.groupQuestionCount === this.subjectiveQuestionCount) {
        this.$message.error("当前已经没有主观题目可供设置！");
        return;
      }

      this.curGroupInfo = {
        id: this.$randomCode(),
        markerList: [],
        doubleRate: 0,
        arbitrateThreshold: 1,
        questions: [],
        pictureConfigList: []
      };
      this.$refs.ModifyMarkerQuestion.open();
    },
    toEdit(row) {
      this.curGroupInfo = row;
      this.updateDisableQuestionIds(row.id);
      this.$refs.ModifyMarkerQuestion.open();
    },
    toSetArea(row) {
      this.curGroupInfo = row;
      this.$refs.ModifyMarkArea.open();
    },
    toDelete(row) {
      const pos = this.groupInfo.findIndex(item => item.id === row.id);
      this.groupInfo.splice(pos, 1);
      this.updateDisableQuestionIds();
    },
    groupModified(row) {
      const pos = this.groupInfo.findIndex(item => item.id === row.id);
      if (pos === -1) {
        this.groupInfo.push(row);
      } else {
        this.groupInfo.splice(pos, 1, row);
      }
      this.updateDisableQuestionIds();
    },
    areaModified(row) {
      const pos = this.groupInfo.findIndex(item => item.id === row.id);
      if (pos === -1) return;
      this.groupInfo.splice(pos, 1, row);
    },
    checkData() {
      let errorMessages = [];

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

      this.groupInfo.forEach((item, index) => {
        if (item.doubleRate === 1 && !item.arbitrateThreshold) {
          errorMessages.push(`序号${index + 1}设置中，仲裁阀值不能为空`);
        }
      });

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

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