<template>
  <div class="pptToJson">
    <div class="file-input" @click="handleClick()">
      <ElButton type="primary">点击导入</ElButton>
      <input webkitdirectory directory class="input" type="file" name="upload" ref="inputRef" @change="$event => handleChange($event)" />
    </div>
    <FullscreenSpin :loading="fullscreenSpinData.loading" :progress="fullscreenSpinData.progress" :tip="fullscreenSpinData.tip" />
  </div>
</template>

<script setup lang="ts">
import { ElButton } from "element-plus"
import { computed, ref, onMounted } from "vue"
import { initWorker, addCourseWareTask } from "@/worker/useCoursewaresWorker"
import { ElMessage } from "element-plus"
import FullscreenSpin from "@/components/FullscreenSpin.vue"

const inputRef = ref<HTMLInputElement>()
let filesData: FileList | null
let filesIndex = 0
let filesArr: any[] = [["地址"]]

const handleClick = () => {
  if (!inputRef.value) return
  filesData = null
  filesIndex = 0
  filesArr = [["地址"]]
  inputRef.value.value = ""
  inputRef.value.click()
}

function handleChange(e: Event) {
  filesData = (e.target as HTMLInputElement).files
  console.log(filesData, "filse")
  importPPTXFile()
}

onMounted(() => {
  initWorker("default")
})

const importing = ref(false)
const importProgress = ref(0)

// 导入PPTX文件
function importPPTXFile() {
  if (!filesData?.length) {
    ElMessage({
      showClose: true,
      message: "没有文件！",
      type: "error",
      duration: 0
    })
    return
  }
  const file = filesData[filesIndex]
  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
      }
    },
    async (e: any) => {
      importProgress.value = parseInt(e.progress)
      if (e.progress === 100) {
        if (e.status === "done") {
          console.log(e.extra.url)
          // const response = await fetch(e.extra.url)
          // const data = await response.json()
          // const jsonStr = JSON.stringify(data)
          // const blob = new Blob([jsonStr], { type: "application/json" })
          // const blobUrl = URL.createObjectURL(blob)
          // const a = document.createElement("a")
          // a.href = blobUrl
          // a.download = getFileNameWithoutExtension(file.name.trim()) + ".json"
          // document.body.appendChild(a)
          // a.click()
          // document.body.removeChild(a)
          // URL.revokeObjectURL(blobUrl)
          filesArr.push([decodeURI(e.extra.url)])
          if (filesData!.length > filesIndex + 1) {
            filesIndex++
            importPPTXFile()
          } else {
            exportArrayToExcel(filesArr)
            ElMessage({
              showClose: true,
              message: `${filesIndex + 1}个文件，下载成功！`,
              type: "success",
              duration: 0
            })
            importing.value = false
          }
        } else if (e.status !== "doing") {
          importing.value = false
          ElMessage({
            showClose: true,
            message: `第${filesIndex + 1}个，${file.name.trim()}，下载失败!`,
            type: "error",
            duration: 0
          })
        }
      }
    }
  ).catch(err => {
    importing.value = false
    ElMessage({
      showClose: true,
      message: `第${filesIndex + 1}个，${file.name.trim()}，下载失败!`,
      type: "error",
      duration: 0
    })
    console.log(err)
  })
}
const fullscreenSpinData = computed(() => {
  return {
    loading: importing.value,
    progress: importProgress.value,
    tip: `第${filesIndex + 1}(${filesData?.length && filesData.length})个，${filesData?.length && filesData[filesIndex]?.name?.trim()}，正在下载，请稍等…`
  }
})
function getFileNameWithoutExtension(filename: string) {
  const lastDotIndex = filename.lastIndexOf(".")
  if (lastDotIndex === -1) {
    return filename
  }
  return filename.substring(0, lastDotIndex)
}

async function exportArrayToExcel(dataArray: any[]) {
  const XLSX = await import("xlsx")
  const wb = XLSX.utils.book_new()
  const ws = XLSX.utils.aoa_to_sheet(dataArray)
  XLSX.utils.book_append_sheet(wb, ws, "json数据")
  XLSX.writeFile(wb, "json数据.xlsx")
}
</script>

<style lang="scss" scoped>
.pptToJson {
  padding: 50px 0 0 100px;
  .input {
    display: none;
  }
}
</style>
