<template>
  <el-dialog
    class="scan-task-dialog"
    :visible.sync="modalIsShow"
    top="10vh"
    width="550px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    append-to-body
    @open="visibleChange"
  >
    <div class="scan-head" slot="title">
      <h3>扫描</h3>
      <div
        v-if="scanStatus !== 'START'"
        class="scan-head-btn cont-link"
        @click="closeDialog"
      >
        <i class="el-icon-close"></i>
      </div>
    </div>
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="课程名称：">
        {{ task.courseName }}
      </el-form-item>
      <el-form-item prop="preScanCount" label="预扫张数：">
        <el-input-number
          v-model="modalForm.preScanCount"
          :min="0"
          :max="1000000"
          :step="1"
          step-strictly
          :controls="false"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="实扫张数：">
        <span class="color-danger">
          {{ realScanCount }}
        </span>
        <i v-if="scanStatus === 'START'" class="el-icon-loading"></i>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button v-if="scanStatus === 'INIT'" type="primary" @click="startTask"
        >开始扫描</el-button
      >
      <el-button
        v-if="scanStatus === 'PAUSE'"
        type="primary"
        @click="continueTask"
        >继续扫描</el-button
      >
      <el-button v-if="scanStatus === 'PAUSE'" type="primary" @click="confirm"
        >确认</el-button
      >
      <el-button v-if="scanStatus === 'PAUSE'" @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { bingScanUser } from "../api";
import {
  getPreUploadFiles,
  getPreUploadFileCount,
  saveOutputImage,
  renamePreUploadJsonFile,
  clearDir
} from "../../../plugins/imageOcr";
import setTimeMixins from "../../../mixins/setTimeMixins";
import db from "../../../plugins/db";
import { evokeScanner } from "../../../plugins/scanner";
import log4js from "@/plugins/logger";
const logger = log4js.getLogger("scan");

export default {
  name: "scan-task-dialog",
  props: {
    task: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  mixins: [setTimeMixins],
  data() {
    return {
      modalIsShow: false,
      loading: false,
      user: this.$ls.get("user", { id: "" }),
      scanStatus: "INIT", // INIT:初始状态，START:已开始，PAUSE:已暂停
      modalForm: {
        preScanCount: 0
      },
      rules: {
        preScanCount: [
          {
            required: true,
            message: "请输入预扫张数",
            trigger: "change"
          }
        ]
      },
      scaningImageList: [],
      realScanCount: 0,
      taskScanUserId: ""
    };
  },
  computed: {
    taskBound() {
      return this.user.id === this.taskScanUserId;
    }
  },
  beforeDestroy() {
    this.clearSetTs();
  },
  methods: {
    initData() {
      this.loading = false;
      this.modalForm.preScanCount = undefined;
      this.scaningImageList = [];
      this.scanStatus = "INIT";
      this.realScanCount = 0;
    },
    visibleChange() {
      logger.info(`00进入扫描`);
      this.taskScanUserId = this.task.scanUserId;
      this.initData();
    },
    close() {
      this.modalIsShow = false;
      this.$emit("on-close");
      logger.info(`99退出扫描`);
    },
    open() {
      this.modalIsShow = true;
    },
    closeDialog() {
      if (this.scanStatus === "START") return;

      if (this.scanStatus === "INIT") {
        this.close();
        return;
      }

      this.cancel();
    },
    async startTask() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

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

      if (!this.taskBound) {
        await bingScanUser({
          paperScanTaskId: this.task.id,
          userId: this.user.id
        });
        this.taskScanUserId = this.user.id;
      }
      logger.info(`01开始扫描`);
      this.scaningImageList = [];
      this.scanStatus = "START";
      this.getInitFile();

      this.evokeScanExe();
    },
    async continueTask() {
      logger.info(`01继续扫描`);
      this.scanStatus = "START";
      this.getInitFile();

      this.evokeScanExe();
    },
    async evokeScanExe() {
      logger.info("02唤起扫描仪");
      // console.log(commandStr);
      await evokeScanner(this.GLOBAL.input).catch(error => {
        console.error(error);
      });
      this.scanStatus = "PAUSE";

      // 缓存已扫描的数据
      const res = getPreUploadFiles(this.GLOBAL.input);
      if (!res.succeed) {
        logger.error(`03扫描仪停止，故障：${res.errorMsg}`);
        this.$message.error(res.errorMsg);
        return;
      }
      logger.info(`03扫描仪停止，扫描数：${res.data.length}`);
      this.scaningImageList.push(...res.data);
      // console.log(this.scaningImageList);
      renamePreUploadJsonFile(this.GLOBAL.input);
    },
    async confirm() {
      if (!this.scaningImageList.length) {
        this.$message.error("当前没有需要保存的数据！");
        return;
      }
      if (this.realScanCount !== this.modalForm.preScanCount) {
        this.$message.error("实扫张数与预扫张数不一致！");
        return;
      }
      logger.info(`04-1开始保存数据`);
      await this.saveScanImage();
      logger.info(`04-2保存数据结束`);

      const confirm = await this.$confirm(`是否继续扫描?`, "提示", {
        type: "warning"
      }).catch(() => {});

      if (confirm !== "confirm") {
        this.close();
        return;
      }

      this.initData();
    },
    async cancel() {
      const confirm = await this.$confirm(
        `取消扫描后，当前未保存的数据将会被清空，确定要取消扫描吗?`,
        "提示",
        {
          type: "warning"
        }
      ).catch(() => {});
      if (confirm !== "confirm") return;

      this.clearScanList();
      this.close();
    },
    // scan relate
    getInitFile() {
      this.clearSetTs();
      if (this.scanStatus !== "START") return;

      this.realScanCount = getPreUploadFileCount(this.GLOBAL.input);
      this.addSetTime(() => {
        this.getInitFile();
      }, 500);
    },
    async saveScanImage() {
      for (let i = 0, len = this.scaningImageList.length; i < len; i++) {
        const files = this.scaningImageList[i];
        const ouputImageList = saveOutputImage(
          [files.frontFile, files.versoFile],
          {
            taskId: this.task.id
          }
        );
        const fileInfo = {
          taskId: this.task.id,
          taskName: this.task.scanTaskName,
          courseCode: "",
          courseName: this.task.courseName,
          teachingClassName: this.task.teachClazzName,
          frontOriginImgPath: ouputImageList[0],
          versoOriginImgPath: ouputImageList[1],
          clientUserId: this.user.id,
          clientUsername: this.user.name,
          clientUserLoginTime: this.user.loginTime
        };

        await db.saveUploadInfo(fileInfo).catch(err => {
          console.error(err);
          logger.error(`04-1保存数据错误，${err}`);
        });
      }
    },
    clearScanList() {
      this.scaningImageList = [];
      clearDir(this.GLOBAL.input);
    }
  }
};
</script>
