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

  <el-button class="download-file" @click.stop="downloadFile" size="large" circle type="primary">
    <el-icon><Download /></el-icon>
  </el-button>
</template>

<script lang="ts" setup>
import { Download } from '@element-plus/icons-vue'
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 filePath = ref('')
const props = defineProps(['fileId'])
const luckysheet = (window as any).luckysheet
const loading = ref(false)
const route = useRoute()

/**生成excel */
const generateExcel = (path: string) => {
  // 保存浏览文件的地址
  filePath.value = path
  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 downloadFile = () => {
  window.open('/api/sys/static/' + filePath.value, '_blank')
}

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

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

onMounted(() => {
  getFilePath()
})
onUnmounted(() => {
  isFunction((window as any)?.luckysheet?.destroy) && luckysheet.destroy()
})
</script>
<style lang="scss" scoped>
#preview-excel {
  width: 100%;
  height: 100%;
}
.download-file {
  position: fixed;
  bottom: 30px;
  right: 20px;
  z-index: 3000;
}
</style>
