// 统一暴露工具,供其他地方调用

// 数组转对象
export function arrToObj(arr) {
  // 参数必须是一个数组
  if (!Array.isArray(arr)) {
    throw new Error("type err: arr 必须是一个数组");
  }
  // 存放返回结果
  const obj = {};
  arr.map((item) => {
    obj[Object.keys(item)[0]] = item[Object.keys(item)[0]];
  });
  return obj;
}

/*
*  文件流转换为url
*  @params file 文件流
*  @return url
*/
export function getObjectURL(file) {
  console.log(file)
  let url = null;
  if (window.createObjectURL != undefined) { // basic
    url = window.createObjectURL(file);
  } else if (window.webkitURL != undefined) { // webkit or chrome
    url = window.webkitURL.createObjectURL(file);
  } else if (window.URL != undefined) { // mozilla(firefox)
    url = window.URL.createObjectURL(file);
  }
  return url;
}

/**
* @description 文件下载(兼容IE)
* @param {Object} response options 接口响应的数据 包括文件流及保文信息
* @param {String} file_name 文件名称
* @returns {undefined} undefined
*/
export function downloadFile(response, file_name = "ExportFile") {
  const fileType = response.headers["content-type"] || "application/pdf";
  const disposition = response.headers["content-disposition"]
  if (disposition) {
    file_name = disposition.split("filename=")[1]
  }
  const blob = new Blob([response.data], { type: `${fileType};charset=utf-8` });

  const ie = navigator.userAgent.match(/MSIE\s([\d.]+)/),
    ie11 = navigator.userAgent.match(/Trident\/7.0/) && navigator.userAgent.match(/rv:11/),
    ieEDGE = navigator.userAgent.match(/Edge/g),
    ieVer = ie ? ie[1] : ie11 ? 11 : ieEDGE ? 12 : -1;

  if (ie && ieVer < 10) {
    this.message.error('No blobs on IE<10');
    return;
  }
  if (ieVer > -1) {
    window.navigator.msSaveBlob(blob, file_name);
    return {}
  } else {
    const url = window.URL.createObjectURL(blob);
    return {
      url,
      file_name
    }
    // let link = document.createElement('a');
    // link.setAttribute('href', url);
    // link.setAttribute('download', file_name);
    // document.body.appendChild(link);
    // link.click();
    // document.body.removeChild(link);
  }
}

//导出excel
export function exportFile(res, file_name) {
  let blob = new Blob([res.data], {
    type:"application/vnd.ms-excel;charset=utf-8"
  });
  let url=window.URL.createObjectURL(blob);
  let aLink=document.createElement("a");
  aLink.style.display="none";
  aLink.href=url;
  aLink.setAttribute("download", file_name);
  document.body.appendChild(aLink);
  aLink.click();
  document.body.removeChild(aLink);
  window.URL.revokeObjectURL(url);
}

export const numValid = /^([1-9][0-9]*|0)([.][0-9]+)?$/