<template>
  <div id="preview-excel"></div>
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, ref, watch } from 'vue'
import LuckyExcel from 'luckyexcel'
import { getOrderFileById } from '@/api/order'
import {
  cellRightClickConfig,
  sheetRightClickConfig,
  showsheetbarConfig,
  showstatisticBarConfig
} from '@/constants/excelConfig'
import { useRoute } from 'vue-router';
import { isFunction } from '@/utils/is';

const props = defineProps(['fileId'])
const luckysheet = (window as any).luckysheet
const loading = ref(false)
const route = useRoute()

/**生成excel */
const generateExcel = (path: string) => {
  LuckyExcel.transformExcelToLuckyByUrl(
    '/api/sys/static/' + path,
    new Date().getTime() + '.xlsx',
    async (exportJson: any) => {
      luckysheet.create({
        container: 'preview-excel', //luckysheet is the container id
        showinfobar: false,
        showtoolbar: false,
        showsheetbar: false,
        showsheetbarConfig,
        cellRightClickConfig,
        sheetRightClickConfig,
        showstatisticBarConfig,
        data: exportJson.sheets,
        title: exportJson.info.name,
        userInfo: exportJson.info.name.creator
      })
    }
  )
}

/**获取文件路径 */
const getFilePath = async () => {
  try {
    loading.value = true
    const { data } = await getOrderFileById((props.fileId || route.query.fileId) as string)
    if (data.code == 200) {
      generateExcel(data.result.mergeFilePath)
    }
  } catch {}
  loading.value = false
}

watch(
  () => props.fileId,
  (val) => {
    if (val) {
      getFilePath()
    }
  }
)

onMounted(() => {
  // luckysheet.create({
  //   container: 'preview-excel'
  // })

  getFilePath()
})
onUnmounted(() => {
  isFunction((window as any)?.luckysheet?.destroy) && luckysheet.destroy()
})
</script>
<style lang="scss" scoped>
#preview-excel {
  width: 100%;
  height: 100%;
}
</style>
