import * as request from '../../utils/request';
import config from '../../config/config';
import {upload} from "../../utils/request";

export function getFilesList(params) {
  return request.get(`${config.base_api.getFilesList}`, params);
}

export function onUpload(params) {
  return request.upload(`${config.base_api.onUpload}`, params);
}

export function onDelete(params) {
  return request.post(`${config.base_api.onDelete}`, params);
}

export function onDownload(record) {
  const event = document.createEvent("MouseEvents");
  const element = document.createElement("a");
  element.href = URL.createObjectURL(convertBase64ToBlob("data:" + record.type + ";base64," + record.base64));
  element.download = record.name;
  event.initEvent("click", true, true);
  element.dispatchEvent(event);
}

var convertBase64ToBlob = function(base64){
  var base64Arr = base64.split(',');
  var imgtype = '';
  var base64String = '';
  if(base64Arr.length > 1){
    //如果是图片base64，去掉头信息
    base64String = base64Arr[1];
    imgtype = base64Arr[0].substring(base64Arr[0].indexOf(':')+1,base64Arr[0].indexOf(';'));
  }
  // 将base64解码
  var bytes = atob(base64String);
  //var bytes = base64;
  var bytesCode = new ArrayBuffer(bytes.length);
  // 转换为类型化数组
  var byteArray = new Uint8Array(bytesCode);

  // 将base64转换为ascii码
  for (var i = 0; i < bytes.length; i++) {
    byteArray[i] = bytes.charCodeAt(i);
  }

  // 生成Blob对象（文件对象）
  return new Blob( [bytesCode] , {type : imgtype});
};

export function downloadTemplate(params) {
  return request.download(`${config.system_api.downloadTemplate}`, params, "template").then((res) => {
    console.log(res);
    const event = document.createEvent("MouseEvents");
    const element = document.createElement("a");
    element.href = URL.createObjectURL(res.data);
    element.download = "模板文件.xlsx";
    event.initEvent("click", true, true);
    element.dispatchEvent(event);
  });
}
