<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 { getOrderFileById as getVarOrderFileById } from '@/api/var'
import {
  cellRightClickConfig,
  sheetRightClickConfig,
  showsheetbarConfig,
  showstatisticBarConfig
} from '@/constants/excelConfig'
import { useRoute } from 'vue-router'
import { isFunction } from '@/utils/is'
import axios from 'axios'
import { ElMessage } from 'element-plus'

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

/**生成excel */
const generateExcel = async (path: string) => {
  // 保存浏览文件的地址
  filePath.value = path
  try {
    // 验证文件是否存在
    await axios.get('/api/sys/static/' + 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
        })
      }
    )
  } catch (e) {
    // 验证文件是否存在，不存在报错
    if (e?.response) {
      ElMessage.error(e.response.data.message)
    }
  }
}

const downloadFile = () => {
  window.open('/api/sys/static/' + filePath.value, '_blank')
}

/**获取文件路径 */
const getFilePath = async () => {
  try {
    loading.value = true
    const fileId = props.fileId || route.query.fileId
    const type = props.type || route.query.type
    if (fileId) {
      const { data } =
        type === 'var' ? await getVarOrderFileById(fileId) : await getOrderFileById(fileId)
      if (data.code == 200) {
        generateExcel(data.result.mergeFilePath)
      }
    } else {
      const path = (route.query.filePath || '') as string
      !!path && generateExcel(path)
    }
  }catch (e) {
    // 验证文件是否存在，不存在报错
    if (e?.response) {
      ElMessage.error(e.response.data.message)
    }
  }
  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>
