/**
 * 根据src地址获取文件类型
*/
export function getExtByFileSrc(fileSrc) {
  if (!fileSrc) {
    return
  }
  return fileSrc.substr(fileSrc.lastIndexOf('.') + 1).toLowerCase()
}

/**
 * 根据src地址获取文件名称
*/
export function getExtByFileName(fileSrc) {
  if (!fileSrc) {
    return
  }
  let fileName = fileSrc.substr(fileSrc.lastIndexOf('/') + 1)
  try {
    fileName = window.decodeURIComponent(fileName)
  } catch (e) {
    console.log(e)
  }
  return fileName
}

/**
 * 格式化文件尺寸为友好字符串
*/
export function formatFileSize(fileSize) {
  let fileSizeBack = ''
  if (fileSize < 1024) {
    fileSizeBack = fileSize + 'B'
    return fileSizeBack
  } else if (fileSize < (1024 * 1024)) {
    let temp = fileSize / 1024
    temp = temp.toFixed(0)
    fileSizeBack = temp + 'K'
    return fileSizeBack
  } else if (fileSize < (1024 * 1024 * 1024)) {
    let temp = fileSize / (1024 * 1024)
    temp = temp.toFixed(0)
    fileSizeBack = temp + 'M'
    return fileSizeBack
  } else {
    let temp = fileSize / (1024 * 1024 * 1024)
    temp = temp.toFixed(0)
    fileSizeBack = temp + 'G'
    return fileSizeBack
  }
}

/**
 * 下载文件
*/
export function downloadFile(fileUrl) {
  if ('download' in document.createElement('a')) { // 非IE下载
    const elink = document.createElement('a')
    elink.download = getExtByFileName(fileUrl)
    elink.style.display = 'none'
    elink.href = fileUrl
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href) // 释放URL 对象
    document.body.removeChild(elink)
  } else { // IE10+下载
    window.location.href = fileUrl
  }
}
