const system=require("../system");
var crypto = require('crypto');
var fs = require('fs');
var path = require('path');
var http=require("http");
var request = require('request');//http请求库
// var formstream = require('formstream');//http发送post请求构造表单数据的库
class AppletBase{
  constructor(){
    this.db=system.getObject("db.connection").getCon();
    this.cacheManager=system.getObject("db.cacheManager");
    this.rc=system.getObject("util.execClient");
    this.channelSve=system.getObject("service.channelSve");
    this.wxAppletConfig1={//合伙人
      appid:"wxda6eab8429128ccd",
      secret:"9a03f3ca37e97c92de9275265e4a3595"
    };
    this.wxAppletConfig2={//微商城
      appid:"wx9a01a96463f3f356",
      secret:"104ba29efa9aad971a7c5751b42cd67c"
    };
    this.wxAppletConfig3={//boss智能助手
      appid:"wx5ab0a6c0311e6b1e",
      secret:"032720f63c2b4e4b934ee5c8130e4711"
    }
    this.wxAppletConfig4={//微商水印
      appid:"wxccd57cb1f8585c77",
      secret:"f89fccbe2e044e5c4c0f579501d83f2b"
    }
    this.wxAppletConfig5={//易知产
      appid:"wx025e704bdb495dda",
      secret:"424945ff99f5b8b67fdd24efabf67933"
    }
    this.wxAppletConfig6={//司宝金服
      appid:"wx4f4451f470fb3d43",
      secret:"0c7fdefa3e2b89d82fb69af8af82dab0"
    }
    this.wxAppletConfig7={//计税宝
      appid:"wx28bd24fe4aaf5bf2",
      secret:"ef6de35a80c748d5bc641df767e3b404"
    }
    this.wxAppletConfig8={//每日易照
      appid:"wxf622b54d5f62fcdb",
      secret:"2eb29e6e244c49c1b711823f57e307a7"
    }
  }
  async getChannelByChannelCode(channelCode){
    return this.channelSve.findOne({channelCode:channelCode});
  }
  async code2Session(obj,req){
     var code = obj.code;
     var rtn=null;
     // 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/sns/jscode2session?appid=wxda6eab8429128ccd&secret=9a03f3ca37e97c92de9275265e4a3595&grant_type=authorization_code&js_code="+code;
     if( obj.apptype == 'storeapp' ){
       url="https://api.weixin.qq.com/sns/jscode2session?appid=wx9a01a96463f3f356&secret=104ba29efa9aad971a7c5751b42cd67c&grant_type=authorization_code&js_code="+code;
     }
     if( obj.apptype == 'boss' ){
       url="https://api.weixin.qq.com/sns/jscode2session?appid=wx5ab0a6c0311e6b1e&secret=032720f63c2b4e4b934ee5c8130e4711&grant_type=authorization_code&js_code="+code;
     }
     if( obj.apptype == 'wssy' ){
       url="https://api.weixin.qq.com/sns/jscode2session?appid=wxccd57cb1f8585c77&secret=f89fccbe2e044e5c4c0f579501d83f2b&grant_type=authorization_code&js_code="+code;
     }
     if( obj.apptype == 'yzc' ){
       url="https://api.weixin.qq.com/sns/jscode2session?appid=wx025e704bdb495dda&secret=424945ff99f5b8b67fdd24efabf67933&grant_type=authorization_code&js_code="+code;
     }
     if( obj.apptype == 'sbjf' ){
       url="https://api.weixin.qq.com/sns/jscode2session?appid=wx4f4451f470fb3d43&secret=0c7fdefa3e2b89d82fb69af8af82dab0&grant_type=authorization_code&js_code="+code;
     }
     if( obj.apptype == 'jsb' ){
       url="https://api.weixin.qq.com/sns/jscode2session?appid=wx28bd24fe4aaf5bf2&secret=ef6de35a80c748d5bc641df767e3b404&grant_type=authorization_code&js_code="+code;
     }
     if( obj.apptype == 'mryz' ){
       url="https://api.weixin.qq.com/sns/jscode2session?appid=wxf622b54d5f62fcdb&secret=2eb29e6e244c49c1b711823f57e307a7&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){
       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')
    }

    // 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.wxAppletConfig1;
    }else if(type==2){
      config=this.wxAppletConfig2;
    }else if(type==3){
      config=this.wxAppletConfig3;
    }else if (type==4){
      config=this.wxAppletConfig4;
    }else if (type==5){
      config=this.wxAppletConfig5;
    }else if (type==6){
      config=this.wxAppletConfig6;
    }else if(type==7){
      config=this.wxAppletConfig7;
    }else{
      config=this.wxAppletConfig8;
    }
    // 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);
      return result;
    }catch(e){
      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)
            }
          })
    })

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