<template>
  <div class="marker-grading">
    <marker-header
      v-if="curSubject.id"
      show-select-all
      @area-change="areaChange"
      @step-change="stepChange"
      @page-set-change="pageSetChange"
      @to-progress="toProgress"
      @to-select-all="toSelectAll"
      @to-history="toHistory"
      @to-standard="toStandard"
      @to-statistics="toStatistics"
      @on-code-search="serachPaperByCode"
      @on-mark-search="serachPaperByCode"
    ></marker-header>

    <div
      :class="[
        'marker-action',
        'dark-mark',
        { 'marker-action-fullscreen': isFullscreenMarking }
      ]"
      v-show="!multipleGradingList.length"
    >
      <grade-action
        :cur-paper-or-task="curPaper"
        :levels="levels"
        :params-set="paramsSet"
        :key="curPaper.key"
        @on-leader-level="leaderSelectLevel"
        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>
        <h3 class="action-grade-info-title" v-if="markLeaderOnlyRight">
          当前操作：{{ markLeaderOnlyRight.name }}
        </h3>
        <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
              ref="MarkerImageView"
              :data="paper"
              :can-select="ACTION_CAN_BATCH"
              @to-review="toReview(index)"
              @to-select="selectMultiplePaper"
            ></marker-image-view>
          </div>
        </div>
      </div>
      <div v-else class="marker-image-none">暂无数据</div>
    </div>

    <!-- LeaderStatistics -->
    <leader-statistics
      :question-id="filter.questionId"
      ref="LeaderStatistics"
    ></leader-statistics>
    <!-- LeaderProgress -->
    <leader-progress ref="LeaderProgress"></leader-progress>
    <!-- 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"
    ></marker-standard>
    <!-- modify-leader-grading -->
    <modify-leader-grading
      class="marker-modal"
      :level-info="levelInfo"
      :markers="markers"
      @modified="leaderGradingSuccess"
      ref="ModifyLeaderGrading"
    ></modify-leader-grading>
    <!-- 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 "../marker/MarkerHeader";
import MarkerImageView from "../marker/MarkerImageView";
import MarkerHistory from "../marker/MarkerHistory";
import MarkerStandard from "../marker/MarkerStandard";
import LeaderProgress from "./LeaderProgress";
import LeaderStatistics from "./LeaderStatistics";
import GradeAction from "../components/GradeAction";
import SimpleImagePreview from "@/components/SimpleImagePreview";
import ModifyLeaderGrading from "../components/ModifyLeaderGrading";

import {
  paperList,
  markLeaderLevelStatData,
  workLevelList,
  taskSnSearch,
  subjectDetail,
  markHistoryList,
  getParamsSet,
  leaderGradingPaper
} from "@/api";

export default {
  name: "marker-grading",
  components: {
    MarkerHeader,
    MarkerImageView,
    MarkerHistory,
    MarkerStandard,
    LeaderProgress,
    LeaderStatistics,
    GradeAction,
    SimpleImagePreview,
    ModifyLeaderGrading
  },
  data() {
    return {
      filter: {
        questionId: "",
        sort: "secretNumber"
      },
      typeFilter: {
        done: {
          level: ""
        },
        reject: {
          reject: true
        },
        arbitrate: {
          arbi: true
        }
      },
      workId: this.$route.params.workId,
      subjectId: this.$route.params.subjectId,
      levels: [],
      papers: [],
      curPaper: {},
      curPaperIndex: 0,
      // leader-grade
      levelInfo: {},
      markers: [],
      // carousel paper review,
      carouselType: "",
      carouselPapers: [],
      curCarouselPaperIndex: 0,
      isFullscreenMarking: false,
      // multiple grading
      multiplebtnClicked: false,
      multipleGradingList: [],
      // 科组长权限
      markLeaderOnlyRight: null
    };
  },
  computed: {
    ...mapState("marker", [
      "paramsSet",
      "page",
      "steps",
      "curStep",
      "curArea",
      "curSubject"
    ]),
    markerImageListClasses() {
      return ["marker-image-list", `marker-image-list-${this.page.size}`];
    },
    IS_TEST() {
      return this.curSubject.test === 2;
    },
    ACTION_CAN_BATCH() {
      return this.curStep.type === "done" && !this.paramsSet.paperStage;
    }
  },
  created() {
    this.markLeaderOnlyRight = this.$ls.get("user", {
      markLeaderOnlyRight: null
    }).markLeaderOnlyRight;

    const curUserRoleType = this.$ls.get("user", { role: "" }).role;
    this.setCurUserRoleType(curUserRoleType);
    this.initData();
  },
  methods: {
    ...mapMutations("marker", [
      "setParamSet",
      "setPage",
      "setSteps",
      "setCurStep",
      "setCurArea",
      "setCurSubject",
      "setCurUserRoleType",
      "clearState"
    ]),
    initData() {
      this.getParamsSetInfo();
      this.getSubjectDetail();
      this.getWorkLevels();
    },
    async getParamsSetInfo() {
      const data = await getParamsSet(this.workId);
      this.setParamSet(data || {});
    },
    async getSubjectDetail() {
      const curSubject = await subjectDetail(this.subjectId);
      this.setCurSubject(curSubject || {});
    },
    async getList() {
      this.multipleGradingList = [];
      const datas = {
        ...this.filter,
        ...this.typeFilter[this.curStep.type],
        page: this.page.current - 1,
        size: this.page.size
      };
      if (this.curStep.type === "done") datas.level = this.curStep.name;

      const data = await paperList(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 markLeaderLevelStatData(
        this.subjectId,
        this.filter.questionId
      );
      const undoIndex = data.findIndex(item => item.id === null);
      let otherStep = [];
      let undo = {
        count: 0,
        rejected: 0,
        arbitrated: 0
      };
      if (undoIndex !== -1) {
        undo = { ...data[undoIndex] };
        data.splice(undoIndex, 1);
      }

      if (this.IS_TEST) {
        otherStep.push({
          name: "待评",
          count: undo.count,
          type: "undo"
        });
      }
      otherStep.push({
        name: "打回",
        count: undo.rejected,
        type: "reject"
      });
      otherStep.push({
        name: "仲裁",
        count: undo.arbitrated,
        type: "arbitrate"
      });

      let levelStep = data.map(item => {
        return {
          ...item,
          name: item.id,
          type: "done"
        };
      });
      this.setSteps({ levelStep, otherStep });

      if (!this.curStep.name) {
        const firstStep = otherStep.find(item => item.count);
        const curStep = firstStep || levelStep[0];
        this.setCurStep(curStep);
      } else {
        const curStep = [...levelStep, ...otherStep].find(
          item => item.name === this.curStep.name
        );
        this.setCurStep(curStep);
      }
    },
    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);
    },
    async multipleSelectLevel(level) {
      if (!this.multipleGradingList.length) return;
      if (this.multiplebtnClicked) return;

      this.multiplebtnClicked = true;

      const data = await markHistoryList(
        this.multipleGradingList[0].id,
        "LEVEL"
      ).catch(() => {
        this.multiplebtnClicked = false;
      });

      if (!data) return;

      const markers = data.map(item => {
        return {
          id: item.markerId,
          name: item.marker
        };
      });
      const levelInfo = {
        paperIds: this.multipleGradingList.map(item => item.id).join(),
        curLevel: this.curStep.name,
        selectedLevel: level.name,
        markLeaderOnlyRight: this.markLeaderOnlyRight
      };

      await this.leaderSelectLevel(levelInfo, markers).catch(() => {});
      this.multiplebtnClicked = false;
    },
    // paper view action
    toReview(index) {
      this.isFullscreenMarking = true;
      this.multipleGradingList = [];
      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 serachPaperByCode(params) {
      const data = await taskSnSearch(
        params.codeType,
        params.code,
        this.filter.questionId
      );
      if (!data) {
        this.$Message.error("没有查找到结果！");
        return;
      }
      data.title = `NO.${data.sn}`;
      this.papers = [data];
      this.setPage({ current: 1, total: 1, totalPage: 1 });
      this.selectPaper(0);
    },
    async serachMarkPaper(params) {
      console.log(params);
      // TODO:
    },
    async leaderSelectLevel(levelInfo, markers) {
      // 唯一权限时，直接操作
      if (levelInfo.markLeaderOnlyRight && !this.paramsSet.leaderConfirm) {
        const datas = {
          action: levelInfo.markLeaderOnlyRight.action,
          level: levelInfo.selectedLevel,
          originLevel: levelInfo.curLevel,
          paperIds: levelInfo.paperIds
        };
        if (datas.action === "reject") {
          datas.range = markers.map(item => item.id).join();
        }
        let result = true;
        const paper = await leaderGradingPaper(datas).catch(() => {
          result = false;
        });
        if (!result) return;

        this.leaderGradingSuccess(datas, paper);
        return;
      }

      this.levelInfo = levelInfo;
      this.markers = markers;
      this.$refs.ModifyLeaderGrading.open();
    },
    async leaderGradingSuccess(datas, paper) {
      this.getStepLevels();

      if (this.multipleGradingList && this.multipleGradingList.length) {
        // 批量处理逻辑
        if (
          this.page.current > 1 &&
          this.page.current === this.page.totalPage &&
          this.papers.length === this.multipleGradingList.length
        ) {
          this.setPage({ current: this.page.current - 1 });
        }

        this.multipleGradingList = [];
        await this.getList();
        this.selectPaper(this.curPaperIndex);
      } else {
        // 单张处理逻辑
        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 (type === "prev" && this.curCarouselPaperIndex > 0) {
        this.curCarouselPaperIndex--;
      } else if (
        type === "next" &&
        this.curCarouselPaperIndex < this.carouselPapers.length - 1
      ) {
        this.curCarouselPaperIndex++;
      }
      this.selectCarouselPaper(this.curCarouselPaperIndex);
    },
    carouseImagePreviewClose() {
      this.isFullscreenMarking = false;
      this.carouselType = "";
      this.selectPaper(this.curPaperIndex);
    },
    // header
    toHistory() {
      this.$refs.MarkerHistory.open();
    },
    toStandard() {
      this.$refs.MarkerStandard.open();
    },
    toProgress() {
      this.$refs.LeaderProgress.open();
    },
    toSelectAll(allSelected) {
      this.$refs.MarkerImageView.forEach(item => {
        item.changeSelect(allSelected);
      });
    },
    toStatistics() {
      this.$refs.LeaderStatistics.open();
    }
  },
  beforeDestroy() {
    this.clearState();
  }
};
</script>
