import axios from 'axios'
import i18n from '../i18n'

const { t } = i18n.global

/**
 * 导出表格
 * @param {Object} pigeon - pigeon实例(弹窗实例)
 * @param {String} url - 接口地址
 * @param {Object} params - 请求参数
 * @param {String} name - 文件名
 */
export function exportExcel(pigeon, url, params, name = 'Download') {
  axios
    .post(url, { ...params }, { responseType: 'blob' })
    .then((res) => {
      try {
        if (res.status == 200) {
          if ('msSaveOrOpenBlob' in navigator) {
            window.navigator.msSaveOrOpenBlob(res.data, name)
          } else {
            let url = window.URL.createObjectURL(res.data)
            let a = document.createElement('a')
            document.body.appendChild(a)
            a.href = url
            a.download = name + '_' + formatDate() + '.xlsx'
            a.click()
            window.URL.revokeObjectURL(url)
          }
        } else {
          pigeon.MessageError(t('Msg.Download'))
        }
      } catch (error) {
        pigeon.MessageError(t('Msg.Download'))
      }
    })
    .catch(() => {
      pigeon.MessageError(t('Msg.SystemError'))
    })
}
function formatDate(date = new Date(), format = 'yyyyMMddHHmmss') {
  const pad = (num) => String(num).padStart(2, '0')

  const map = {
    yyyy: date.getFullYear(),
    MM: pad(date.getMonth() + 1),
    dd: pad(date.getDate()),
    HH: pad(date.getHours()),
    mm: pad(date.getMinutes()),
    ss: pad(date.getSeconds()),
  }

  return format.replace(/yyyy|MM|dd|HH|mm|ss/g, (key) => map[key])
}
