const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
import { uploadFormalImage } from "../modules/client/api";
import { Message } from "element-ui";

/**
 * 文件上传
 * @param {Object} options 上传信息
 */
function toUploadImg(options) {
  const formData = new FormData();
  // frontFile,frontMd5,versoFile,versoMd5,taskId

  const { file: frontFile, md5: frontMd5 } = getFileAdnMd5(
    options.frontOriginImgPath
  );
  formData.append("frontMd5", frontMd5);
  formData.append("frontFile", frontFile);
  const { file: versoFile, md5: versoMd5 } = getFileAdnMd5(
    options.versoOriginImgPath
  );
  formData.append("versoMd5", versoMd5);
  formData.append("versoFile", versoFile);

  formData.append("paperScanTaskId", options.taskId);

  return uploadFormalImage(formData);
}

function getFileAdnMd5(filepath) {
  const buffer = fs.readFileSync(filepath);
  let fsHash = crypto.createHash("md5");
  fsHash.update(buffer);
  const md5 = fsHash.digest("hex");
  const file = new File([buffer], path.basename(filepath));
  return { file, md5 };
}

/**
 * 获取文件的MD5
 * @param {String} source 文件路径
 */
// function getMD5(source) {
//   const buffer = fs.readFileSync(source);
//   let fsHash = crypto.createHash("md5");
//   fsHash.update(buffer);
//   return fsHash.digest("hex");
// }

let messageInst = null;

class UploadTask {
  constructor({
    taskList,
    uploadSuccessCallback,
    uploadTaskOverCallback,
    uploadErrorCallBack
  }) {
    this.taskList = taskList;
    this.setTs = [];
    this.taskRunning = false;
    this.uploadSuccessCallback = uploadSuccessCallback;
    this.uploadTaskOverCallback = uploadTaskOverCallback;
    this.uploadErrorCallBack = uploadErrorCallBack;

    this.startUploadTask();
  }

  addSetTime(action, time = 1 * 1000) {
    this.setTs.push(setTimeout(action, time));
  }

  clearSetTs() {
    if (!this.setTs.length) return;
    this.setTs.forEach(t => clearTimeout(t));
    this.setTs = [];
  }

  addUploadTask(data) {
    this.taskList.push(data);
  }

  getCurTask() {
    return this.taskList.shift();
  }

  startUploadTask() {
    this.taskRunning = true;

    this.addSetTime(() => {
      this.runUploadTask();
    }, 10);
  }

  async runUploadTask() {
    this.clearSetTs();

    if (!this.taskList.length || !this.taskRunning) {
      this.overUploadTask();
      return;
    }
    const curTask = this.getCurTask();

    let uploadResult = true;
    await toUploadImg(curTask).catch(() => {
      if (messageInst) {
        messageInst.close();
        messageInst = null;
      }
      messageInst = Message.error({
        message: "上传异常",
        offset: 1
      });
      uploadResult = false;
    });
    if (uploadResult) {
      if (messageInst) {
        messageInst.close();
        messageInst = null;
      }
      this.uploadSuccessCallback(curTask);
    } else {
      this.uploadErrorCallBack(curTask);
    }

    this.addSetTime(() => {
      this.runUploadTask();
    }, 10);
  }

  overUploadTask() {
    this.taskRunning = false;
    this.clearSetTs();
    this.uploadTaskOverCallback && this.uploadTaskOverCallback();
  }
  stopUploadTask() {
    this.taskRunning = false;
    this.taskList = [];
  }
}

export default UploadTask;

export { toUploadImg };
