import { defineStore } from "pinia"
import { store } from "./index"
import { getTeacherChapterKnowledgeMaterial, putTeacherChapterKnowledgeMaterial, putChapterKnowledgeMaterialUpdate } from "@/api/pptOperate"
import { httpAjaxErrMsg } from "@/plugins/httpAjax"
import { useRoute } from "vue-router"
import LoadingBar from "@/plugins/loadingBar"
import { getHttpJson, jsonToPpt, getJsonToBlob } from "@/libs/jsonTool"
import fileUpload from "@/utils/oss-file-upload"
import { ElMessage } from "element-plus"
import { toBlob } from "html-to-image"
import { useSlidesStore } from "@/store"
import queryParams from "@/queryParams"
import router from "@/router"

type pptWork = { id: string; coverImg: string; jsonUrl: string; isSave: boolean }

const useStore = defineStore("pptWork", {
  state: (): pptWork => {
    const route = useRoute()
    return {
      id: route.query.id as string,
      coverImg: "",
      jsonUrl: "",
      isSave: false // 当前是否保存，用来关闭页面时候判断 提不提示
    }
  },
  actions: {
    /** 初始化 */
    async initPPTData() {
      if (this.id) {
        LoadingBar.loading(true, "资源加载中,请稍等...")
        const res = await httpAjaxErrMsg(getTeacherChapterKnowledgeMaterial, this.id, queryParams.fromType)
        if (res.code === 200) {
          const { dataJson, chapterLessonCoursewareName } = res.data || {}
          const { coverImg, jsonUrl } = JSON.parse(dataJson)
          this.coverImg = coverImg || ""
          const slidesStore = useSlidesStore()
          slidesStore.setTitle(chapterLessonCoursewareName)
          if (jsonUrl) {
            const jsonRes = await getHttpJson(jsonUrl)
            if (jsonRes.code === 200) {
              jsonToPpt(jsonRes.data)
            }
          }
        } else {
          // 获取不到ppt数据的时候 跳转到错误页面
          router.replace("/err")
        }
        LoadingBar.loading(false)
      }
    },
    async updatePPT() {
      LoadingBar.loading(true, "课件保存中,请稍等...")
      await this.updateCoverImg()
      const { blob } = getJsonToBlob()
      fileUpload(`${this.id}ppt`, blob, `${this.id}/`, false, { isLoading: false })
        .then(url => {
          const _time = Date.now()
          httpAjaxErrMsg(queryParams.fromType === "PLATFORM" ? putChapterKnowledgeMaterialUpdate : putTeacherChapterKnowledgeMaterial, {
            id: this.id,
            dataJson: JSON.stringify({
              coverImg: this.coverImg + `?v=_${_time}`, // 加上时间戳，防止资源更新之后的缓存
              jsonUrl: url + `?v=_${_time}`
            })
          }).then(res => {
            if (res.code === 200) {
              this.isSave = true
              ElMessage({
                showClose: true,
                message: "保存成功!",
                type: "success"
              })
            }
            LoadingBar.loading(false)
          })
        })
        .catch(() => {
          LoadingBar.loading(false)
          ElMessage({
            showClose: true,
            message: "保存失败!",
            type: "error"
          })
        })
    },
    async updateCoverImg() {
      try {
        const coverImgDom = document.querySelector("#thumbnailSlide_0") as HTMLElement
        if (coverImgDom) {
          const dataBlob = await toBlob(coverImgDom)
          if (dataBlob) {
            const url = await fileUpload(`${this.id}coverImg`, dataBlob, `${this.id}/`, false, { isLoading: false })
            url && (this.coverImg = url)
          }
        }
      } catch (err) {
        console.log(err, "上传coverImg错误")
      }
    }
  }
})
export default () => {
  return useStore(store)
}
