var co = require('co');
var OSS = require('ali-oss');
const request = require("request");
const fs = require("fs");
class OSSClient {
  constructor() {
    this.client = new OSS({
      endpoint: 'https://oss-cn-beijing.aliyuncs.com',
      accessKeyId: 'LTAI4GC5tSKvqsH2hMqj6pvd',
      accessKeySecret: '3KV9nIwW8qkTGlrPmAe3HnR3fzM6r5'
    });
    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 aliurl2zcurl(key) {
    var filename=key.split("/").pop().split("?")[0];
    var writeStream = fs.createWriteStream("/tmp/tmpfile.jpg");
    var self=this;
    request(key).pipe(writeStream);
    writeStream.on('finish', function () {
      self.upfile(filename, "/tmp/tmpfile.jsp").then(function (result) {
        console.log(result.res.requestUrls[0]);
        return result.res.requestUrls[0];
      });
    })
  }

}
module.exports = OSSClient;
// var oss = new OSSClient();
// var key = "https://gsb-zc.oss-cn-beijing.aliyuncs.com/zc_86315541780601882019212740188%E4%B9%A6.jpg";
// oss.downossurlfile(key);
// /tmp/zc_86315541780601882019212740188%E4%B9%A6.jpg

// oss.upfile("20200412aaa.jpg","/tmp/zc_86315541780601882019212740188%E4%B9%A6.jpg").then(function(result){
//   console.log(result);
// });

// 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);
// });
