/**
 * 文件工具类
 * @author ilex.h
 */
import _amosTool,{ UUID } from 'amos-tool';
import globalConfig from './global';

export const compleHeaders = () => {
  return {
    ...globalConfig.getRequestHeader()
  };
};

/**
 * 图片的绝对路径地址 转换成base64编码 如下代码：
 * @param {*} img
 */
const getBase64Image = img => {
  let canvas = document.createElement('canvas');
  canvas.width = img.width;
  canvas.height = img.height;
  let ctx = canvas.getContext('2d');
  ctx.drawImage(img, 0, 0, img.width, img.height);
  let ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase();
  let dataURL = canvas.toDataURL(`image/${ext}`);
  return {
    dataURL,
    type: `image/${ext}`
  };
};
/**
 * base64转文件
 * @param {*} base64
 * @param {*} filename
 */
const convertBase64UrlToFile = (base64, filename) => {
  let urlData = base64.dataURL;
  let type = base64.type;
  let mime = type.split('/')[1];
  let bytes = window.atob(urlData.split(',')[1]); // 去掉url的头，并转换为byte
  // 处理异常,将ascii码小于0的转换为大于0
  let ab = new ArrayBuffer(bytes.length);
  let ia = new Uint8Array(ab);
  for (let i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i);
  }
  return new File([ia], filename, { type: mime });
};
/**
 * 根据file对象获取base64
 * @param {*} file
 */
export const getBase64 = file => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
};
/**
 * 图片地址转换成File对象
 * @param {*} imgUrl
 * @param {*} filename
 * @param {*} callBack
 */
export const convertImgUrlToFile = (imgUrl, filename, callBack) => {
  let image = new Image();
  image.crossOrigin = '';
  image.src = imgUrl;
  image.onload = function() {
    let base64 = getBase64Image(image);
    let file = convertBase64UrlToFile(base64, filename);
    file.uid = UUID.uuidFast();
    file.url = imgUrl;
    callBack(file);
  };
};
/**
 * post请求下载文件
 * @param {*} url
 * @param {*} searchParam
 */
export const downLoadFilePost = (url,searchParam)=>{
  fetch(url, {
    method: 'post',
    headers: {
      'Accept': 'application/json, */*',
      'Content-Type': 'application/json; charset=utf-8',
      ...compleHeaders()
    },
    body: JSON.stringify(searchParam)
  }).then(e => {
    e.blob().then(blob => {
      const a = window.document.createElement('a');
      const downUrl = window.URL.createObjectURL(blob);
      let currDate = new Date();
      const filename = [currDate.getTime(), 'xls'];
      a.href = downUrl;
      a.download = `${decodeURI(filename[0])}.${filename[1]}`;
      a.click();
      window.URL.revokeObjectURL(downUrl);
    });
  }).catch(e => {
    _amosTool.Log.error(e.message);
  });
};

/**
 * get请求下载文件
 * @param {*} url
 * @param {*} fileName
 * @param {*} searchParam
 */
export const downLoadFileGET = (url,fileName,searchParam)=>{
  fetch(url, {
    method: 'get',
    headers: {
      'Accept': 'application/json, */*',
      'Content-Type': 'application/json; charset=utf-8',
      ...compleHeaders()
    },
    body: JSON.stringify(searchParam)
  }).then(e => {
    e.blob().then(blob => {
      const a = window.document.createElement('a');
      const downUrl = window.URL.createObjectURL(blob);
      const filename = [fileName, 'pdf'];
      a.href = downUrl;
      a.download = `${decodeURI(filename[0])}.${filename[1]}`;
      a.click();
      window.URL.revokeObjectURL(downUrl);
    });
  }).catch(e => {
    _amosTool.Log.error(e.message);
  });
};
