小工具方法使用

109 阅读2分钟
// 格式化日期
export function formatDate(val, format, dateDetails) {
  if (!val) { return '' }
  const reYY = /yy/g
  const reMM = /mm/g
  const reDD = /dd/g
  const reHH = /hh/g
  const reMin = /min/g
  const reSS = /ss/g

  function addZero(val) {
    return val < 10 ? '0' + val : val
  }
  const value = val.toString().indexOf('-') != -1 ? val.toString().replace(/-/g, '/') : val
  const _date = value ? new Date(value) : new Date()

  const year = _date.getFullYear()
  const month = addZero(_date.getMonth() + 1)
  const date = addZero(_date.getDate())
  const hour = addZero(_date.getHours())
  const minutes = addZero(_date.getMinutes())
  const seconds = addZero(_date.getSeconds())

  if (dateDetails) {
    return {
      year: year,
      month: month,
      date: date,
      hour: hour,
      minutes: minutes,
      seconds: seconds
    }
  }

  format = format || 'yy-mm-dd hh:min:ss'
  const formatDate = format.replace(reYY, year)
    .replace(reMM, month)
    .replace(reDD, date)
    .replace(reHH, hour)
    .replace(reMin, minutes)
    .replace(reSS, seconds)

  return formatDate
}
formatDate(this.form.startTime, 'yy-mm-dd hh:min:ss')

// 千分位的表示法
export const formatWithToLocaleString = (number, minimumFractionDigits, maximumFractionDigits) => {
  minimumFractionDigits = minimumFractionDigits || 2
  maximumFractionDigits = (maximumFractionDigits || 2)
  maximumFractionDigits = Math.max(minimumFractionDigits, maximumFractionDigits)

  return Number(number).toLocaleString('en-us', {
    maximumFractionDigits: maximumFractionDigits || 2,
    minimumFractionDigits: minimumFractionDigits || 2
  })
}

// 前端导出excel.js
dataSource   数据
columns      表格的columns
export const exportSelectedData = (dataSource, columns, filename, sheetname) => {
  const workbook = new ExcelJS.Workbook()
  const sheet = workbook.addWorksheet(sheetname, {
    views: [{ state: 'frozen', ySplit: 1 }]
  })
  sheet.columns = columns.map(c => ({ header: c.title, key: c.dataIndex, width: c.width || 10 }))
  const data = []
  dataSource.forEach((d, i) => {
    data[i] = []
    columns.forEach(c => {
      const item = d[c.dataIndex]
      data[i].push(typeof c.render === 'function' ? c.render(item, d, i) : item)
    })
  })
  sheet.addRows(data)
  sheet.getRow(1).font = { bold: true }
  sheet.getRow(1).eachCell(function(cell) {
    cell.border = {
      right: { style: 'thin' }
    }
  })
  sheet.eachRow(function(row, rowNumber) {
    row.alignment = { wrapText: true }
    if (rowNumber > 1) {
      row.eachCell(function(cell) {
        cell.border = {
          right: { style: 'thin' },
          bottom: { style: 'thin' }
        }
      })
    }
  })
  workbook.xlsx.writeBuffer().then(data => {
    const blob = new Blob([data])
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blob, filename)
    } else {
      imatateDownloadByA(window.URL.createObjectURL(blob), filename)
    }
  })
}

export function imatateDownloadByA(href, filename) {
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    const arr = href.split(',')
    const mime = arr[0].match(/:(.*?);/)[1]
    const bstr = atob(arr[1])
    let n = bstr.length
    const u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    const blob = new Blob([u8arr], { type: mime })
    window.navigator.msSaveOrOpenBlob(blob, filename)
  } else {
    const a = document.createElement('a')
    a.download = filename
    a.style.display = 'none'
    a.href = href
    document.body.appendChild(a)
    a.click()
    a.remove()
    window.URL.revokeObjectURL(href)
  }
}

// 响应拦截
instance.interceptors.response.use((response) => {
  mask.forEach((element, index) => {
    if (response.config.url.indexOf(element) >= 0) {
      mask.splice(index, 1)
      if (document.getElementsByClassName('mask-loading')[0]) {
        document.querySelector('body').removeChild(document.getElementsByClassName('mask-loading')[0])
      }
    }
  })
  if (response.config.responseType === 'blob') {
    if (response.status !== 200) {
      const data = new Promise((resolve) => {
        const fileReader = new FileReader()
        fileReader.readAsText(response.data)
        fileReader.onload = function() {
          try {
            resolve(
              JSON.parse(fileReader.result)
            )
          } catch (e) {
            resolve({
              msg: i18nLang.i18n.t('PAGCOMMONEPSINFO_0772')
            })
          }
        }
      })
      return Promise.reject(data.msg)
    }
    const fileName = response.headers['content-disposition'].split(/filename=/i)[1]
    if (isIE()) {
      return navigator.msSaveBlob(new Blob([response.data], { type: 'text/csv; charset = utf-8;' }), `${fileName}`)
    } else {
      return downloadHandler(response.data, fileName)
    }
  }
  let { code, message } = response.data
  if(code===undefined) {// 兼容一个获取pc客户端下载链接的接口,来自驾驶舱
    code = response.data.responseCode
  }
  response.data.body = response.data.body === null ? {} : response.data.body
  switch (+code) {
    case -32:
    case -5:
    case 10006:
    case 20015:
      location.href = '#/403'
      return response.data //  登录超时
    case 10005:
    case -4:
    case 402:
      if (process.env.NODE_ENV === 'development') {
        location.replace(DEV_HOST() + '/hbp/login/#/index')
      } else {
        location.replace(DEV_HOST() + '/hbp/login/#/index?redirectUrl' + (encodeURIComponent('=' + encodeURIComponent(location.href))))
      }
      return
    case 0:
    case 200:
    case 10001:
      return response.data
    default:
      // 若统一处理需后端返回相对友好的错误信息提示(能直接面向客户)
      // Message.error(message || '未知服务器错误')
      return Promise.reject(response.data)
  }
}, (err) => {
  mask.forEach((element, index) => {
    if (err.config.url.indexOf(element) >= 0) {
      mask.splice(index, 1)
      if (document.getElementsByClassName('mask-loading')[0]) {
        document.querySelector('body').removeChild(document.getElementsByClassName('mask-loading')[0])
      }
    }
  })
  // 错误抛到业务代码
  console.info('请求错误:', err)
  // axios 发生 cancelToken 取消请求时 不再往下执行
  if (err.message === 'cancel') return

  // 培训班作业批改文件过大下载不了的提示处理
  if (err.response.config.fileSize === 'over' && (err.response.status === 404 || err.response.status === 504)){
    showModal(STATUS_TYPE.ERROR, {
      title: i18nLang.i18n.t('PAGCOMMONEPSINFO_0247'),
      content: i18nLang.i18n.t('文件体积过大,无法批量下载,请单独下载学员作业')
    })
    return
  }

  if (
    (!err.response && err.message && err.message !== 'cancel') ||
    (err.response && (
      err.response.status === 500 ||
      err.response.status === 503 ||
      err.response.status === 504 ||
      err.response.status === 404
    ))
  ) {
    showModal(STATUS_TYPE.ERROR, {
      title: i18nLang.i18n.t('PAGCOMMONEPSINFO_0247'),
      content: i18nLang.i18n.t('PAGCOMMONEPSINFO_0774')
    })
  } else if (err.response && err.response.status === 402) {
    if (!/^#\/login/.test(location.hash)) {
      showModal(STATUS_TYPE.INFO, {
        title: i18nLang.i18n.t('PAGCOMMONEPSINFO_0775'),
        content: i18nLang.i18n.t('PAGCOMMONEPSINFO_0776'),
        onOk: () => {
          location.hash = '#/login'
        }
      })
    }
  } else {
    Message.error(i18nLang.i18n.t('PAGCOMMONEPSINFO_0299'))
  }
})

// 文件流的下载
export function downloadHandler(result, fileName) {
  return new Promise(resolve => {
    let fileReader = new FileReader()
    fileReader.readAsDataURL(result)
    fileReader.onload = () => {
      let a = document.createElement('a')
      a.href = fileReader.result
      a.download = decodeURIComponent(fileName)
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      fileReader = a = null
      resolve(true)
    }
  })
}

// 倒计时时间转化
dateformat(micro_second, type) {
      // 总秒数
      const second = Math.floor(micro_second / 1000)
      // 天数
      const day = Math.floor(second / 3600 / 24)
      // 小时
      const hr = Math.floor(second / 3600 % 24)
      // 分钟
      const min = Math.floor(second / 60 % 60)
      // 秒
      const sec = Math.floor(second % 60)

      this.showTime = { min: min, sec: sec, type: type }
      return day + '天' + hr + '小时' + min + '分钟' + sec + '秒'
    }