import { ElLoading, ElMessage } from 'element-plus'
import { saveAs } from 'file-saver'
import CODE_MESSAGE from '/@/utils/codeMessage'
import { blobValidate, tansParams } from '/@/utils/index'
import request from '/@/utils/request'

// 通用下载方法
export function download(url: string, params: any, filename: any, config: any) {
  let downloadLoadingInstance = ElLoading.service({ text: '正在下载数据，请稍候', background: 'rgba(0, 0, 0, 0.7)' })
  return request
    .post(url, params, {
      transformRequest: [
        (params) => {
          return tansParams(params)
        },
      ],
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      responseType: 'blob',
      ...config,
    })
    .then(async (data: any) => {
      const isBlob = blobValidate(data)
      if (isBlob) {
        const blob = new Blob([data as any])
        saveAs(blob, filename)
      } else {
        const resText = await data.text()
        const rspObj: { code: keyof typeof CODE_MESSAGE; msg: string } = JSON.parse(resText)
        const errMsg = CODE_MESSAGE[rspObj.code] || rspObj.msg || CODE_MESSAGE['default']
        ElMessage.error(errMsg)
      }
      downloadLoadingInstance.close()
    })
    .catch((error) => {
      console.error(error)
      ElMessage.error('下载文件出现错误，请联系管理员！')
      downloadLoadingInstance.close()
    })
}
