var co = require('co');
var OSS = require('ali-oss');
var jszip = require("jszip");

class OSSClient {
  constructor() {
    this.client = new OSS({
      // endpoint: 'https://oss-cn-beijing.aliyuncs.com',
      accessKeyId: 'LTAI4GC5tSKvqsH2hMqj6pvd',
      accessKeySecret: '3KV9nIwW8qkTGlrPmAe3HnR3fzM6r5',
      region: 'oss-cn-beijing',
      bucket: 'gsb-zc',
    });
    // this.client.useBucket('gsb-zc');
  }
  async downfile(key) {
    var me = this;
    var result = await co(function* () {
      var result = yield me.client.get(key, '/tmp/' + key);
      return result;
    });
    return result;
  }

  async upfile(key, filepath) {
    var me = this;
    var result = await co(function* () {
      var result = yield me.client.put(key, filepath);
      return result;
    })
    return result;
  }

  async putBuffer(key, buf) {
    try {
      var result = await this.client.put(key, buf);
      console.log(result);
      return result
    } catch (e) {
      console.log(e);
      return null
    }
  }

  async signatureUrl(key, name) {
    return this.client.signatureUrl(key,
      {
        expires: 3600,
        response: {
          "content-disposition": `attachment; filename=${name}`
        }
      });
  }
  /**
   * 
   * @param {*} fileArr [
      {
          url: '', //文件的oss存储路径 (必填)
          name: '', // 文件名 (可选, 不需要填扩展名)
          foldPath: '目录1/目录2/' //(可选, 文件在压缩包中的存储路径)
      }]
   * @param {*} zipName 
   */
  async batchDownloadAndZip(fileArr, zipName) {
    var me = this;
    return new Promise((resolve, reject) => {
      const zip = new jszip();
      let promises = [];
      fileArr.forEach(item => {
        let promise = me.getFile(item.url).then(data => {
          // 获取文件类型
          let typeArr = item.url.split(".");
          let type = typeArr[typeArr.length - 1];
          // 默认文件名·
          let nameArr = item.url.split("/");
          let name = item.name ? (item.name + '.' + type) : nameArr[nameArr.length - 1];
          let foldPath = item.foldPath || "";
          zip.file(foldPath + name, data, {
            binary: true
          });
        })
        promises.push(promise);
      });

      Promise.all(promises).then(() => {
        zip.generateAsync({ type: "nodebuffer" }).then(async (content) => {
          const url = await co(function* () {
            const result = yield me.client.put((zipName || `${new Date().getTime()}`) + '.zip', content);
            return result.url;
          });
          resolve(url);
        }).catch(err => {
          reject(err)
        });;
      });
    })
  }

  /**
   * 下载文件到内存
   * @param {*} url 
   */
  async getFile(url) {
    let me = this;
    let key;
    if (url.includes('aliyuncs.com//')) {
      let str = 'aliyuncs.com//';
      key = url.substring(url.lastIndexOf(str) + str.length, url.length);
    } else if (url.includes('aliyuncs.com/')) {
      let str = 'aliyuncs.com/';
      key = url.substring(url.lastIndexOf(str) + str.length, url.length);
    } else {
      throw new Error(`文件路径错误${url}`)
    }
    const content = await co(function* () {
      var result = yield me.client.get(key);
      return result.content;
    });
    return content;
  }
}
module.exports = OSSClient;
// var oss=new OSSClient();
// var key="netsharp_QSzjD4HdKdTmRR6b5486pEA3AbsW8Pr8.jpg"
// oss.upfile(key,"/usr/devws/OMC/igirl-api/r3.jpg").then(function(result){
//   console.log(result);
// });
// oss.downfile(key).then(function(result){
//   console.log(result);
// });
