<template>
  <div>
    <el-dialog
      class="scan-task-dialog page-dialog"
      :visible.sync="modalIsShow"
      fullscreen
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      append-to-body
      @open="dialogOpen"
    >
      <div class="scan-head" slot="title">
        <h3>
          扫描详情
          <span class="color-gray ml-2"
            >{{ task.courseName }}（{{ task.courseCode }}）</span
          >
        </h3>
        <div
          v-if="scanStatus === 'INIT'"
          class="scan-head-btn cont-link"
          @click="close"
        >
          <i class="el-icon-close"></i>
        </div>
      </div>

      <div class="scan-image-list">
        <div
          v-for="item in scanHistoryList"
          :key="item"
          class="scan-image-item"
          @click="toViewPaper(item)"
        >
          <img :src="item" />
        </div>
      </div>

      <div slot="footer">
        <el-button
          type="primary"
          :loading="scanStatus !== 'INIT'"
          @click="startTask"
        >
          {{ statusDesc[scanStatus] }}
        </el-button>
      </div>
    </el-dialog>

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

<script>
import { mapState } from "vuex";
import {
  getPreUploadFiles,
  saveOutputImage,
  clearDir,
  decodeImageCode,
} from "../../../plugins/imageOcr";
import db from "../../../plugins/db";
import { evokeScanner } from "../../../plugins/scanner";
import SimpleImagePreview from "@/components/SimpleImagePreview.vue";
import log4js from "@/plugins/logger";
const logger = log4js.getLogger("scan");

export default {
  name: "scan-task-dialog",
  components: {
    SimpleImagePreview,
  },
  props: {
    task: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: true,
      scanStatus: "INIT",
      realScanCount: 0,
      scanHistoryList: [],
      curPaper: {},
      statusDesc: {
        INIT: "开始扫描",
        SCAN: "扫描中",
        SAVING: "保存数据中",
      },
    };
  },
  computed: {
    ...mapState("client", ["ocrArea"]),
  },
  methods: {
    initData() {
      this.scanStatus = "INIT";
      this.realScanCount = 0;
      this.getScanHistory();
    },
    dialogOpen() {
      logger.info(`00进入扫描`);
      this.initData();
    },
    close() {
      this.modalIsShow = false;
      this.$emit("on-close");
      logger.info(`99退出扫描`);
    },
    open() {
      this.modalIsShow = true;
    },
    startTask() {
      logger.info(`01开始扫描`);
      this.scanStatus = "SCAN";
      this.evokeScanExe();
    },
    async evokeScanExe() {
      logger.info("02唤起扫描仪");
      // console.log(commandStr);
      await evokeScanner(this.GLOBAL.input).catch((error) => {
        console.error(error);
      });

      // 缓存已扫描的数据
      const res = getPreUploadFiles(this.GLOBAL.input);
      if (!res.succeed) {
        logger.error(`03扫描仪停止，故障：${res.errorMsg}`);
        this.$message.error(res.errorMsg);
        this.scanStatus = "INIT";
        return;
      }
      logger.info(`03扫描仪停止，扫描数：${res.data.length}`);
      this.scanStatus = "SAVING";
      await this.saveScanImage(res.data).catch(() => {
        this.$message.error("保存数据失败，请重新扫描！");
        logger.error(`保存数据失败，请重新扫描！`);
      });
      clearDir(this.GLOBAL.input);
      this.scanStatus = "INIT";
      await this.getScanHistory();
    },
    // scan relate
    async getScanHistory() {
      const res = await db
        .searchHistoryList({
          isFormal: this.task.isFormal ? 1 : 0,
          taskId: this.task.id,
        })
        .catch(() => {});
      if (!res) return;

      this.scanHistoryList = [];
      res.forEach((item) => {
        this.scanHistoryList.push(item.frontOriginImgPath);
        this.scanHistoryList.push(item.versoOriginImgPath);
      });

      this.curPaper = {};
      this.$refs.SimpleImagePreview.close();
    },
    async saveScanImage(imageList) {
      logger.info(`04-1开始保存数据`);
      for (let i = 0, len = imageList.length; i < len; i++) {
        const files = imageList[i];
        const ouputImageList = saveOutputImage(
          [files.frontFile, files.versoFile],
          {
            taskId: this.task.id,
          }
        );
        const fileInfo = {
          taskId: this.task.id,
          schoolId: this.task.schoolId,
          examId: this.task.examId,
          courseCode: this.task.courseCode,
          courseName: this.task.courseName,
          frontOriginImgPath: ouputImageList[0],
          versoOriginImgPath: ouputImageList[1],
          isFormal: this.task.isFormal ? 1 : 0,
          studentCode: "",
          clientUserId: this.user.id,
          clientUsername: this.user.loginName,
          clientUserLoginTime: this.user.loginTime,
        };

        if (this.task.isFormal) {
          const num = await decodeImageCode(
            fileInfo.frontOriginImgPath,
            this.ocrArea
          ).catch((err) => {
            console.error(err);
            logger.error(`04-2条码解析失败，${err}`);
          });
          console.log(num);
          fileInfo.studentCode = num || "";
          fileInfo.ocrArea = JSON.stringify(this.ocrArea);
        }
        let res = true;
        await db.saveUploadInfo(fileInfo).catch((err) => {
          res = false;
          console.error(err);
          logger.error(`04-1保存数据错误，${err}`);
        });
        if (!res) return Promise.reject();
      }

      logger.info(`04-2保存数据结束`);
    },
    // image-preview
    toViewPaper(imgUrl) {
      this.curPaper = { url: imgUrl };
      this.$refs.SimpleImagePreview.open();
    },
    toPrevPaper() {
      const curPaperIndex = this.scanHistoryList.findIndex(
        (item) => item === this.curPaper.url
      );
      if (curPaperIndex <= 0) return;
      this.curPaper = this.scanHistoryList[curPaperIndex - 1];
    },
    toNextPaper() {
      const curPaperIndex = this.scanHistoryList.findIndex(
        (item) => item === this.curPaper.url
      );
      if (curPaperIndex >= this.scanHistoryList.length - 1) return;
      this.curPaper = this.scanHistoryList[curPaperIndex + 1];
    },
  },
};
</script>
