import myWorker from "./index"
import axios from "axios"
import { getToken } from "@/libs/auth"
import { URL_API } from "@/config/index"
import usePptWork from "@/store/pptWork"

let worker: any = null
let useOnCoursewaresMessage = (e: any) => {}

/**
 * 初始化worker
 */
export const initWorker = (filePath?: string) => {
  // eslint-disable-next-line no-async-promise-executor
  return new Promise(async (resolve, reject) => {
    if (!worker) {
      const usePptWorkHook = usePptWork()
      const str1 = await axios.get("./pptworker/cos-js-sdk-v5.min.js")
      const str2 = await axios.get("./pptworker/upload.js")
      const str3 = await axios.get("./pptworker/pptJson.js")
      /*  这里根据id 加上一个文件夹 */
      worker = new myWorker([str1.data, `\r\nconst filePath = "${filePath || usePptWorkHook.id}/"\r\n`, str2.data, str3.data])
      worker.ready
        .then(() => worker.createTaskController())
        .then(() => {
          worker.onmessage = onCoursewaresMessage
        })
        .then(() => {
          worker.initOssResource(URL_API, getToken())
        })
        .then(resolve(worker))
        .catch(reject)
      return
    }
    resolve(worker)
  })
}
/**
 * 销毁worker
 */
export const destroyWorker = () => {
  return new Promise((resolve, reject) => {
    if (worker) {
      worker
        .destoryTaskController()
        .then(() => worker.terminate())
        .then(() => {
          worker = null
          resolve("")
        })
        .catch(reject)
    } else {
      resolve("")
    }
  })
}
/**
 * 添加任务
 */
type downloadCoursewareType = {
  type: "downloadCourseware"
  extra: {
    id: string
    type: string
    outputName: string
    name: string
    jsonUrl: string
  }
}
/* {
  type: "downloadCourseware",
  qqq:"",  //可以自定义属性 结果返回的时候 同时返回
  extra: {
    id: "",
    type: "pptx",
    outputName: `test.pptx`,
    name: "test",
    jsonUrl: "https://oss.dayaedu.com/pptList/example.json"
  }
} */
type uploadCoursewareType = {
  type: "uploadCourseware"
  extra: {
    outputName: string
    name: string
    type: string
    suffix: string
    path: string
    paths: string[]
    files: File
  }
}
/* {
  type: "uploadCourseware",
  qqq:"",  //可以自定义属性 结果返回的时候 同时返回
  extra: {
    files: File
    name: "test",
    outputName: "test.pptx",
    path: "",
    paths: [""],
    suffix: ".pptx",
    type: "application/vnd.openxmlformats-officedocument.presentationml.presentation"
  }
} */
export const addCourseWareTask = (task: downloadCoursewareType | uploadCoursewareType | null, onCoursewaresMessage: (e: any) => void) => {
  return new Promise((resolve, reject) => {
    if (worker) {
      useOnCoursewaresMessage = onCoursewaresMessage
      worker
        .addCourseWareTask(task)
        .then((result: any) => {
          task = null
          resolve(result)
        })
        .catch(reject)
    } else {
      reject("worker没有初始化")
    }
  })
}

/**
 * 获取运行中的任务id
 */
/* getRunJobIds().then(res => {
  // res.length 大于 1 时候 说明有任务运行
}) */
export const getRunJobIds = () => {
  return new Promise((resolve, reject) => {
    if (worker) {
      worker.getRunJobIds().then(resolve).catch(reject)
    } else {
      reject("worker没有初始化")
    }
  })
}

/**
 * 任务进度监控
 */
const onCoursewaresMessage = (e: any) => {
  const { type, result = {} } = e.data
  if (type === "progress") {
    useOnCoursewaresMessage(result)
  }
}
