import { ElNotification, ElMessage } from 'element-plus'
import { saveAs } from 'file-saver'
import { blobValidate } from '@/utils/common'
import errorCode from '@/utils/errorCode'
/**
 * @description 接收数据流生成 blob，创建链接，下载文件
 * @param {Function} api 导出表格的api方法 (必传)
 * @param {String} tempName 导出的文件名 (必传)
 * @param {Object} params 导出的参数 (默认{})
 * @param {Boolean} isNotify 是否有导出消息提示 (默认为 true)
 * @param {String} fileType 导出的文件格式 (默认为.xlsx)
 * */
export const useDownload = async (
  api: (param: any) => Promise<any>,
  tempName: string,
  params: any = {},
  isNotify: boolean = true,
  fileType: string = '.xlsx',
  fileName?: string
) => {
  if (isNotify) {
    ElNotification({
      title: '温馨提示',
      message: '如果数据庞大会导致下载缓慢哦，请您耐心等待！',
      type: 'info',
      duration: 3000
    })
  }
  const saveAsFn = (text: string | Blob, name: string | undefined, opts?: any) => {
    saveAs(text, name, opts)
  }
  const printErrMsg = async data => {
    const resText = await data.text()
    const rspObj = JSON.parse(resText)
    const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
    ElMessage.error(errMsg)
  }
  try {
    const data = await api(params)
    const isBlob = await blobValidate(data)
    if (isBlob) {
      const blob = fileType == 'zip' ? new Blob([data], { type: 'application/zip' }) : new Blob([data])
      const name = fileType == 'zip' ? fileName : `${tempName}_${new Date().getTime()}${fileType}`
      saveAsFn(blob, name, null)
      console.log('%s ====>>>导出成功', tempName)
    } else {
      printErrMsg(data)
    }
  } catch (error) {
    console.log(error)
    ElMessage.error('下载文件出现错误，请联系管理员！')
  }
}
