const system = require("../system");
var crypto = require('crypto');
var fs = require('fs');
var path = require('path');
var http = require("http");
var request = require('request');
const axios = require("axios");

class AppletBase {
  constructor() {
    this.redisClient = system.getObject("util.redisClient");
    this.merchantSve = system.getObject("service.saas.merchantSve");
    this.merchantappletuserSve = system.getObject("service.uc.merchantappletuserSve");
  }

  async getConfig(merchant_id) {
    return await this.merchantSve.getSettings(merchant_id);
  }

  async getMerchant(merchant_id) {
    return await this.merchantSve.getMerchantWithCache({id: merchant_id, forceUpdate: true});
  }

  async getLoginUser(merchant_id, openid, forceUpdate) {
    return await this.merchantappletuserSve.getLoginUser({merchant_id: merchant_id, openid: openid, forceUpdate: forceUpdate});
  }

  async code2Session(obj, req) {
    let wxConfig = await this.getConfig(obj.merchant_id);
    let code = obj.code;
    let url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxConfig.appid + "&secret=" + wxConfig.secret + "&grant_type=authorization_code&js_code=" + code;
    try {
      let rs = await axios({
        method: 'post',
        url: url,
      });
      // rtn = await this.rc.execGet({}, url);
      console.log(rs.data);
      console.log("code2Sessioncode2Sessioncode2Session");
      // var result = JSON.parse(rtn.stdout);
      return rs.data;
    } catch (e) {
      console.log(e);
      return null;
    }
  }

  async decryptData(obj) {
    // base64 decode
    var sessionKey = new Buffer(obj.sessionKey, 'base64')
    var encryptedData = new Buffer(obj.encryptedData, 'base64')
    var iv = new Buffer(obj.iv, 'base64')
    try {
      var decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv);
      decipher.setAutoPadding(true);
      var decoded = decipher.update(encryptedData, 'binary', 'utf8');
      decoded += decipher.final('utf8');
      decoded = JSON.parse(decoded);
    } catch (err) {
      console.log(err);
      throw new Error('Illegal Buffer ' + JSON.stringify(obj) + "   aaaaaaaaaa   " + err.stack);
    }
    return decoded;
  }

  async getAccessToken() {
    var rtn = null;
    var url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + this.wxConfig.appid + "&secret=" + this.wxConfig.secret;
    try {
      rtn = await this.rc.execGet({}, url);
      console.log(rtn);
      console.log("code2Sessioncode2Sessioncode2Session");
      var result = JSON.parse(rtn.stdout);
      if (result && result.access_token) {
      }
      return result;
    } catch (e) {
      return null;
    }
  }

  async getAK(type) {
    type = type || 1;
    var key = "access_token_" + this.wxConfig.appid;
    var ak = await this.redisClient.get(key);
    if (ak) {
      return ak;
    } else {
      var rs = await this.getAccessToken(type);
      if (rs && rs.access_token) {
        ak = rs.access_token;
        await this.redisClient.setWithEx(key, ak, 7000);
      }
    }

    return ak || "";
  }

  async getIdCardInfo(imageUrl, type) {
    type = type || 1;
    var ak = await this.getAK(type);
    if (!ak) {
      return;
    }
    var url = "http://api.weixin.qq.com/cv/ocr/idcard?type=photo&img_url=" + encodeURI(imageUrl) + "&access_token=" + ak;
    try {
      var rtn = await this.rc.execGet({}, url);
      console.log(rtn);
      var result = JSON.parse(rtn.stdout);
      return result;
    } catch (e) {
      console.log(e.stack)
      return null;
    }
  }

  async getBankInfo(imageUrl, type) {
    type = type || 1;
    var ak = await this.getAK(type);
    if (!ak) {
      return;
    }
    var url = "http://api.weixin.qq.com/cv/ocr/bankcard?img_url=" + encodeURI(imageUrl) + "&access_token=" + ak;
    try {
      var rtn = await this.rc.execGet({}, url);
      console.log(rtn);
      var result = JSON.parse(rtn.stdout);
      return result;
    } catch (e) {
      console.log(e.stack)
      return null;
    }
  }

  async getWXACodeUnlimit(access_token, obj) {
    var rtn = null;
    var url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_token;
    try {
      rtn = await this.rc.execPost2(obj, url);
      // var buf = Buffer.from(rtn.stdout, 'binary');
      // console.log(rtn.stdout.from());
      // var base64Data = rtn.stdout.replace(/^data:image\/\w+;base64,/, "");
      // var dataBuffer = new Buffer(base64Data, 'base64');
      // var result=JSON.parse(rtn);
      // console.log(rtn.stdout);

      return rtn.stdout;
    } catch (e) {
      return null;
    }
  }

  async sendCustomerMessage(obj, type) {
    var ctype = 1;
    if (type) {
      ctype = type;
    }
    var result = await this.getAccessToken(ctype);
    console.log(result);
    var url = ""
    if (result && result.access_token) {
      url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + result.access_token;
      try {
        return this.rc.execPost2(obj, url).stdout;
      } catch (e) {
        console.log(e);
        return null;
      }
    }

  }

  async uploadTempMaterial(filepath, type) {
    var ctype = 1;
    if (type) {
      ctype = type;
    }
    var that = this;
    var form = { //构造表单
      media: fs.createReadStream(filepath)
    }
    var result = await this.getAccessToken(ctype);
    console.log(result);
    var url = ""
    if (result && result.access_token) {
      return new Promise(function (resolve, reject) {
        var url = 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token=' + result.access_token + '&type=image';
        request.post(url, {
          formData: form,
          json: true
        }, function (err, res, body) {
          if (err) {
            reject(err);
          } else {
            console.log("111111qqqqqqqqqqqqqqq");
            console.log(body);
            resolve(body);
          }
        })
      })

    }
  }
  returnResult(code, msg, data) {
    return {
      code: code || 0,
      msg: msg || "",
      data: data
    }
  }

  returnSuccess(data) {
    return this.returnResult(1, "success", data)
  }

  returnFail(msg, data) {
    return this.returnResult(0, msg, data);
  }

  trim(o) {
    if (!o) {
      return "";
    }
    return o.toString().trim();
  }

  getUidStr(len, radix) {
    var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
    var uuid = [],
      i;
    radix = radix || chars.length;
    if (len) {
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
      var r;
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random() * 16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }
    return uuid.join('');
  }
}

module.exports = AppletBase;
// var task=new AppletBase();
// var imgpath = path.dirname(__filename) + '/impl/gzh.jpg';
// var c={media_id:"x-u4c1uLiHhV8h6ZiJ88M6FRx-HTYrlxH2x2eT00knFiuS1947klzUbwrWp5ePt6"};
// var text="4006-798-9999";
// var obj={'touser':'owD7y5JaO2DWzNqNk7cOz_nXBZAs','msgtype':'text','text':{content:"text"}};
// task.sendCustomerMessage(obj,3).then(function(result){
//   console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
//   console.log((result));
// }).catch(function(e){
//   console.log(e);
// });