import axios from '@/common/services/axios-instance'
import ProgressBar from '@/common/services/progress-bar'
function download(url, fname, flag = true) {
  let i = 0.4
  if (flag) ProgressBar.start()
  let p
  const onDownloadProgress = (progress) => {
    if (flag) {
      if (progress.total) {
        ProgressBar.set(Math.round(progress.loaded / progress.total))
      } else {
        i = i + (1 - i) * 0.3
        ProgressBar.set(i)
      }
    }
  }
  if (typeof url === 'string') {
    p = axios({
      url,
      responseType: 'blob',
      onDownloadProgress,
    })
  } else {
    Object.assign(url, {
      responseType: 'blob',
      onDownloadProgress,
    })
    p = axios(url)
  }
  return p.then((res) => {
    if (flag) ProgressBar.done()
    if ('msSaveOrOpenBlob' in window.navigator) {
      // 兼容IE
      window.navigator.msSaveOrOpenBlob(res.data, fname)
      return
    }
    const blobUrl = URL.createObjectURL(res.data)
    const a = document.createElement('a')
    a.href = blobUrl
    a.download = fname
    // 不用a.click()因为52的firefox不允许
    var evt = document.createEvent('MouseEvents')
    evt.initEvent('click', true, true)
    a.dispatchEvent(evt)
    URL.revokeObjectURL(blobUrl)
  })
}
export default download
