<template>
  <div class="paper-manage page-container-flex">
    <div class="part-box part-box-filter part-box-head">
      <div class="part-box-head-left">
        <Form ref="FilterForm" label-position="left" inline>
          <FormItem>
            <Select
              v-model="filter.subject"
              @on-change="subjectChange"
              placeholder="科目"
            >
              <Option
                v-for="(item, index) in subjects"
                :key="index"
                :value="item.subject"
                :label="item.name"
              ></Option>
            </Select>
          </FormItem>
          <FormItem>
            <Select v-model="filter.areaCode" placeholder="选择考区" clearable>
              <Option
                v-for="area in areas"
                :key="area.id"
                :value="area.areaCode"
                :label="area.areaName"
              ></Option>
            </Select>
          </FormItem>
          <FormItem>
            <Input
              v-model="filter.startNumber"
              type="text"
              placeholder="输入开始编号"
              clearable
            />
          </FormItem>
          <FormItem>
            <Input
              v-model="filter.endNumber"
              type="text"
              placeholder="输入结束编号"
              clearable
            />
          </FormItem>
          <FormItem>
            <Select
              v-model="paperType"
              @on-change="typeChange"
              placeholder="类型"
            >
              <Option
                v-for="(val, key) in CAFA_EXCEPTION_TYPE"
                :key="key"
                :value="key"
                :label="val"
              ></Option>
            </Select>
          </FormItem>
          <FormItem>
            <Select
              v-model="filter.scanUserId"
              placeholder="选择采集账号"
              clearable
            >
              <Option
                v-for="user in scanUsers"
                :key="user.id"
                :value="user.name"
                :label="user.name"
              ></Option>
            </Select>
          </FormItem>
          <FormItem>
            <Input
              v-model.trim="filter.studentName"
              placeholder="输入姓名"
              clearable
            ></Input>
          </FormItem>
          <FormItem>
            <Select v-model="filter.sortBy" placeholder="排序方式" clearable>
              <Option
                v-for="(val, key) in SORT_RULE_TYPE"
                :key="key"
                :value="key"
                :label="val"
              ></Option>
            </Select>
          </FormItem>
          <FormItem>
            <Button
              size="small"
              class="btn-form-search"
              type="primary"
              @click="toPage(1)"
              >查询</Button
            >
          </FormItem>
        </Form>
      </div>
      <div class="part-box-head-right">
        <Button
          type="success"
          shape="circle"
          icon="upload-white icon"
          @click="toExportMark"
          >导出标记试卷</Button
        >
      </div>
    </div>

    <image-action-list
      v-if="papers.length"
      :data="papers"
      :actions="actions"
      @on-review="toReview"
      ref="ImageActionList"
    ></image-action-list>

    <div class="part-page" v-if="total > size">
      <Page
        :current="current"
        :total="total"
        :page-size="size"
        show-total
        show-elevator
        @on-change="toPage"
      ></Page>
    </div>

    <!-- image-preview -->
    <simple-image-preview
      :cur-image="curPaper"
      @on-prev="toPrevPaper"
      @on-next="toNextPaper"
      ref="SimpleImagePreview"
    ></simple-image-preview>
  </div>
</template>

<script>
import { paperPageList, subjectList, areaList, clientUserQuery } from "@/api";
import { SORT_RULE_TYPE, CAFA_EXCEPTION_TYPE } from "@/constants/enumerate";
import ImageActionList from "./components/ImageActionList";
import SimpleImagePreview from "@/components/SimpleImagePreview";

export default {
  name: "paper-manage",
  components: { ImageActionList, SimpleImagePreview },
  data() {
    return {
      filter: {
        workId: this.$route.params.workId,
        studentName: "",
        areaCode: "",
        startNumber: null,
        endNumber: null,
        subject: "",
        sortBy: "",
        scanUserId: "",
        isManual: null,
        missing: null,
        isRelate: null,
        isMark: null
      },
      SORT_RULE_TYPE,
      CAFA_EXCEPTION_TYPE: {},
      paperType: "9",
      confirmPaperType: "9",
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      totalPage: 0,
      papers: [],
      subjects: [],
      scanUsers: [],
      areas: [],
      curPaper: {},
      curPaperIndex: 0
    };
  },
  computed: {
    actions() {
      return this.confirmPaperType === "1"
        ? ["mark"]
        : ["rotate", "absent", "mark"];
    }
  },
  mounted() {
    this.CAFA_EXCEPTION_TYPE = {
      ...CAFA_EXCEPTION_TYPE,
      8: "已标记",
      9: "全部"
    };
    this.initData();
  },
  methods: {
    async initData() {
      await this.getSubjects();
      this.filter.subject = this.subjects[0].subject;
      this.filter.areaCode = "";
      this.areas = [];
      await this.getAreaList();
      if (!this.filter.areaCode) {
        this.filter.areaCode = this.areas[0].areaCode;
      }
      this.getScanUsers();
      this.toPage(1);
    },
    async getList() {
      const datas = {
        ...this.filter,
        page: this.current - 1,
        size: this.size
      };
      this.papers = [];
      const data = await paperPageList(datas);
      this.papers = data.data.map(paper => {
        const title = paper.manual
          ? `${paper.examNumber} ${paper.studentName}`
          : paper.examNumber;
        return {
          id: paper.id,
          key: this.$randomCode(),
          title,
          imgSrc: paper.imgSrc,
          thumbSrc: paper.thumbSrc,
          missing: paper.missing,
          isMark: paper.isMark,
          stage: paper.stage,
          styles: {},
          deg: 0
        };
      });
      this.total = data.totalCount;
      this.totalPage = data.pageCount;
    },
    toPage(page) {
      if (!this.filter.subject || !this.filter.areaCode) {
        this.$Message.error("请选择科目和考区！");
        return;
      }
      this.confirmPaperType = this.paperType;
      this.current = page;
      this.getList();
    },
    subjectChange() {
      this.filter.areaCode = "";
      this.areas = [];
      if (!this.filter.subject) return;
      this.getAreaList();
    },
    async getAreaList() {
      const data = await areaList({
        workId: this.filter.workId,
        subject: this.filter.subject
      });
      this.areas = data.map(item => {
        return {
          id: item.id,
          areaName: item.areaName,
          areaCode: item.areaCode
        };
      });
      if (this.areas.length === 1) {
        this.filter.areaCode = this.areas[0].areaCode;
      }
    },
    async getSubjects() {
      const data = await subjectList(this.filter.workId);
      this.subjects = data.filter(item => item.enable);
    },
    async getScanUsers() {
      const data = await clientUserQuery(this.filter.workId);
      this.scanUsers = data.data;
    },
    typeChange() {
      const typeToField = {
        0: "missing",
        1: "isManual",
        2: "isRelate",
        8: "isMark"
      };
      Object.values(typeToField).forEach(val => {
        this.filter[val] = typeToField[this.paperType] === val ? true : null;
      });
    },
    toExportMark() {
      window.open(
        this.urlAddAuthor(
          `${this.GLOBAL.domain}/api/export/paper/${this.filter.workId}/mark`
        )
      );
    },
    // paper view
    toReview(index) {
      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.current > 1) {
          this.current--;
          this.curPaperIndex = this.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.current === this.totalPage) {
          this.$Message.warning("当前已经是最后一条数据了");
          return;
        } else {
          this.current++;
          this.curPaperIndex = 0;
          await this.getList();
        }
      } else {
        this.curPaperIndex++;
      }

      this.selectPaper(this.curPaperIndex);
    }
  }
};
</script>
