<template>
  <div class="mark-param-class">
    <div class="part-box part-box-pad">
      <div>
        <!-- <el-switch
          v-if="checkPrivilege('button', 'OpenClassReading', 'MarkSetting')"
          v-model="markClassIsOpen"
          active-text="分班阅卷"
          @change="markClassChange"
        ></el-switch> -->
      </div>
      <div></div>
    </div>
    <div 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">
        <template v-if="groupInfo.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 class="mark-footer">
      <el-button type="primary" :disabled="loading" @click="submit"
        >提交</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </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 {
  markClassMarkerList,
  markClassMarkerSave,
  markClassStatusUpdate,
} from "../../api";
import { mapState } from "vuex";
import SelectClassByCourse from "./SelectClassByCourse.vue";

export default {
  name: "mark-param-class",
  components: { SelectClassByCourse },
  data() {
    return {
      dataList: [],
      curRow: {},
      classList: [],
      selectedClassIds: [],
      loading: false,
      unsignData: [],
      markClassIsOpen: false,
    };
  },
  computed: {
    ...mapState("markParam", ["basicInfo", "groupInfo", "openMarkClass"]),
  },
  mounted() {
    this.initData();
  },
  methods: {
    async initData() {
      this.markClassIsOpen = this.openMarkClass;

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

      this.updateUnsignData();
    },
    async markClassChange() {
      const name = this.markClassIsOpen ? "开启" : "取消";
      const confirm = await this.$confirm(`确定要${name}分班阅卷吗?`, "提示", {
        type: "warning",
      }).catch(() => {});
      if (confirm !== "confirm") {
        this.markClassIsOpen = !this.markClassIsOpen;
        return;
      }

      const res = await markClassStatusUpdate({
        examId: this.basicInfo.examId,
        paperNumber: this.basicInfo.paperNumber,
        openMarkClass: this.markClassIsOpen,
      }).catch(() => {
        this.markClassIsOpen = !this.markClassIsOpen;
      });
      if (!res) return;
      this.setOpenMarkClass(this.markClassIsOpen);
    },
    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.groupInfo
            .filter(
              (group) =>
                !group.markers.some((marker) => markIds.includes(marker.userId))
            )
            .map((group) => {
              return {
                id: group.id,
                groupNumber: group.groupNumber,
                question: group.questions
                  .map((q) => `${q.mainNumber}-${q.subNumber}`)
                  .join(),
              };
            });

          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 markClassMarkerSave({
        examId: this.basicInfo.examId,
        paperNumber: this.basicInfo.paperNumber,
        groupMarkerClass: this.dataList,
      }).catch(() => {});
      if (!res) return;
      this.$message.success("保存成功！");
    },
    cancel() {
      this.$emit("cancel");
    },
  },
};
</script>
