<template>
  <div class="scan-paper">
    <div class="part-box part-box-pad part-box-flex scan-head">
      <div>
        <h2>课程（代码）：{{ task.courseName }}（{{ task.courseCode }}）</h2>
      </div>
      <div>
        <el-button :disabled="!hasSelectedData" type="primary" @click="toBind"
          >重新绑定</el-button
        >
        <el-button :disabled="!canSave" type="danger" @click="clearStage"
          >清空</el-button
        >
        <el-button
          :disabled="!canSave"
          :loading="saving"
          type="primary"
          @click="toSave"
          >保存</el-button
        >
        <el-button
          type="primary"
          :loading="scanStatus === 'SCAN'"
          :disabled="!canScan"
          @click="toScan"
        >
          {{ statusDesc[scanStatus] }}
        </el-button>
      </div>
    </div>

    <div class="scan-body">
      <div class="scan-result">
        <div class="mb-4 tab-btns scan-result-head">
          <el-button
            size="medium"
            :type="curTab === 'normal' ? 'primary' : 'default'"
            @click="switchTab('normal')"
            >正常 <span>[{{ normalCount }}]</span></el-button
          >
          <el-button
            size="medium"
            :type="curTab === 'error' ? 'danger' : 'default'"
            @click="switchTab('error')"
            >异常
            <span class="color-danger">[{{ errorCount }}]</span></el-button
          >
        </div>
        <div class="scan-result-table">
          <scan-result-table
            v-if="isNormalTab"
            ref="scanResultTableRef"
            :datas="scanStageList"
            @row-click="rowClickHandle"
            @select-change="selectChange"
            @delete-paper="deletePaperHandle"
          ></scan-result-table>
          <scan-result-table
            v-else
            ref="scanResultTableRef"
            :datas="errorStageList"
            @row-click="rowClickHandle"
            @select-change="selectChange"
            @delete-paper="deletePaperHandle"
          ></scan-result-table>
        </div>
        <div class="scan-result-foot">
          共{{ studentCount }}人，{{ paperCount }}张图片
        </div>
      </div>
      <div class="scan-content">
        <image-contain
          v-if="curPaper && curPaper.url"
          ref="ImageContain"
          :image="curPaper"
          @on-prev="toPrevPaper"
          @on-next="toNextPaper"
        ></image-contain>
      </div>
    </div>

    <!-- ManualBindDialog -->
    <manual-bind-dialog
      ref="ManualBindDialog"
      :datas="selectList"
      @confirm="bindConfirm"
    ></manual-bind-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
import {
  getPreUploadFiles,
  saveOutputImage,
  clearDir,
  decodeImageCode,
  getDirScanFile,
} from "../../../plugins/imageOcr";
import db from "../../../plugins/db";
import { evokeScanner } from "../../../plugins/scanner";
import ImageContain from "@/components/ImageContain.vue";
import ScanResultTable from "../components/ScanResultTable.vue";
import ManualBindDialog from "../components/ManualBindDialog.vue";
import timeMixins from "@/mixins/setTimeMixins";
import { getStudentInfo } from "../api";
import log4js from "@/plugins/logger";
import { randomCode, calcSum } from "@/plugins/utils";
import { getStageDir } from "@/plugins/env";
const logger = log4js.getLogger("scan");

export default {
  name: "scan-paper",
  mixins: [timeMixins],
  components: { ImageContain, ScanResultTable, ManualBindDialog },
  data() {
    return {
      task: this.$ls.get("task", {}),
      scanStatus: "INIT",
      scanStageList: [],
      errorStageList: [],
      selectList: [],
      statusDesc: {
        INIT: "开始扫描",
        SCAN: "扫描中",
        FINISH: "继续扫描",
      },
      user: this.$ls.get("user", {}),
      saving: false,
      maxCacheCount: 120,
      lastStudentCode: "",
      scanCount: 0,
      menus: [
        { code: "normal", name: "正常" },
        { code: "error", name: "异常" },
      ],
      curTab: "normal",
      // 非等待模式：delayMode:0
      looping: false,
      // 图片预览
      curPapers: [],
      curPaperIndex: 0,
      curPaper: { url: "" },
      stageDir: getStageDir(),
    };
  },
  computed: {
    ...mapState("client", ["ocrArea"]),
    canSave() {
      return this.scanStatus === "FINISH" && this.scanStageList.length;
    },
    canScan() {
      return this.scanStageList.length <= this.maxCacheCount;
    },
    hasSelectedData() {
      return Boolean(this.selectList.length);
    },
    IS_DELAY_MODE() {
      return this.GLOBAL.delayMode === 1;
    },
    errorCount() {
      return calcSum(this.errorStageList.map((item) => item.papers.length));
    },
    normalCount() {
      return calcSum(this.scanStageList.map((item) => item.papers.length));
    },
    isNormalTab() {
      return this.curTab === "normal";
    },
    studentCount() {
      return this.isNormalTab
        ? this.scanStageList.length
        : this.errorStageList.length;
    },
    paperCount() {
      return this.isNormalTab ? this.normalCount : this.errorCount;
    },
  },
  beforeDestroy() {
    this.stopLoopScaningFile();
  },
  methods: {
    initData() {
      this.lastStudentCode = "";
      this.scanStageList = [];
      this.errorStageList = [];
      this.scanStatus = "INIT";
      this.curPagePapers = [];
      this.curPagePaperIndex = 0;
      this.curPagePaper = { url: "" };
      this.scanCount = 0;
    },
    clearFiles() {
      clearDir(this.stageDir);
    },
    async goBackHandle() {
      if (this.scanStageList.length) {
        const res = await this.$confirm(
          `当前存在未保存的扫描数据，确定要退出吗?`,
          "警告",
          {
            type: "warning",
          }
        ).catch(() => {});
        if (res !== "confirm") return;
      }

      logger.info(`99退出扫描`);
    },
    switchTab(tab) {
      this.$refs.scanResultTableRef.clearSelection();
      this.curTab = tab;
      this.selectList = [];
    },
    // scan
    toScan() {
      if (!this.canScan) {
        this.$message.error("已超过最大缓存数量，请先保存数据再继续扫描！");
        return;
      }
      if (this.scanStatus === "INIT") {
        this.startTask();
      } else {
        this.continueTask();
      }
    },
    startTask() {
      logger.info(`01开始扫描`);
      this.continueTask();
    },
    continueTask() {
      this.scanStatus = "SCAN";
      if (this.IS_DELAY_MODE) {
        this.evokeScanExe();
      } else {
        this.evokeScanExeNotDelay();
      }
    },
    async evokeScanExe() {
      logger.info("02唤起扫描仪");
      await evokeScanner(this.GLOBAL.input).catch((error) => {
        console.error(error);
      });

      // 缓存已扫描的数据
      const res = getPreUploadFiles(this.GLOBAL.input, true);
      if (!res.succeed) {
        logger.error(`03扫描仪停止，故障：${res.errorMsg}`);
        this.$message.error(res.errorMsg);
        this.scanStatus = "FINISH";
        return;
      }
      logger.info(`03扫描仪停止，扫描数：${res.data.length}`);
      await this.stageScanImage(res.data);
      this.scanStatus = "FINISH";
      logger.info(`03-1完成条码解析`);
    },
    async evokeScanExeNotDelay() {
      logger.info("02唤起扫描仪");
      this.looping = true;
      this.loopScaningFile();

      await evokeScanner(this.GLOBAL.input).catch((error) => {
        console.error(error);
      });
      this.stopLoopScaningFile();
      await this.getScaningFile();

      const scanCount = this.scanStageList.length - this.scanCount;
      this.scanCount = this.scanStageList.length;

      // 已扫描的数据
      const res = getPreUploadFiles(this.GLOBAL.input);
      this.scanStatus = "FINISH";
      if (!res.succeed) {
        logger.error(
          `03扫描仪停止，扫描数：${scanCount}，故障：${res.errorMsg}`
        );
        this.$message.error(res.errorMsg);
        return;
      }
      logger.info(`03扫描仪停止，扫描数：${scanCount}`);
    },
    async stageScanImage(imageList) {
      const ocrAreaContent = JSON.stringify(this.ocrArea);
      for (let i = 0, len = imageList.length; i < len; i++) {
        const fileInfo = {
          id: "",
          taskId: this.task.id,
          schoolId: this.task.schoolId,
          semesterId: this.task.semesterId,
          examId: this.task.examId,
          courseCode: this.task.courseCode,
          courseName: this.task.courseName,
          frontOriginImgPath: imageList[i].frontFile,
          versoOriginImgPath: imageList[i].versoFile,
          isFormal: 1,
          studentName: "",
          studentCode: "",
          ocrArea: ocrAreaContent,
          clientUserId: this.user.id,
          clientUsername: this.user.loginName,
          clientUserLoginTime: this.user.loginTime,
          select: false,
        };

        const code = await decodeImageCode(
          fileInfo.frontOriginImgPath,
          this.ocrArea
        ).catch((err) => {
          console.error(err);
          logger.error(`03条码解析失败，${err}`);
        });
        fileInfo.studentCode = code || this.lastStudentCode;
        // 按照识别空自动绑定前一张code的规则，无论识别到的code是否合法，都应该作为最后一次识别的code
        // 否则，第一张进异常，后面空白条码页会自动进正常页面，对后续处理带来一定困扰
        if (fileInfo.studentCode) {
          this.lastStudentCode = fileInfo.studentCode;
        }

        fileInfo.id = `${fileInfo.studentCode || 0}-${randomCode(16)}`;

        const studentStage = this.scanStageList.find(
          (item) => item.studentCode === fileInfo.studentCode
        );
        if (studentStage) {
          studentStage.papers.push(fileInfo);
          continue;
        }

        const res = await getStudentInfo({
          courseCode: this.task.courseCode,
          studentCode: fileInfo.studentCode,
        }).catch(() => {});
        if (res) {
          fileInfo.studentName = res.studentName;
          this.scanStageList.push({
            id: res.id,
            studentCode: res.studentCode,
            studentName: res.studentName,
            courseCode: res.courseCode,
            courseName: res.courseName,
            teacher: res.teacher,
            teachClass: res.teachClass,
            collegeName: res.collegeName,
            majorName: res.majorName,
            className: res.className,
            score: res.score,
            remark: res.remark,
            select: false,
            papers: [fileInfo],
          });
          continue;
        }

        const errorStudentStage = this.errorStageList.find(
          (item) => item.studentCode === fileInfo.studentCode
        );
        if (errorStudentStage) {
          errorStudentStage.papers.push(fileInfo);
          continue;
        }

        this.errorStageList.push({
          id: `none-${randomCode(16)}`,
          studentCode: fileInfo.studentCode,
          select: false,
          papers: [fileInfo],
        });
      }
    },
    async saveScanItem(fileInfo) {
      const ouputImageList = saveOutputImage(
        [fileInfo.frontOriginImgPath, fileInfo.versoOriginImgPath],
        {
          courseCode: this.task.courseCode,
        }
      );

      fileInfo.frontOriginImgPath = ouputImageList[0];
      fileInfo.versoOriginImgPath = ouputImageList[1];

      await db.saveUploadInfo(fileInfo);
    },
    async toSave() {
      if (this.errorStageList.length) {
        this.$message.error("还有异常数据未处理！");
        return;
      }

      if (!this.scanStageList.length) {
        this.$message.error("当前无要保存的数据！");
        return;
      }

      if (this.saving) return;
      this.saving = true;

      const datas = this.scanStageList.map((item) => item.papers).flat();
      // TODO: 使用批量保存，有时间再做
      logger.info(`04-1开始保存数据`);
      for (let i = 0, len = datas.length; i < len; i++) {
        const fileInfo = datas[i];

        let res = true;
        await this.saveScanItem(fileInfo).catch((err) => {
          res = false;
          console.error(err);
          logger.error(`04-1保存数据错误，${err}`);
        });
        if (!res) {
          this.saving = false;
          this.$message.error("保存数据错误，请重新尝试！");
          return Promise.reject();
        }
      }

      this.$message.success("保存成功！");
      this.saving = false;
      logger.info(`04-2保存数据成功`);
      this.clearFiles();
      this.initData();
    },
    // delay mode
    // 实时获取扫描图片
    async loopScaningFile() {
      this.clearSetTs();
      if (!this.looping) return;
      await this.getScaningFile();

      this.addSetTime(this.loopScaningFile, 1 * 1000);
    },
    stopLoopScaningFile() {
      this.clearSetTs();
      this.looping = false;
    },
    async getScaningFile() {
      const newScanFiles = getDirScanFile(this.GLOBAL.input);
      await this.stageScanImage(newScanFiles, true);
    },
    // table action
    toBind() {
      if (!this.selectList.length) return;
      this.$refs.ManualBindDialog.open();
    },
    bindConfirm(studentInfo) {
      if (this.isNormalTab) {
        this.normalBind(studentInfo);
      } else {
        this.errorBind(studentInfo);
      }
      this.clearViewPapers();
      this.$refs.scanResultTableRef.clearSelection();
    },
    normalBind(studentInfo) {
      const selectPaperIds = this.selectList
        .map((item) => item.papers.map((p) => p.id))
        .flat();
      let prevIndex = this.scanStageList.findIndex(
        (row) => row.id === this.selectList[0].id
      );

      // 删除选择的数据
      this.scanStageList.forEach((row) => {
        row.papers = row.papers.filter((p) => !selectPaperIds.includes(p.id));
      });

      this.scanStageList = this.scanStageList.filter(
        (row) => row.papers.length
      );

      // 绑定逻辑
      const preAddPapers = this.selectList
        .map((row) => {
          return row.papers.map((p) => {
            return {
              ...p,
              studentCode: studentInfo.studentCode,
              studentName: studentInfo.studentName,
              id: `${stageStudent.studentCode}-${randomCode(16)}`,
            };
          });
        })
        .flat();

      const stageStudent = this.scanStageList.find(
        (row) => row.studentCode === studentInfo.studentCode
      );
      if (stageStudent) {
        stageStudent.papers.push(...preAddPapers);
        return;
      }

      prevIndex = Math.max(
        0,
        Math.min(prevIndex, this.scanStageList.length - 1)
      );

      this.scanStageList.splice(prevIndex, 0, {
        ...studentInfo,
        papers: preAddPapers,
      });
    },
    errorBind(studentInfo) {
      const selectPaperIds = this.selectList
        .map((item) => item.papers.map((p) => p.id))
        .flat();

      // 删除选择的数据
      this.errorStageList.forEach((row) => {
        row.papers = row.papers.filter((p) => !selectPaperIds.includes(p.id));
      });

      this.errorStageList = this.errorStageList.filter(
        (row) => row.papers.length
      );

      // 绑定逻辑
      const preAddPapers = this.selectList
        .map((row) => {
          return row.papers.map((p) => {
            return {
              ...p,
              studentCode: studentInfo.studentCode,
              studentName: studentInfo.studentName,
              id: `${stageStudent.studentCode}-${randomCode(16)}`,
            };
          });
        })
        .flat();

      const stageStudent = this.scanStageList.find(
        (row) => row.studentCode === studentInfo.studentCode
      );
      if (stageStudent) {
        stageStudent.papers.push(...preAddPapers);
        return;
      }

      this.scanStageList.push({
        ...studentInfo,
        papers: preAddPapers,
      });
    },
    async clearStage() {
      const res = await this.$confirm(`确定要清空数据吗?`, "警告", {
        type: "warning",
      }).catch(() => {});
      if (res !== "confirm") return;

      this.initData();
      this.clearFiles();
      logger.info(`99数据清空`);
      this.$message.success("数据已清空！");
    },
    selectChange(data) {
      this.selectList = data;
    },
    deletePaperHandle(deletedPapers) {
      this.curPapers = this.curPapers.filter((p) => !deletedPapers.includes(p));
      if (!this.curPapers.length) {
        this.curPaperIndex = 0;
        this.curPaper = { url: "" };
        return;
      }

      if (deletedPapers.includes(this.curPaper.url)) {
        this.curPaperIndex = 0;
        this.setCurPaper(0);
        return;
      }

      this.curPaperIndex = this.curPapers.indexOf(this.curPaper.url);
    },
    // image-preview
    rowClickHandle({ curPapers, curPagePaperIndex }) {
      this.curPapers = curPapers;
      this.curPaperIndex = curPagePaperIndex;
      this.setCurPaper(curPagePaperIndex);
    },
    clearViewPapers() {
      this.curPapers = [];
      this.curPaperIndex = 0;
      this.curPaper = { url: "" };
    },
    setCurPaper(index) {
      this.curPaper = { url: this.curPapers[index] };
    },
    toPrevPaper() {
      if (this.curPaperIndex <= 0) {
        this.$message.error("没有上一页了");
        return;
      }
      this.setCurPaper(this.curPaperIndex - 1);
    },
    toNextPaper() {
      if (this.curPaperIndex >= this.curPapers.length - 1) {
        this.$message.error("没有下一页了");
        return;
      }
      this.setCurPaper(this.curPaperIndex + 1);
    },
  },
};
</script>
