
import Service from './service'
class Collection {
  /**
   * @param {*} base64Url base64字段
   * @desc 图片base64转换为blob
   */
  base64ToBlob(base64Url) {
    var bytes = window.atob(base64Url.split(',')[1]); // 去掉url的头，并转换为byte
    //处理异常,将ascii码小于0的转换为大于0
    var ab = new ArrayBuffer(bytes.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < bytes.length; i++) {
      ia[i] = bytes.charCodeAt(i);
    }
    return new Blob([ab], {
      type: 'image/png',
    });
  }
  /**
 * @param {*} theBlob Blob
 * @param {*} name 文件名称
 * @desc 图片base64转换为blob
 */
  blobToFile(theBlob, name) {
    // 创建一个新的 File 对象  
    var file = new File([theBlob], name, {
      type: theBlob.type,
      lastModified: Date.now()
    });
    return file;
  }

  // 获取所有收藏图片
  querySimplePictureFavorites() {
    let options = { pictureTypes: [1, 2, 3, 4] };
    Service.querySimplePictureFavorites(options).then((_) => {
      return Promise.resolve();
    });
  }

  // 添加图片收藏
  async addPictureFavorite(options) {
    if (options.scenceImageUrl.indexOf('data:image') >= 0) {
      // 图片地址为base64则先上传至羚羊再添加到mediaList
      const oldFile = this.base64ToBlob(options.scenceImageUrl);
      const formData = new FormData();
      let file =this.blobToFile(oldFile,'file.png')
      formData.append('file', file,'file.png');
      await Service.uploadImg(formData).then((res) => {
        if (res.code !== 0) {
          return false;
        }
        options.scenceImageUrl = options.smallImageUrl = res.data.url;
      });
    }

    return Service.addPictureFavorite(options).then((res) => {
      this.querySimplePictureFavorites();
      return res;
    });
  }
}

export default new Collection();
