<template>
  <el-upload ref="uploadRef" :show-file-list="false" :limit="1" :on-change="onFileChange" :auto-upload="false"
    accept=".xlsx" style="display: inline-block">
    <el-button type="primary"><el-icon>
        <EditPen />
      </el-icon>导入（.xlsx）</el-button>
  </el-upload>

  <div class="edit-excel-pop" v-if="visible">
    <div class="edit-excel-hd">
      <el-button type="primary" @click="onExport"><el-icon>
          <download />
        </el-icon>导出（.xlsx）</el-button>
      <el-button @click="onClose" class="fr" style="margin-top: 6px"><el-icon>
          <Close />
        </el-icon>关闭</el-button>
    </div>
    <div class="edit-excel-bd" id="luckysheet" />
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue"
import LuckyExcel from "luckyexcel"
import { exportExcel } from "./exportExcel"
import { f } from "html2pdf.js"
// const props = defineProps({
// })
const visible = ref(false)
const uploadRef = ref(null)
const title = ref("")
const onFileChange = (file, fileList) => {
  const selectedFile = file.raw
  if (!(selectedFile instanceof File)) {
    console.error("传入了非文件对象")
    return
  }

  title.value = selectedFile.name.replace(/\.[^/.]+$/, "")
  let reader = new FileReader()

  reader.onload = async e => {
    let fileData = e.target.result
    try {
      visible.value = true
      LuckyExcel.transformExcelToLucky(fileData, async (exportJson, luckysheetfile) => {
        creatExcel(JSON.stringify(exportJson.sheets))
      })
    } catch (e) {
      console.error(e)
    }
  }

  reader.onerror = function () {
    console.error("File could not be read! Code " + reader.error.code)
  }

  reader.readAsArrayBuffer(selectedFile)
}
const onClose = () => {
  visible.value = false
  uploadRef.value.clearFiles()
}
const creatExcel = content => {
  const options = {
    container: "luckysheet",
    title: title.value,
    lang: "zh",
    hook: {
      updated: e => {
        $("#luckysheet_info_detail_save").text("已修改")
        let content = luckysheet.getAllSheets()
        for (let i in content) content[i].data = undefined
      }
    }
  }
  options.data = JSON.parse(content)

  window.luckysheet.destroy()
  window.luckysheet.create(options)
}
const onExport = () => {
  let title = document.getElementById("luckysheet_info_detail_input").value
  exportExcel(window.luckysheet.getAllSheets(), title)
}

const onDownload = () => { }
</script>

<style lang="scss" scoped></style>
