const system = require("../system");
var crypto = require('crypto');
var fs = require('fs');
var path = require('path');
var http = require("http");
var request = require('request');
class AppletBase {
    constructor() {
        this.db = system.getObject("db.connection").getCon();
        this.cacheManager = system.getObject("db.cacheManager");
        this.redisClient = system.getObject("util.redisClient");
        this.rc = system.getObject("util.execClient");
        this.configDLG = { //打零工
            appid: "wx32bfeb4bde101eb0",
            secret: "966718f84fbf864db4fa1d5aeee9bd10"
        };
    }

    async   code2Session(obj, req) {
        var code = obj.code;
        var rtn = null;
        var url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + this.configDLG.appid + "&secret=" + this.configDLG.secret + "&grant_type=authorization_code&js_code=" + code;
        try {
            rtn = await this.rc.execGet({}, url);
            console.log(rtn);
            console.log("code2Sessioncode2Sessioncode2Session");
            var result = JSON.parse(rtn.stdout);
            return result;
        } catch (e) {
            console.log(e);
            return null;
        }
    }
    async getUserInfo(openid) {
        return this.cacheManager["AppletUserinfoCache"].get(openid);
    }

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

        // if (decoded.watermark.appid !== "wxda6eab8429128ccd") {
        //   throw new Error('Illegal Buffer')
        // }

        return decoded
    }
    async getAccessToken(type) {
        var rtn = null;
        var config = {};
        if (type == 1) {
            config = this.configDLG;
        }
        // var url="https://api.weixin.qq.com/sns/jscode2session?appid=wx57678a30a6b5babc&secret=ac845d30d8973cc5e8e5b061b50f3263&grant_type=authorization_code&js_code="+code;
        var url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + config.appid + "&secret=" + config.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 config = {};
        if (type == 1) {
            config = this.configDLG;
        }
        var key = "access_token_" + config.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 config;
        if (type == 1) {
            config = this.configDLG;
        }
        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 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);
                    }
                })
            })

        }
    }

    trim(str) {
        return str ? str.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);
// });