import notification from 'ant-design-vue/es/notification'
import moment from 'moment'

// 导出excel
/*
  *url: 数据请求接口
  *params: 请求参数
  *fileName: 导出文件名称
  *callback: 回调函数
*/
export const hdExportExcel = function (url, params, fileName, callback) {
  url(params).then(res => {
    if (res.type == 'application/json') {
      var reader = new FileReader()
      reader.addEventListener('loadend', function () {
        const obj = JSON.parse(reader.result)
        if (obj.status != 200) {
          notification.error({
            message: '提示',
            description: obj.message
          })
        }
      })
      reader.readAsText(res)
    } else {
      downloadExcel(res, fileName)
    }
    callback()
  })
}
// 导出下载excel
export const downloadExcel = function (data, fileName) {
  if (!data) { return }
  const a = moment().format('YYYYMMDDHHmmss')
  const fname = fileName + a
  const blob = new Blob([data], { type: 'application/vnd.ms-excel' })
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, fname + '.xlsx')
  } else {
    const link = document.createElement('a')
    link.style.display = 'none'
    var href = URL.createObjectURL(blob)
    link.href = href
    link.setAttribute('download', fname + '.xlsx')
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(href) // 释放掉blob对象
  }
}
