import { ref, onMounted } from "vue"

import { getHttpJson, jsonToPpt } from "@/libs/jsonTool"
import { initWorker, addCourseWareTask, getRunJobIds } from "@/worker/useCoursewaresWorker"
import { ElMessage } from "element-plus"
import useHistorySnapshot from "@/hooks/useHistorySnapshot"

export default () => {
  const { addHistorySnapshot } = useHistorySnapshot()
  const importing = ref(false)
  const importProgress = ref(0)
  onMounted(() => {
    initWorker()
  })
  // 导入PPTX文件
  const importPPTXFile = (files: FileList) => {
    // getHttpJson("./mjkJson/9.json").then(res => {
    //   if (res.code === 200) {
    //     jsonToPpt(res.data)
    //   }
    // })
    // return
    const file = files[0]
    if (!file) return
    importing.value = true
    importProgress.value = 0
    const suffix = `.${file.name.split(".")?.reverse()[0]}`
    addCourseWareTask(
      {
        type: "uploadCourseware",
        extra: {
          outputName: file.name.trim(),
          name: file.name.replace(suffix, "").trim(),
          type: file.type,
          suffix,
          path: file.webkitRelativePath,
          paths: file.webkitRelativePath.split("/"),
          files: file
        }
      },
      (e: any) => {
        console.log(e, "导入")
        importProgress.value = parseInt(e.progress)
        if (e.progress === 100) {
          if (e.status === "done") {
            getHttpJson(e.extra.url).then(res => {
              if (res.code === 200) {
                jsonToPpt(res.data)
                addHistorySnapshot()
                importing.value = false
              } else {
                importing.value = false
                ElMessage({
                  showClose: true,
                  message: "导入失败!",
                  type: "error"
                })
              }
            })
          } else if (e.status !== "doing") {
            importing.value = false
            ElMessage({
              showClose: true,
              message: "导入失败!",
              type: "error"
            })
          }
        }
      }
    ).catch(err => {
      importing.value = false
      ElMessage({
        showClose: true,
        message: "导入失败!",
        type: "error"
      })
      console.log(err)
    })
  }

  return {
    importPPTXFile,
    importing,
    importProgress
  }
}
