import { ref } from "vue"
import { storeToRefs } from "pinia"
import { saveAs } from "file-saver"
import { toPng, toJpeg } from "html-to-image"
import { useSlidesStore } from "@/store"
import message from "@/utils/message"
import { addCourseWareTask } from "@/worker/useCoursewaresWorker"
import { downloadFile } from "@/libs/tools"

interface ExportImageConfig {
  quality: number
  width: number
  fontEmbedCSS?: string
}

export default () => {
  const slidesStore = useSlidesStore()
  const { slides, theme, viewportRatio, title, viewportSize } = storeToRefs(slidesStore)

  const exporting = ref(false)

  // 导出图片
  const exportImage = (domRef: HTMLElement, format: string, quality: number, ignoreWebfont = true) => {
    exporting.value = true
    const toImage = format === "png" ? toPng : toJpeg

    const foreignObjectSpans = domRef.querySelectorAll("foreignObject [xmlns]")
    foreignObjectSpans.forEach(spanRef => spanRef.removeAttribute("xmlns"))

    setTimeout(() => {
      const config: ExportImageConfig = {
        quality,
        width: 1600
      }

      if (ignoreWebfont) config.fontEmbedCSS = ""

      toImage(domRef, config)
        .then(dataUrl => {
          exporting.value = false
          saveAs(dataUrl, `${title.value}.${format}`)
        })
        .catch(() => {
          exporting.value = false
          message.error("导出图片失败")
        })
    }, 200)
  }

  // 导出JSON文件
  const exportJSON = () => {
    const json = {
      width: viewportSize.value,
      height: viewportSize.value * viewportRatio.value,
      slides: slides.value,
      theme: theme.value
    }
    const blob = new Blob([JSON.stringify(json)])
    saveAs(blob, `${title.value}.json`)
  }

  // 导出PPTX文件
  const exportPPTX = () => {
    const json = {
      width: viewportSize.value,
      height: viewportSize.value * viewportRatio.value,
      slides: slides.value,
      theme: theme.value
    }
    const blob = new Blob([JSON.stringify(json)])
    const url = URL.createObjectURL(blob)
    exporting.value = true
    addCourseWareTask(
      {
        type: "downloadCourseware",
        extra: {
          id: "",
          type: "pptx",
          outputName: `${title.value}.pptx`,
          name: title.value,
          jsonUrl: url
        }
      },
      e => {
        console.log(e, "导出")
        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 {
    exporting,
    exportImage,
    exportJSON,
    exportPPTX
  }
}
