<template>
  <div class="marker-grading">
    <marker-header
      ref="MarkerHeader"
      @area-change="areaChange"
      @step-change="stepChange"
      @page-set-change="pageSetChange"
      @to-history="toHistory"
      @to-standard="toStandard"
      @to-statistics="toStatistics"
    ></marker-header>

    <div
      :class="[
        'marker-action',
        { 'marker-action-fullscreen': isFullscreenMarking }
      ]"
      v-show="!multipleGradingList.length"
    >
      <grade-action
        :cur-paper-or-task="curPaper"
        :levels="levels"
        :params-set="paramsSet"
        :key="curPaper.key"
        @on-select-level="gradeCurPaper"
        @on-pass="passCurPaper"
        ref="GradeAction"
        v-if="curPaper.id"
      ></grade-action>
    </div>
    <!-- multiple grading action -->
    <div class="marker-action" v-show="multipleGradingList.length">
      <div class="grade-action">
        <div class="action-paper-state">
          <p class="paper-state-cont">批量分档</p>
        </div>
        <div class="action-paper-info">
          <p><span>任务密号：</span><span>--</span></p>
        </div>
        <div class="action-grade-list">
          <div
            class="action-grade-item"
            v-for="(level, index) in levels"
            :key="index"
          >
            <div
              :class="[
                'action-grade-item-content',
                { 'action-item-content-disabled': multiplebtnClicked }
              ]"
              @click="multipleSelectLevel(level)"
            >
              <p>{{ level.name }}</p>
              <p>{{ level.minScore }}~{{ level.maxScore }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="marker-body">
      <div :class="markerImageListClasses" v-if="papers.length">
        <div
          v-for="(paper, index) in papers"
          :key="paper.key"
          :class="[
            'marker-image-item',
            {
              'marker-image-item-act': curPaperIndex === index
            }
          ]"
        >
          <div class="marker-image-content">
            <marker-image-view
              :data="paper"
              @to-review="toReview(index)"
              @to-select="selectMultiplePaper"
            ></marker-image-view>
          </div>
        </div>
      </div>
      <div v-else class="marker-image-none">暂无数据</div>
    </div>

    <!-- MarkerHistory -->
    <marker-history
      :question-id="filter.questionId"
      @on-paper-click="
        (index, papers) => {
          toViewCarouselPaper(index, papers, 'history');
        }
      "
      ref="MarkerHistory"
    ></marker-history>
    <!-- MarkerStandard -->
    <marker-standard
      :question-id="filter.questionId"
      :levels="levels"
      @on-paper-click="
        (index, papers) => {
          toViewCarouselPaper(index, papers, 'sample');
        }
      "
      ref="MarkerStandard"
      v-if="levels.length && filter.questionId && paramsSet.showSample"
    ></marker-standard>
    <!-- MarkerStatistics -->
    <marker-statistics ref="MarkerStatistics"></marker-statistics>
    <!-- image-preview -->
    <simple-image-preview
      class="grading-operation-image-preview"
      :cur-image="curPaper"
      @on-prev="toPrevPaper"
      @on-next="toNextPaper"
      @on-close="isFullscreenMarking = false"
      ref="SimpleImagePreview"
    ></simple-image-preview>

    <!-- carousel paper review -->
    <simple-image-preview
      class="grading-operation-image-preview"
      :cur-image="curPaper"
      @on-prev="toCarousePaper('prev')"
      @on-next="toCarousePaper('next')"
      @on-close="carouseImagePreviewClose"
      ref="CarouselPapersPreview"
    ></simple-image-preview>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import MarkerHeader from "./MarkerHeader";
import MarkerImageView from "./MarkerImageView";
import MarkerHistory from "./MarkerHistory";
import MarkerStandard from "./MarkerStandard";
import MarkerStatistics from "./MarkerStatistics";
import GradeAction from "../components/GradeAction";
import SimpleImagePreview from "@/components/SimpleImagePreview";

import {
  markerTaskList,
  markerLevelTotalStatData,
  workLevelList,
  paperSelectLevelOrScore,
  paperSelectLevelBatch,
  paperTaskPass,
  getParamsSet
} from "@/api";

export default {
  name: "marker-grading",
  components: {
    MarkerHeader,
    MarkerImageView,
    MarkerHistory,
    MarkerStandard,
    MarkerStatistics,
    GradeAction,
    SimpleImagePreview
  },
  data() {
    return {
      filter: {
        markerId: this.$ls.get("user").id,
        questionId: "",
        sort: "randomSeq,asc",
        stage: "LEVEL"
      },
      typeFilter: {
        done: {
          level: ""
        },
        undo: {},
        reject: {
          reject: true
        }
      },
      workId: this.$route.params.workId,
      subjectId: this.$route.params.subjectId,
      subject: "",
      workSubject: {},
      curStandardGradeId: "",
      levels: [],
      papers: [],
      curPaper: {},
      curPaperIndex: 0,
      // multiple grading
      multiplebtnClicked: false,
      multipleGradingList: [],
      // carousel paper review,
      carouselType: "",
      carouselPapers: [],
      curCarouselPaperIndex: 0,
      isFullscreenMarking: false
    };
  },
  computed: {
    ...mapState("marker", ["paramsSet", "page", "steps", "curStep", "curArea"]),
    markerImageListClasses() {
      return ["marker-image-list", `marker-image-list-${this.page.size}`];
    }
  },
  created() {
    this.subject = this.subjectId.split("-")[1];
    this.workSubject = {
      workId: this.workId,
      subject: this.subject
    };
    const curUserRoleType = this.$ls.get("user", { role: "" }).role;
    this.setCurUserRoleType(curUserRoleType);
    this.initData();
  },
  methods: {
    ...mapMutations("marker", [
      "setParamSet",
      "setPage",
      "setSteps",
      "setCurArea",
      "setCurStep",
      "setCurUserRoleType",
      "clearState"
    ]),
    async initData() {
      await this.getParamsSetInfo();
      await this.getWorkLevels();
    },
    async getParamsSetInfo() {
      const data = await getParamsSet(this.workId);
      this.setParamSet(data || {});
    },
    async getList() {
      this.clearMultiplePaper();
      const datas = {
        ...this.filter,
        ...this.typeFilter[this.curStep.type],
        workId: this.workId,
        page: this.page.current - 1,
        size: this.page.size
      };
      if (this.curStep.type === "done") {
        datas.level = this.curStep.name;
        datas.sort = "updatedOn,desc";
      }

      const data = await markerTaskList(datas);
      this.papers = data.data.map(paper => {
        paper.key = this.$randomCode();
        paper.title = `NO.${paper.sn}`;
        paper.selected = false;
        return paper;
      });
      this.setPage({
        total: data.totalCount,
        totalPage: data.pageCount
      });
    },
    async toPage(page) {
      this.setPage({
        current: page
      });
      await this.getList();
      this.selectPaper(this.curPaperIndex);
    },
    async getStepLevels() {
      const data = await markerLevelTotalStatData(
        this.filter.markerId,
        this.filter.questionId
      );
      const undoIndex = data.findIndex(item => item.id === null);
      let otherStep = [];
      let undo = {
        count: 0,
        rejected: 0
      };
      if (undoIndex !== -1) {
        undo = { ...data[undoIndex] };
        data.splice(undoIndex, 1);
      }

      otherStep.push({
        name: "待评",
        count: undo.count,
        type: "undo"
      });
      otherStep.push({
        name: "打回",
        count: undo.rejected,
        type: "reject"
      });
      let levelStep = data.map(item => {
        // 评卷员不展示kdpt
        item.kdpt = null;
        return {
          ...item,
          name: item.id,
          type: "done"
        };
      });
      this.setSteps({ levelStep, otherStep });

      if (!this.curStep.name) {
        let curStep = {};
        if (undoIndex === -1) {
          curStep = levelStep[0];
        } else {
          const firstStep = otherStep.find(item => item.count);
          curStep = firstStep || levelStep[0];
        }
        this.setCurStep(curStep);
      } else {
        const curStep = [...levelStep, ...otherStep].find(
          item => item.name === this.curStep.name
        );
        this.setCurStep(curStep);
      }
    },
    updateStepLevel(curStep, curLevel, count) {
      if (curStep.type === "done") {
        const lpos = this.steps.levelStep.findIndex(
          item => item.name === curStep.name
        );
        this.steps.levelStep[lpos].count -= count;
      } else {
        const opos = this.steps.otherStep.findIndex(
          item => item.type === curStep.type
        );
        this.steps.otherStep[opos].count -= count;
      }

      const pos = this.steps.levelStep.findIndex(
        item => item.name === curLevel
      );
      this.steps.levelStep[pos].count += count;

      this.steps.levelStep.forEach(item => {
        item.percent =
          item.finalKdTotal && item.count
            ? ((100 * item.count) / item.finalKdTotal).toFixed(3)
            : 0;
      });
      this.setSteps(this.steps);
    },
    async getWorkLevels() {
      const data = await workLevelList(this.workId);
      this.levels = data.map(item => {
        return {
          id: item.id,
          name: item.code,
          minScore: item.minScore,
          maxScore: item.maxScore
        };
      });
    },
    async pageSetChange() {
      await this.getList();
      this.selectPaper(this.curPaperIndex);
    },
    async stepChange(step) {
      this.setCurStep(step);
      this.setPage({ current: 1 });
      this.isFullscreenMarking = false;
      await this.getList();
      this.getStepLevels();
      if (this.papers.length) {
        this.selectPaper(0);
      } else {
        this.curPaper = {};
      }
    },
    async areaChange(curArea) {
      this.setCurArea(curArea);
      this.filter.questionId = curArea.id;
      await this.getStepLevels();
      this.toPage(1);
    },
    // selectMultiplePaper
    selectMultiplePaper(paper) {
      if (paper.sample) return;
      const curPaper = this.papers.find(p => p.id === paper.id);
      curPaper.selected = paper.selected;
      this.multipleGradingList = this.papers.filter(paper => paper.selected);
    },
    clearMultiplePaper() {
      this.multipleGradingList = [];
      this.papers.forEach(paper => {
        paper.selected = false;
      });
      this.$refs.MarkerHeader.changeAllSelect(false);
    },
    async multipleSelectLevel(level) {
      if (!this.multipleGradingList.length) return;
      if (this.multiplebtnClicked) return;
      this.multiplebtnClicked = true;
      const multipleGradingListCount = this.multipleGradingList.length;

      let result = true;
      await paperSelectLevelBatch(
        this.multipleGradingList.map(item => item.id).join(), // is taskId
        level.name,
        "LEVEL"
      ).catch(() => {
        result = false;
      });

      this.multiplebtnClicked = false;
      if (!result) return;

      this.multipleGradingList = [];
      // this.getStepLevels();
      this.updateStepLevel(this.curStep, level.name, multipleGradingListCount);

      // update paper list
      if (
        this.page.current > 1 &&
        this.page.current === this.page.totalPage &&
        this.papers.length === multipleGradingListCount
      ) {
        this.setPage({ current: this.page.current - 1 });
      }

      await this.getList();
      this.selectPaper(this.curPaperIndex);
    },
    // paper view action
    toReview(index) {
      this.isFullscreenMarking = true;
      this.clearMultiplePaper();
      this.selectPaper(index);
      this.$refs.SimpleImagePreview.open();
    },
    selectPaper(index) {
      let nindex = index;
      if (!this.papers.length) {
        nindex = 0;
      } else if (index > this.papers.length - 1) {
        nindex = this.papers.length - 1;
      } else if (index < 0) {
        nindex = 0;
      }
      this.curPaperIndex = nindex;
      this.curPaper = this.papers[nindex] ? { ...this.papers[nindex] } : {};
    },
    async toPrevPaper() {
      if (this.curPaperIndex === 0) {
        if (this.page.current > 1) {
          this.setPage({ current: this.page.current - 1 });
          this.curPaperIndex = this.page.size - 1;
          await this.getList();
        } else {
          this.$Message.warning("当前已经是第一条数据了");
          return;
        }
      } else {
        this.curPaperIndex--;
      }

      this.selectPaper(this.curPaperIndex);
    },
    async toNextPaper() {
      if (this.curPaperIndex === this.papers.length - 1) {
        if (this.page.current === this.page.totalPage) {
          this.$Message.warning("当前已经是最后一条数据了");
          return;
        } else {
          this.setPage({ current: this.page.current + 1 });
          this.curPaperIndex = 0;
          await this.getList();
        }
      } else {
        this.curPaperIndex++;
      }

      this.selectPaper(this.curPaperIndex);
    },
    async toActionNextPaper() {
      if (this.page.current > 1 && this.papers.length === 1) {
        this.setPage({ current: this.page.current - 1 });
        this.curPaperIndex = this.page.size;
      }

      await this.getList();
      if (!this.papers.length) this.$refs.SimpleImagePreview.cancel();
      this.selectPaper(this.curPaperIndex);
    },
    async gradeCurPaper(level) {
      const paper = await paperSelectLevelOrScore(
        this.curPaper.id, // is taskId
        level.name,
        "LEVEL"
      );
      if (!paper) return;

      if (this.carouselType) {
        this.updateStepLevel(
          { type: "done", name: this.curPaper.level },
          level.name,
          1
        );

        this.$refs.CarouselPapersPreview.cancel();
        this.$refs.MarkerHistory.updatePapers();
      } else {
        this.updateStepLevel(this.curStep, level.name, 1);
        this.toActionNextPaper();
      }
    },
    async passCurPaper() {
      await paperTaskPass(this.curPaper.id);
      this.toActionNextPaper();
    },
    // paper carousel
    toViewCarouselPaper(paperIndex, papers, type) {
      this.carouselType = type;
      this.isFullscreenMarking = true;
      this.carouselPapers = papers;
      this.selectCarouselPaper(paperIndex);
      this.$nextTick(() => {
        this.$refs.CarouselPapersPreview.open();
      });
    },
    selectCarouselPaper(index) {
      this.curCarouselPaperIndex = index;
      this.curPaper = { ...this.carouselPapers[index] };
    },
    toCarousePaper(type) {
      // if (this.carouselType === "sample") {
      //   this.toSampleCarousePaper(type);
      //   return;
      // }
      if (type === "prev" && this.curCarouselPaperIndex > 0) {
        this.curCarouselPaperIndex--;
      } else if (
        type === "next" &&
        this.curCarouselPaperIndex < this.carouselPapers.length - 1
      ) {
        this.curCarouselPaperIndex++;
      }
      this.selectCarouselPaper(this.curCarouselPaperIndex);
    },
    toSampleCarousePaper(type) {
      if (type === "prev") {
        this.$refs.GradeStandardPaper.$refs.PaperCarousel.handleLeft();
      } else if (type === "next") {
        this.$refs.GradeStandardPaper.$refs.PaperCarousel.handleRight();
      }
    },
    carouseImagePreviewClose() {
      this.isFullscreenMarking = false;
      this.carouselType = "";
      this.selectPaper(this.curPaperIndex);
    },
    // header
    toHistory() {
      this.$refs.MarkerHistory.open();
    },
    toStandard() {
      this.$refs.MarkerStandard.open();
    },
    toStatistics() {
      this.$refs.MarkerStatistics.open();
    }
  },
  beforeDestroy() {
    this.clearState();
  }
};
</script>
