/*
    自定义下载
*/

import { Message } from 'element-ui'

// /**
//  * 根据文件流下载文件
//  * @param data
//  * @param filename
//  */
// function downloadByStream(data, filename) {
//     let blob = new Blob([data], { type: 'application/vnd.ms-excel' })//接收的是blob，若接收的是文件流，需要转化一下
//     downloadByBlob(blob, filename)
// }

/**
 * 根据文件流下载文件
 * @param data
 * @param filename
 * @param isVaild
 */
function downloadByStream(data, filename, isVaild, thisCom) {
  if (!data) {
    return
  }
  filename = filename ? filename : '文件'
  thisCom = thisCom ? thisCom : this ? this : {}
  let downloadFun = () => {
    //下载方法
    // let blob = new Blob([data], {type: 'application/vnd.ms-excel'})接收的是blob，若接收的是文件流，需要转化一下
    if (typeof window.chrome !== 'undefined') {
      if (typeof data !== Blob) {
        var blobfile = new Blob([data], { type: 'application/vnd.ms-excel' })
      } else {
        blobfile = data
      }
      const url = window.URL.createObjectURL(blobfile)
      const link = document.createElement('a')
      link.download = filename
      link.href = url
      // Chrome version
      link.click()
    } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
      // IE version
      var blob = new Blob([data], { type: 'application/force-download' })
      window.navigator.msSaveBlob(blob, filename)
    } else {
      // Firefox version
      var file = new File([data], filename, {
        type: 'application/force-download',
      })
      window.open(URL.createObjectURL(file))
    }
  }

  if (isVaild) {
    //验证Blob对象对象
    // console.log(data)
    //IE浏览器会在类型后面加"charset=UTF-8"，例如"application/json;charset=UTF-8"
    let isNeedReader =
      data instanceof Blob && data.type.indexOf('application/json') >= 0 //是否需要解析//"application/vnd.ms-excel"
    if (isNeedReader) {
      //Blob对象，进行解析
      var reader = new FileReader() //文件读取
      reader.readAsText(data, 'utf-8') //读取成文本
      reader.onload = function() {
        //读取完毕后输出结果
        // console.log(this.result)
        var result = this.result
        if (result) {
          // && result.indexOf("code") >= 0 && result.indexOf("data") >= 0 && result.indexOf("message") >= 0) {
          let resultJson = JSON.parse(result)
          // console.log(resultJson)
          if (resultJson.code == 200) {
            downloadFun()
          } else {
            let messageFun = thisCom.$message ? thisCom.$message : Message
            messageFun({
              message: resultJson.message,
              type: 'error',
            })
          }
        } else {
          downloadFun()
        }
      }
    } else {
      downloadFun()
    }

    return
  }

  downloadFun()
}

export default {
  downloadByStream,
}
