<template>
  <div class="grading-operation home">
    <div class="home-header">
      <view-header>
        <h1 slot="logo">{{ curSubject.name }}</h1>
      </view-header>
    </div>
    <div class="home-body">
      <div class="home-main home-main-nofooter grading-detail">
        <grade-step
          :steps="steps"
          :init-step="curStep"
          :show-analysis="false"
          @on-change="stepChange"
          ref="GradeStep"
          v-if="steps.length"
        ></grade-step>
        <div class="detail-body">
          <div class="detail-filter">
            <Form ref="FilterForm" label-position="left" inline>
              <FormItem>
                <Select v-model="filter.questionId" placeholder="请选择考区">
                  <Option
                    v-for="area in areas"
                    :key="area.id"
                    :value="area.id"
                    :label="area.areaName"
                  ></Option>
                </Select>
              </FormItem>
              <FormItem>
                <Button type="primary" icon="ios-search" @click="toPage(1)"
                  >查询</Button
                >
              </FormItem>
            </Form>
          </div>
          <!-- detail-papers -->
          <div :class="detailPapersClasses">
            <div class="detail-papers-carousel">
              <grade-standard-paper
                :levels="levels"
                :question-id="filter.questionId"
                @on-paper-click="toViewCarouselPaper"
                v-if="levels && filter.questionId"
              ></grade-standard-paper>
              <grade-history-paper
                :question-id="filter.questionId"
                @on-paper-click="toViewCarouselPaper"
                v-if="filter.questionId"
              ></grade-history-paper>
            </div>
            <div class="detail-papers-list">
              <div :class="imageViewClasses">
                <div
                  :class="[
                    'image-view',
                    { 'image-view-act': curPaperIndex === index }
                  ]"
                  v-for="(image, index) in papers"
                  :key="index"
                >
                  <h5 class="image-view-title">{{ image.title }}</h5>
                  <div class="image-view-contain">
                    <img
                      :src="image.thumbSrc"
                      :alt="image.title"
                      @click="toReview(index)"
                    />
                  </div>
                </div>
              </div>
              <div class="part-page" v-if="total > size">
                <Page
                  :current="current"
                  :total="total"
                  :page-size="size"
                  show-total
                  show-elevator
                  :page-size-opts="[4, 6, 8]"
                  @on-page-size-change="pageSizeChange"
                  @on-change="toPage"
                ></Page>
              </div>
            </div>
          </div>
          <!-- detail-aciton -->
          <div class="detail-action">
            <grade-action
              :cur-paper="curPaper"
              :levels="levels"
              :user-role="curUserRoleType"
              @on-select-level="gradeCurPaper"
              @on-pass="passCurPaper"
              ref="GradeAction"
              v-if="curPaper.id"
            ></grade-action>
          </div>
        </div>
      </div>
    </div>

    <!-- image-preview -->
    <image-preview
      class="grading-detail-image-preview"
      :image-list="papers"
      :init-index="curPaperIndex"
      @on-paper-change="selectPaper"
      @on-page-prev="prevPage"
      @on-page-next="nextPage"
      header-hide
      ref="ImagePreview"
      v-if="papers.length"
    ></image-preview>

    <!-- carousel paper review -->
    <image-preview
      class="grading-detail-image-preview"
      :image-list="carouselPapers"
      :init-index="curCarouselPaperIndex"
      @on-paper-change="selectCarouselPaper"
      loop
      header-hide
      ref="CarouselPapersPreview"
      v-if="carouselPapers.length"
    ></image-preview>
  </div>
</template>

<script>
import {
  markerPaperList,
  markerLevelStatData,
  areaList,
  workLevelList,
  subjectDetail,
  paperSelectLevel,
  paperPassLevel
} from "@/api";
import ImagePreview from "@/components/common/ImagePreview";
import GradeStep from "./components/GradeStep";
import GradeStandardPaper from "./components/GradeStandardPaper";
import GradeHistoryPaper from "./components/GradeHistoryPaper";
import GradeAction from "./components/GradeAction";
// 三种情况：
// 管理员(ADMIN)，科组长(MARK_LEADER)，评卷员(MARKER)
// 评卷员：标准卷，操作记录，试卷列表，操作盘（只分档）

// TIP:不考虑管理员、科组长的情况
// 管理员：标准卷，试卷列表，操作盘
// 科组长：标准卷，操作记录，试卷列表，操作盘（定档，标准卷，打回）

export default {
  name: "grading-operation",
  components: {
    ImagePreview,
    GradeStep,
    GradeHistoryPaper,
    GradeStandardPaper,
    GradeAction
  },
  data() {
    return {
      filter: {
        markerId: this.$ls.get("user").id,
        questionId: "",
        sort: "randomSeq,asc",
        stage: "LEVEL",
        isSample: false
      },
      typeFilter: {
        done: {
          level: ""
        },
        undo: {},
        reject: {
          reject: true
        }
      },
      workId: this.$route.params.workId,
      subjectId: this.$route.params.subjectId,
      subject: "",
      curSubject: {},
      curUserRoleType: "MARKER",
      current: 1,
      size: 6,
      total: 0,
      totalPage: 1,
      curStep: { type: "undo", name: "待评" },
      curStandardGradeId: "",
      steps: [],
      levels: [],
      areas: [],
      papers: [],
      curPaper: {},
      curPaperIndex: 0,
      // carousel paper review,
      carouselPapers: [],
      curCarouselPaperIndex: 0
    };
  },
  computed: {
    detailPapersClasses() {
      return ["detail-papers", `detail-papers-col-${1 + this.size / 2}`];
    },
    imageViewClasses() {
      return ["image-view-list", `image-view-list-${this.size / 2}`];
    }
  },
  mounted() {
    this.subject = this.subjectId.split("-")[1];
    this.initData();
  },
  methods: {
    async initData() {
      this.getSubjectDetail();
      await this.getAreaList();
      this.filter.questionId = this.areas[0].id;
      this.getStepLevels();
      this.getWorkLevels();
    },
    async getSubjectDetail() {
      this.curSubject = await subjectDetail(this.subjectId);
    },
    async getList() {
      const datas = {
        ...this.filter,
        ...this.typeFilter[this.curStep.type],
        page: this.current - 1,
        size: this.size
      };
      if (this.curStep.type === "done") {
        datas.level = this.curStep.name;
        datas.sort = "updatedOn,desc";
      }

      const data = await markerPaperList(datas);
      this.papers = data.data.map(paper => {
        paper.title = paper.examNumber;
        return paper;
      });
      this.total = data.totalCount;
      this.totalPage = data.totalPage;
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    async getStepLevels() {
      const data = await markerLevelStatData(
        this.filter.markerId,
        this.filter.questionId
      );
      const undoIndex = data.findIndex(item => item.id === null);
      let otherStep = [];
      if (undoIndex !== -1) {
        const undo = { ...data[undoIndex] };
        data.splice(undoIndex, 1);

        otherStep.push({
          name: "待评",
          count: undo.count,
          type: "undo"
        });
        otherStep.push({
          name: "打回",
          count: undo.rejected,
          type: "reject"
        });
      }
      let levelMenu = data.map(item => {
        return {
          ...item,
          name: item.id,
          type: "done"
        };
      });
      this.steps = [...levelMenu, ...otherStep];
      let curStep = {};
      if (undoIndex === -1) {
        curStep = this.steps[0];
      } else {
        curStep = this.steps[this.steps.length - 2];
      }
      this.curStep = 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 getAreaList() {
      const data = await areaList({
        workId: this.workId,
        subject: this.subject
      });
      this.areas = data.map(item => {
        return {
          id: item.id,
          areaName: item.areaName,
          areaCode: item.areaCode
        };
      });
    },
    pageSizeChange(size) {
      this.size = size;
      this.toPage(1);
      this.getStepLevels();
    },
    async stepChange(step) {
      this.curStep = step;
      this.current = 1;
      await this.getList();
      if (this.papers.length) {
        this.selectPaper(0);
      } else {
        this.curPaper = {};
      }
    },
    selectPaper(index) {
      this.curPaperIndex = index;
      this.curPaper = { ...this.papers[index] };
    },
    toReview(index) {
      this.selectPaper(index);
      this.$refs.ImagePreview.open();
    },
    async prevPage() {
      if (this.current === 1) {
        this.$Message.warning("当前已经是第一条数据了");
        return;
      }
      this.current--;
      await this.getList();
      this.selectPaper(this.papers.length - 1);
      this.$refs.ImagePreview.initData();
    },
    async nextPage() {
      if (this.current === this.totalPage) {
        this.$Message.warning("当前已经是最后一条数据了");
        return;
      }
      // 下一页时，继续获取当前页数据。
      await this.getList();
      this.selectPaper(0);
      this.$refs.ImagePreview.initData();
    },
    async gradeCurPaper(level) {
      await paperSelectLevel(this.curPaper.id, level.name, "LEVEL");
      this.getStepLevels();
      this.toNext();
    },
    async passCurPaper(level) {
      await paperPassLevel(this.curPaper.id);
      this.toNext();
    },
    toNext() {
      this.$refs.ImagePreview.showNext();
    },
    // paper carousel
    toViewCarouselPaper(paperIndex, papers) {
      this.curCarouselPaperIndex = paperIndex;
      this.carouselPapers = papers;
      this.$refs.CarouselPapersPreview.open();
    },
    selectCarouselPaper(index) {
      this.curCarouselPaperIndex = index;
      this.curPaper = { ...this.carouselPapers[index] };
    }
  }
};
</script>
