import axios from 'axios'
import XLSX from 'xlsx'
import store from '@/store'
import { startLoading, endLoading } from './loading'
import { ElMessage } from 'element-plus'

const apiUrl = import.meta.env.VITE_BASE_URL

export function writeExcelFile(workSheet, fileName) {
  const workBook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workBook, workSheet, 'sheet1')
  XLSX.writeFile(workBook, fileName)
  store.commit('app/setLoading', false)
  endLoading()
}

export function createWorkSheet(data, fields, titles) {
  const workSheet = XLSX.utils.json_to_sheet(data, { header: fields })
  const range = XLSX.utils.decode_range(workSheet['!ref'])
  for (let c = range.s.c; c <= range.e.c; c++) {
    const header = XLSX.utils.encode_col(c) + '1'
    workSheet[header].v = titles[workSheet[header].v]
  }
  return workSheet
}

export function downloadExcel(data) {
  if (data.jdt) {
    store.commit('app/setJdt', { title: '正在导出 Excel', isOpen: true, closeButton: false })
  } else {
    startLoading()
  }
  axios({
    method: data.method || 'post',
    url: apiUrl + data.url,
    data: data.param,
    responseType: 'blob',
    headers: {
      token: store.state.user.token,
    },
  })
    .then((res) => {
      const link = document.createElement('a')
      let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
      link.style.display = 'none'
      link.href = URL.createObjectURL(blob)
      link.download = data.fileName //下载的文件名
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      endLoading()
      store.commit('app/closeJdt')
    })
    .catch((error) => {
      ElMessage.error('网络连接错误', '错误')
      console.error(error)
      endLoading()
      store.commit('app/closeJdt')
    })
}
