import db from "../plugins/db";
import UploadTask from "../plugins/imageUpload";
// import { getLocalDate } from "../plugins/utils";

/**
 * 上传流程：
 * 1、先取数据库中所有未上传的记录，生成上传任务列表，开启当前上传周期。
 * 2、当前上传周期内新采集的图片追加进当前上传周期。
 * 3、当前上传周期内上传失败的图片进入下次上传周期。
 * 4、当前上传周期结束之后，定时开启下次上传周期。
 */
export default {
  data() {
    return {
      uploadTask: null,
      taskSetTs: []
    };
  },
  methods: {
    async addUploadTask(task) {
      await db.saveUploadInfo(task).catch(err => {
        console.log(err);
      });
    },
    async uploadSuccessCallback(curUploadTask) {
      await db.updateUploadState(curUploadTask.id);
    },
    async initUploadTask() {
      this.clearTaskSetTs();
      const unuploadList = await db.searchUploadList({
        isUpload: 0,
        clientUserId: this.$ls.get("user", { id: "" }).id
      });
      // 创建上传任务
      this.uploadTask = new UploadTask({
        taskList: unuploadList,
        uploadSuccessCallback: curUploadTask => {
          this.uploadSuccessCallback(curUploadTask);
        },
        uploadTaskOverCallback: () => {
          if (!this.uploadTask) return;
          this.taskSetTs.push(
            setTimeout(() => {
              this.initUploadTask();
            }, 1 * 1000)
          );
        },
        uploadErrorCallBack: curUploadTask => {
          const content = `任务：${curUploadTask.taskId}，采集Id：${curUploadTask.id}，图片上传失败！`;
          console.log(content);
          return;
        }
      });
    },
    stopUpload() {
      this.clearTaskSetTs();
      this.uploadTask && this.uploadTask.stopUploadTask();
      this.uploadTask = null;
    },
    clearTaskSetTs() {
      if (!this.taskSetTs.length) return;
      this.taskSetTs.forEach(t => clearTimeout(t));
      this.taskSetTs = [];
    }
  }
};
