const FileUtil = {

  //file 为微信file 单文件
  getFileName(file){
    // size: 132224
    // thumb: "http://tmp/0ftStiYfd18K517836423bbfde024c385140a666b344.png"
    // type: "image"
    // url: "http://tmp/0ftStiYfd18K517836423bbfde024c385140a666b344.png"

    if(file){
      const uuid = this.UUID().replace("/-/g","");
      if(file.url && (file.url.indexOf(".") > -1)){
        const fileType = file.url.split(".")[1];
        return uuid+"."+fileType;
      }else{
        return;
      }
    }
    return;
  },

  UUID () {
    if (typeof crypto === 'object') {
      if (typeof crypto.randomUUID === 'function') {
        return crypto.randomUUID();
      }
      if (typeof crypto.getRandomValues === 'function' && typeof Uint8Array === 'function') {
        const callback = (c) => {
          const num = Number(c);
          return (num ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (num / 4)))).toString(16);
        };
        return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, callback);
      }
    }
    let timestamp = new Date().getTime();
    let perforNow = (typeof performance !== 'undefined' && performance.now && performance.now() * 1000) || 0;
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
      let random = Math.random() * 16;
      if (timestamp > 0) {
        random = (timestamp + random) % 16 | 0;
        timestamp = Math.floor(timestamp / 16);
      } else {
        random = (perforNow + random) % 16 | 0;
        perforNow = Math.floor(perforNow / 16);
      }
      return (c === 'x' ? random : (random & 0x3) | 0x8).toString(16);
    });
  },

  canvasToFile(){
    let canvas = window.map3DControl.viewer.canvas;
    let imgWidth = 1920;
    let img = Canvas2Image.convertToImage(
      canvas,
      imgWidth,
      (imgWidth * canvas.height) / canvas.width,
      "png"
    );
    let file_name = new Date().getTime() + ".png";
    let imgsrc = img.src.slice(22)
    
    let file = this.convertBase64UrlToImgFile(
      imgsrc,
      file_name,
      "image/png"
    )
    return file;
  },
  
  convertBase64UrlToImgFile(urlData, fileName, fileType) {
    urlData = urlData.replace(/^data:image\/\w+;base64,/, "");
    let bytes = wx.base64ToArrayBuffer(urlData);

    // var bytes = wx.atob(urlData); //转换为byte
    //处理异常,将ascii码小于0的转换为大于0
    var ab = new ArrayBuffer(bytes.length);
    var ia = new Int8Array(ab);
    var i;
    for (i = 0; i < bytes.length; i++) {
      ia[i] = bytes.charCodeAt(i);
    }
    //转换成文件，添加文件的type，name，lastModifiedDate属性
    var blob = new Blob([ab], { type: fileType });
    blob.lastModifiedDate = new Date();
    blob.name = fileName;
    return blob;
  }
}


export { FileUtil }