<template>
  <Modal
    class="cropper-task-detail-dialog"
    v-model="modalIsShow"
    :title="title"
    :mask-closable="false"
    fullscreen
    footer-hide
    @on-visible-change="visibleChange"
  >
    <div class="cropper-task-detail">
      <div class="task-list" id="task-list">
        <div class="task-list-body" v-if="taskList.length">
          <div
            v-for="(task, index) in taskList"
            :key="index"
            :id="`task-${task.id}`"
            :class="[
              'task-item',
              {
                'task-current': task.id === curTask.id,
                'task-over': task.isFinished
              }
            ]"
            @click="toDo(task)"
          >
            <div class="task-item-icon">
              <Icon type="ios-document" />
            </div>
            <p>{{ task.filename }}</p>
          </div>
        </div>
      </div>
      <div class="task-main">
        <div class="task-progress">
          <div class="task-progress-tips">
            <span>{{ finishedCount }}</span
            ><span>/</span><span>{{ taskCount }}</span>
          </div>
          <div class="task-progress-body">
            <Progress :percent="taskProgress" />
          </div>
        </div>
        <div class="task-body">
          <div class="task-body-item task-org">
            <scan-area-steps
              v-if="curTask.originImgPath && modalIsShow && curCollectConfig"
              :image-url="curTask.originImgPath"
              :cur-setting="curCollectConfig"
              :key="curTask.key"
              @on-finished="finished"
            ></scan-area-steps>
            <div v-else><p class="task-none">暂无数据</p></div>
          </div>
          <div class="task-body-item task-finally">
            <div class="task-finally-body">
              <img
                v-if="curTask.sliceImgPath"
                class="img-contain"
                :src="curTask.sliceImgPath"
                alt="裁切图"
              />
            </div>
            <div v-if="curTask.sliceImgPath" class="task-action box-justify">
              <h5>处理结果</h5>
              <Button
                type="primary"
                :disabled="loading"
                @click="toComfirmAndNext"
              >
                确认并下一个
              </Button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </Modal>
</template>

<script>
import ScanAreaSteps from "../client/components/ScanAreaSteps";
import {
  getCropperTaskDetailList,
  getCropperTaskFinishCount,
  updateCropperTaskDetail,
  updateCropperTaskFinishedCount
} from "../../plugins/db";
import { saveCropperImage, downloadOriginImg } from "./taskUtils";
import { formatDate, randomCode } from "../../plugins/utils";
import { getPaperInfo } from "./api";
// const path = require("path");
// const fs = require("fs");

export default {
  name: "cropper-task-detail-dialog",
  components: { ScanAreaSteps },
  props: {
    cropperTask: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  computed: {
    title() {
      return this.cropperTask.name;
    }
  },
  data() {
    return {
      modalIsShow: false,
      curTask: {},
      taskList: [],
      curCollectConfig: {},
      taskCount: 0,
      finishedCount: 0,
      taskProgress: 0,
      loading: false
    };
  },
  methods: {
    visibleChange(visible) {
      if (visible) {
        this.initData();
      } else {
        this.$emit("modified");
      }
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async initData() {
      await this.getTasks();

      this.taskCount = this.cropperTask.taskCount;
      this.finishedCount = this.cropperTask.finishedCount;
      this.taskProgress =
        ((100 * this.finishedCount) / this.taskCount).toFixed(2) * 1;

      const nextTaskIndex = this.taskList.findIndex(item => !item.isFinished);
      if (nextTaskIndex === -1) {
        this.$Message.success("当前任务已全部结束");
      } else {
        this.curCollectConfig =
          nextTaskIndex === 0
            ? {}
            : JSON.parse(this.taskList[nextTaskIndex - 1].cropperSet);
        this.toDo(this.taskList[nextTaskIndex]);
        this.scrollTaskList(this.curTask.id);
      }
    },
    async getTasks() {
      const data = await getCropperTaskDetailList(this.cropperTask.id);
      this.taskList = data || [];
    },
    async updateProgress() {
      this.finishedCount = await getCropperTaskFinishCount(this.cropperTask.id);
      await updateCropperTaskFinishedCount({
        id: this.cropperTask.id,
        finishedCount: this.finishedCount
      });
      this.taskProgress =
        ((100 * this.finishedCount) / this.taskCount).toFixed(2) * 1;
    },
    scrollTaskList(taskId) {
      const taskDom = document.getElementById(`task-${taskId}`);
      const scrollTop = Math.max(0, taskDom.offsetTop - 84);
      document.getElementById("task-list").scrollTop = scrollTop;
    },
    async getOriginImg(paperInfo) {
      if (paperInfo.originImgPath) return paperInfo.originImgPath;

      const pInfo = await getPaperInfo({
        workId: paperInfo.workId,
        subjectId: paperInfo.subjectId,
        examNumber: paperInfo.examNumber
      }).catch(() => {});
      if (!pInfo) {
        this.$Message.error("获取原图失败，请重新尝试！");
        return;
      }

      this.curTask.paperId = paperInfo.id;

      const outputOriginPath = await downloadOriginImg({
        ...paperInfo,
        url: pInfo.imgSrc
      }).catch(() => {});
      if (!outputOriginPath) {
        this.$Message.error("下载原图失败，请重新尝试！");
        return;
      }

      this.curTask.originImgPath = outputOriginPath;
    },
    async toDo(task) {
      this.curTask = {
        ...task,
        key: randomCode()
      };
      await this.getOriginImg(task);

      // 在没有裁切图的情况下，自动根据已保存的设置信息生成裁切图。
      if (!this.curTask.sliceImgPath && this.curCollectConfig["codeArea"]) {
        this.loading = true;
        let res = await this.saveCurImage().catch(() => {});
        this.loading = false;
        if (!res) return;
      }
    },
    async curTaskFinished(setting) {
      await updateCropperTaskDetail({
        id: this.curTask.id,
        cropperSet: JSON.stringify(setting),
        originImgPath: this.curTask.originImgPath,
        formalImgPath: this.curTask.formalImgPath,
        sliceImgPath: this.curTask.sliceImgPath,
        isFinished: 1,
        isUpload: 0,
        updateTime: formatDate()
      });
      await this.updateProgress();

      const curTask = this.taskList.find(item => item.id === this.curTask.id);
      curTask.isFinished = true;

      return true;
    },
    async saveCurImage() {
      let res = await saveCropperImage(
        this.curTask,
        this.curCollectConfig
      ).catch(() => {});
      if (!res) {
        return Promise.reject();
      }

      this.curTask.sliceImgPath = res.outputSlicelPath;
      this.curTask.formalImgPath = res.outputFormalPath;
      return true;
    },
    async finished(setting) {
      if (this.loading) return;
      this.loading = true;

      this.curCollectConfig = setting;

      let res = await this.saveCurImage().catch(() => {
        this.loading = false;
      });
      if (!res) {
        this.$Message.error("保存图片失败，请重新尝试！");
        return;
      }

      res = await this.curTaskFinished(setting).catch(() => {});
      this.loading = false;
      if (!res) {
        this.$Message.error("更新图片失败，请重新尝试！");
        return;
      }

      this.toNextTask();
    },
    async toComfirmAndNext() {
      if (this.loading) return;
      this.loading = true;

      const res = await this.curTaskFinished(
        this.curCollectConfig
      ).catch(() => {});
      this.loading = false;
      if (!res) {
        this.$Message.error("更新图片失败，请重新尝试！");
        return;
      }

      this.toNextTask();
    },
    toNextTask() {
      const nextTask = this.taskList.find(item => !item.isFinished);
      if (!nextTask) {
        this.$Message.success("当前任务已全部结束");
        return;
      }

      this.toDo(nextTask);
      this.scrollTaskList(this.curTask.id);
    }
  }
};
</script>
