<template>
  <div class="mark-param-class">
    <div class="part-box part-box-pad box-justify">
      <el-form inline>
        <el-form-item label="是否开启分班阅卷：">
          <el-radio-group v-model="classMarkIsOpen" @change="markClassChange">
            <el-radio-button :label="true">开启</el-radio-button>
            <el-radio-button :label="false">关闭</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="classMarkIsOpen">
          <el-breadcrumb class="el-space" separator="|">
            <el-breadcrumb-item
              >班级数：{{ stat.classCount }}个</el-breadcrumb-item
            >
            <el-breadcrumb-item
              >未分配评卷员班级数：<span class="color-danger">{{
                stat.unsignClassCount
              }}</span
              >个</el-breadcrumb-item
            >
            <el-breadcrumb-item
              >设置完成进度：<span class="color-primary"
                >{{ stat.completeRate }}%</span
              ></el-breadcrumb-item
            >
          </el-breadcrumb>
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" @click="toPrev(1)">上一步</el-button>
        <el-button type="primary" @click="toNext(1)">下一步</el-button>
      </div>
    </div>
    <div v-if="classMarkIsOpen" class="part-box part-box-pad">
      <el-table :data="dataList" border>
        <el-table-column type="index" width="50"> </el-table-column>

        <el-table-column label="评卷员" width="300">
          <template slot-scope="scope">
            <el-tag size="medium">
              {{ scope.row.marker.name }}（{{ scope.row.marker.loginName }}）
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="markerClassList" label="评卷班级">
          <template slot-scope="scope">
            {{ scope.row.markerClassList.join() }}
          </template>
        </el-table-column>
        <el-table-column class-name="action-column" label="操作" width="120">
          <template slot-scope="scope">
            <el-button
              class="btn-primary"
              type="text"
              @click="toSelectClass(scope.row)"
              >选择班级</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="tips-info tips-error mt-2">
        <template v-if="subjectiveTaskList.length <= 1">
          <p v-if="unsignData.length">
            未分配班级：{{ unsignData.map((item) => item.className).join() }}
          </p>
        </template>
        <template v-else>
          <p
            v-for="item in unsignData"
            :key="item.className"
            style="white-space: pre-wrap"
          >
            {{ item.content }}
          </p>
        </template>
      </div>
    </div>
    <div v-else class="part-box part-box-pad">
      <p class="tips-info">1.分班阅卷即评卷老师评指定班级的卷子；</p>
      <p class="tips-info">
        2.如果需要进行分班阅卷，请在点击开启，不需要可以直接点击下一步，进行主观题评卷设置；
      </p>
    </div>

    <!-- SelectClassByCourse -->
    <select-class-by-course
      ref="SelectClassByCourse"
      :selected-ids="selectedClassIds"
      :class-list="classList"
      required
      @confirm="classSelected"
    ></select-class-by-course>
  </div>
</template>

<script>
import { markClassList, markClassSave, markClassStatusUpdate } from "../../api";
import { mapState, mapMutations } from "vuex";
import SelectClassByCourse from "./SelectClassByCourse.vue";
import { toPrecision } from "@/plugins/utils";
import { MD5 } from "@/plugins/md5";

export default {
  name: "mark-param-class",
  components: { SelectClassByCourse },
  data() {
    return {
      dataList: [],
      cacheDataMd5: "",
      curRow: {},
      classList: [],
      selectedClassIds: [],
      loading: false,
      unsignData: [],
      classMarkIsOpen: false,
    };
  },
  computed: {
    ...mapState("markParam", [
      "basicInfo",
      "subjectiveTaskList",
      "openClassMark",
    ]),
    stat() {
      return {
        classCount: this.classList.length,
        unsignClassCount: this.unsignData.length,
        completeRate: toPrecision(
          (100 * this.unsignData.length) / this.classList.length,
          2
        ),
      };
    },
  },
  mounted() {
    this.initData();
  },
  methods: {
    ...mapMutations("markParam", ["setOpenClassMark"]),
    async initData() {
      this.classMarkIsOpen = this.openClassMark;
      if (!this.classMarkIsOpen) return;

      const params = {
        examId: this.basicInfo.examId,
        paperNumber: this.basicInfo.paperNumber,
      };
      const res = await markClassList(params);
      this.dataList = res.markerClass || [];
      this.classList = res.classNames || [];

      this.updateUnsignData();
      this.cacheDataMd5 = this.getSubmitDataMd5();
    },
    resetData() {
      this.dataList = [];
      this.classList = [];
      this.selectedClassIds = [];
      this.unsignData = [];
      this.cacheDataMd5 = "";
    },
    getSubmitDataMd5() {
      this.cacheDataMd5 = MD5(JSON.stringify(this.dataList));
    },
    async markClassChange() {
      const name = this.classMarkIsOpen ? "开启" : "关闭";
      const confirm = await this.$confirm(`确定要${name}分班阅卷吗?`, "提示", {
        type: "warning",
      }).catch(() => {});
      if (confirm !== "confirm") {
        this.classMarkIsOpen = !this.classMarkIsOpen;
        return;
      }

      const res = await markClassStatusUpdate({
        examId: this.basicInfo.examId,
        paperNumber: this.basicInfo.paperNumber,
        classMark: this.classMarkIsOpen,
      }).catch(() => {
        this.classMarkIsOpen = !this.classMarkIsOpen;
      });
      if (!res) return;
      this.setOpenClassMark(this.classMarkIsOpen);
      if (this.classMarkIsOpen) {
        this.initData();
      } else {
        this.resetData();
      }
    },
    toSelectClass(row) {
      this.curRow = row;
      this.selectedClassIds = row.markerClassList;
      this.$refs.SelectClassByCourse.open();
    },
    classSelected(markerClassList) {
      this.curRow.markerClassList = markerClassList;

      this.updateUnsignData();
    },
    updateUnsignData() {
      this.unsignData = this.classList
        .map((className) => {
          const markIds = this.dataList
            .filter((row) => row.markerClassList.includes(className))
            .map((row) => row.marker.userId);

          const unsignGroups = this.subjectiveTaskList
            .filter(
              (group) =>
                !group.markers.some((marker) => markIds.includes(marker.userId))
            )
            .map((group) => {
              return {
                id: group.id,
                question: `${group.mainNumber}-${group.subNumber}`,
              };
            });

          const nrow = {
            className,
            unsignGroups,
            content: "",
          };
          if (unsignGroups.length) {
            const groupCont = unsignGroups
              .map((group) => group.question)
              .join("   ");
            nrow.content = `${className}班级，${groupCont}，未分配评卷员`;
          }

          return nrow;
        })
        .filter((item) => item.unsignGroups.length);
    },
    async submit() {
      if (this.unsignData.length) {
        this.$message.error("存在未分配班级，请完成分配！");
        return;
      }
      if (this.loading) return;

      const unvalid = this.dataList.some(
        (item) => !item.markerClassList.length
      );
      if (unvalid) {
        this.$message.error("有评卷员未设置班级");
        return;
      }

      const res = await markClassSave({
        examId: this.basicInfo.examId,
        paperNumber: this.basicInfo.paperNumber,
        questionMarkerClass: this.dataList,
      }).catch(() => {});
      if (!res) return;
      this.$message.success("保存成功！");
      this.cacheDataMd5 = this.getSubmitDataMd5();
      return true;
    },
    async toPrev(step = 1) {
      if (
        !this.classMarkIsOpen ||
        this.cacheDataMd5 === this.getSubmitDataMd5()
      ) {
        this.$emit("prev", step);
        return;
      }

      const confirm = await this.$confirm(
        `存在未保存的数据，是否保存后返回上一步？`,
        "提示",
        {
          type: "warning",
        }
      ).catch(() => {});
      if (confirm !== "confirm") {
        this.$emit("prev", step);
        return;
      }

      const res = await this.submit();
      if (!res) return;
      this.$emit("prev", step);
    },
    async toNext(step = 1) {
      if (
        !this.classMarkIsOpen ||
        this.cacheDataMd5 === this.getSubmitDataMd5()
      ) {
        this.$emit("next", step);
        return;
      }

      const res = await this.submit();
      if (!res) return;
      this.$emit("next", step);
    },
  },
};
</script>
