'use strict';
const Service = require('egg').Service;

class CommonService extends Service {
  // 获取51shequ的oss签名
  async get_business_signature() {
    const { ctx } = this;

    const region = 'oss-cn-hangzhou';
    const bucket = '51shequ';

    const id = 'LTAIbdayv82O7OYM';
    const key = 'plCSzfiZCpMoh39omrzdaHHEltv4Un';
    const host = '//' + bucket + '.' + region + '.aliyuncs.com';
    const url = '//r.51gjj.com/';
    const now = Math.round(new Date().getTime() / 1000).toString();
    const expire = 120;
    const end = now + expire;

    const expiration = new Date().toISOString().replace(/\..+/, '') + 'Z';

    const dir = 'webpublic/resume/';

    // 最大文件大小.用户可以自己设置
    const condition = new Array(3);
    condition[0] = 'content-length-range';
    condition[1] = 0;
    condition[2] = 1048576000;

    const start = new Array('starts-with', '$key', dir);

    const conditions = new Array(condition, start);


    const policy = { expiration, conditions };


    const base64_policy = new Buffer(JSON.stringify(policy)).toString('base64');

    const string_to_sign = base64_policy;
    const crypto = require('crypto');
    const signature = crypto.createHmac('sha1', key).update(string_to_sign).digest()
      .toString('base64');
    const config = {
      region,
      accessKeyId: id,
      accessKeySecret: key,
      bucket,

    };
    const response = {
      accessid: id,
      static_host: url + dir,
      host,
      policy: base64_policy,
      signature,
      expire: end,
      config,
      dir,
    };

    return response;

  }


  async uploadOss(input) {
    const { ctx } = this;
    const image = input.image.replace(/^data:image\/\w+;base64,/, '');
    const imgBuffer = new Buffer(image, 'base64');
    const uuidv4 = require('uuid/v4');
    const uuid = uuidv4();
    const now = new Date();

    // 上传oss
    const name = 'image/catalog/' + input.directory + '/' + uuid + now.getTime() + '.png';
    const result = await ctx.oss.put(name, imgBuffer);
    if (result && typeof (result.url) !== 'undefined') {
      const url = result.url + '?height=' + input.height + '&width=' + input.width;
      return url;
    }
    ctx.failed('uploadOss failed');
  }
}

module.exports = CommonService;
