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

/**
 * 上传流程：
 * 1、先取数据库中所有未上传的记录，生成上传任务列表，开启当前上传周期。
 * 2、当前上传周期内新采集的图片追加进当前上传周期。
 * 3、当前上传周期内上传失败的图片进入下次上传周期。
 * 4、当前上传周期结束之后，定时开启下次上传周期。
 */
export default {
  data() {
    return {
      uploadTask: "",
      setT: ""
    };
  },
  computed: {
    uploadNo() {
      return this.$store.state.uploadNo;
    }
  },
  methods: {
    async addUploadTask(task) {
      const id = await db.saveUploadInfo(task).catch(err => {
        console.log(err);
      });
      if (id) {
        task.id = id;
        this.uploadTask.addUploadTask(task);
      }
    },
    async uploadSuccessCallback(curUploadTask) {
      await db.updateUploadState(curUploadTask.id);
      this.$store.commit("setUploadNo", this.uploadNo + 1);
    },
    async initUploadTask() {
      if (this.setT) clearTimeout(this.setT);
      // 今日事今日毕的前提下，上传任务只取当天未上传的记录。
      // const curDate = getLocalDate();
      const unuploadList = await db.searchUploadList({
        // createdTime: curDate,
        isUpload: 0
      });
      // 创建上传任务
      this.uploadTask = new UploadTask({
        taskList: unuploadList,
        uploadSuccessCallback: curUploadTask => {
          this.uploadSuccessCallback(curUploadTask);
        },
        uploadTaskOverCallback: () => {
          this.setT = setTimeout(() => {
            this.initUploadTask();
          }, 5 * 1000);
        }
      });
    },
    stopUpload() {
      this.uploadTask && this.uploadTask.stopUploadTask();
    }
  }
};
