import { ref } from "vue"
import { addCourseWareTask } from "@/worker/useCoursewaresWorker"
import { downloadFile } from "@/libs/tools"
import { getJsonToBlob } from "@/libs/jsonTool"

export default () => {
  const exporting = ref(false)
  const exportProgress = ref(0)

  // 导出PPTX文件
  const exportPPTX = () => {
    const { blob, title } = getJsonToBlob()
    const url = URL.createObjectURL(blob)
    exportProgress.value = 0
    exporting.value = true
    addCourseWareTask(
      {
        type: "downloadCourseware",
        extra: {
          id: "",
          type: "pptx",
          outputName: `${title}.pptx`,
          name: title,
          jsonUrl: url
        }
      },
      e => {
        console.log(e, "导出")
        /* 导出有个 bug 会先出现100，再出现50, 所以排除 doing 的100 */
        if (!(e.status === "doing" && parseInt(e.progress) === 100)) {
          exportProgress.value = parseInt(e.progress)
        }
        if (e.progress === 100) {
          if (e.status === "done") {
            exporting.value = false
            const { extra = {} } = e
            const { name, buffer } = extra
            downloadFile(new Blob([buffer]), name)
          } else if (e.status !== "doing") {
            exporting.value = false
          }
        }
      }
    ).catch(err => {
      exporting.value = false
      console.log(err)
    })
  }

  return {
    exportPPTX,
    exporting,
    exportProgress
  }
}
