const system=require("../../system");
const settings=require("../../../config/settings");
const ServiceBase=require("../sve.base");
const wxsvr=require("../wxsvr");
const fs=require("fs");
var WXPay = require('wx-pay');
var sha1 = require('sha1');
const uuidv4 = require('uuid/v4');
const path=require("path");
const logCtl=system.getObject("web.oplogCtl");
const servicepath=path.join(settings.basepath,"app/base/service");
class WxService{
  constructor(){
    this.cacheManager=system.getObject("db.cacheManager");
    this.restClient=system.getObject("util.restClient");
    this.execClient=system.getObject("util.execClient");
    this.userSve = system.getObject("service.userSve");
    this.wxpay = WXPay({
     //appid: 'wx6f3ebe44defe336a',
     //mch_id: '1232813602',
     //partner_key: 'sinotone2014sinotone2014sinotone',
      appid: 'wx4c91e81bbb6039cd',
      mch_id: '1514728461',
      partner_key: 'gongsibao1234567890zhangfeilong1',
      pfx: fs.readFileSync(servicepath+'/apiclient_cert.p12'), //微信商户平台证书
    });
  }
  async sendTmplMsg (touser,tid,queryStr,data,appkey) {
    var ak=appkey || "wx4c91e81bbb6039cd";
    var sendMsgUrlPattern = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
    var ack=await this.getWxAccessKey(ak);
    sendMsgUrlPattern=sendMsgUrlPattern+ack;
    console.log(sendMsgUrlPattern);
    var txtObj ={
          "touser":touser,
          "template_id":tid,
          "url":queryStr,
          "topcolor":"#FF0000",
          "data":data
    }
    return this.restClient.execPost(txtObj,sendMsgUrlPattern);
	}


  //推送模板消息 跳转微信小程序
  async sendTmplMsg2 (touser,tid,data,appid,pagepath,appkey) {
    var ak=appkey || "wx4c91e81bbb6039cd";
    var sendMsgUrlPattern = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
    var ack=await this.getWxAccessKey(ak);
    sendMsgUrlPattern=sendMsgUrlPattern+ack;
    console.log(sendMsgUrlPattern);
    var txtObj ={
          "touser":touser,
          "template_id":tid,
          "topcolor":"#FF0000",
          "miniprogram":{
            "appid":appid,
            "pagepath":pagepath,
          },
          "data":data
    }
    return this.restClient.execPost(txtObj,sendMsgUrlPattern);
	}
  //生成服务号的二维码
  //智信云1000
  async makeQrWithScene(appkey,val){
    var ak=appkey || "wx4c91e81bbb6039cd";
    var acck=await this.getWxAccessKey(ak);
    var cmdUrl=`https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=${acck}`;
    var postobj={
      "action_name":"QR_LIMIT_SCENE",
      "action_info":{
          "scene":{
              "scene_id": val
          }
      }
    };
    var result=await this.restClient.execPost(postobj,cmdUrl);
    var rtnobj=JSON.parse(result.stdout);
    var tkt=rtnobj.ticket;
    var qrurl=`https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=${tkt}`;
    return qrurl;
  }
  //获取OAUTH path
  async fetchOAuthPath(appkey,subfix){
    var ak=appkey || "wx4c91e81bbb6039cd";
    var appobj=await this.cacheManager["AppCache"].cacheApp(ak);
    var appkey=appobj.appid;
    var redirect_uri=encodeURIComponent(appobj.authPage);
    var state=appkey;
    var subfix2=subfix || "";
    var strtmpl= `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appkey}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=${state}${subfix2}#wechat_redirect`;
    return strtmpl;
  }
  //获取OAUTH path
  async fetchWxOAuthPath(subfix){
    var appkey="wx4c91e81bbb6039cd";
    var redirect_uri = "https://igirl.gongsibao.com/orderpay/orderpay";
    redirect_uri=encodeURIComponent(redirect_uri);
    var subfix2=subfix || "";
    var strtmpl= `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appkey}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=${subfix2}#wechat_redirect`;
    return strtmpl;
  }
  //获取wxapi-accesskey
  async getWxAccessKey(appkey){
    var ak=appkey || "wx4c91e81bbb6039cd";
    var accessKey=await this.cacheManager["WxCache"].cacheAccessToken(ak);
    return accessKey;
  }
  //获取用户信息
  async getUserInfo(openid){
    var ak=appkey || "wx4c91e81bbb6039cd";
    // var appkey=wxsvr.wxconfig.AppID;
    // console.log(appkey);
    var ack = await this.getWxAccessKey(ak);
    console.log(ack);
    var url="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+ack+"&openid="+openid+"&lang=zh_CN"
    console.log(url);
    var out=await this.execClient.execGet('',url);
    console.log(out.stdout);
    return out.stdout;
  }
  // {"subscribe":1,
  // "openid":"ozFDk0ywZa9HehiAItgkbTXR2bxA",
  // "nickname":"庄冰",
  // "sex":1,
  // "language":"zh_CN",
  // "city":"朝阳",
  // "province":"北京",
  // "country":"中国",
  // "headimgurl":"http://thirdwx.qlogo.cn/mmopen/nYqlIIYZqJSVYjWrOpBibV7j8E6Smhviav955wS3ZKNhWEqCs8GSgeEW2Wg5JqH5JfD4wj9zlAVRwIulVe5icbiblchOu0DJVWjk/132",
  // "subscribe_time":1543458037,
  // "unionid":"odnZ4t9d_RtUEWg_PigNoO6xXdSs",
  // "remark":"","groupid":0,"tagid_list":[],"subscribe_scene":"ADD_SCENE_QR_CODE","qr_scene":0,"qr_scene_str":""}

  async checkAndLogin(openid){

    try {
      console.log("checkAndLogincheckAndLogincheckAndLogincheckAndLogin");
      var userInfo = await this.getUserInfo(openid);
      console.log(userInfo);
      logCtl.error({
         optitle:"客户登录异常 测试 非异常",
         op:"service/impl/wxSve/checkAndLogin",
         content:userInfo,
         clientIp:openid
       });
      if(userInfo){
        userInfo=JSON.parse(userInfo);
        var existedUser = await this.userSve.getUserByOpenId(userInfo.openid,"wx4c91e81bbb6039cd");
        if(!existedUser){
          var wxUserInfo={
              nickName:userInfo.nickname,
              description:userInfo.country+"-"+userInfo.province+"-"+userInfo.city,
              openId:userInfo.openid,
              unionId:userInfo.unionid,
              onlyCode:userInfo.unionid,
              userName:userInfo.nickname,
              headUrl:userInfo.headimgurl,
              sex:userInfo.sex==1?"male":"female",
              // from:userInfo.province+","+userInfo.city+","+userInfo.country,
              appKey:'wx4c91e81bbb6039cd',
           };
           console.log("wxUserInfo-----------------------------------------------------");
           console.log(wxUserInfo);
          //创建用户信息
          var userRisgered=await this.userSve.login(wxUserInfo);
          console.log("userRisgered------------------------------------------");
          console.log(userRisgered);
          this.cacheManager["AppletUserinfoCache"].set(userInfo.openid,JSON.stringify(userRisgered));
        }
      }
      return userInfo
    } catch (e) {
      logCtl.error({
         optitle:"客户登录异常",
         op:"service/impl/wxSve/checkAndLogin",
         content:e.stack,
         clientIp:openid
       });
      return {
           code: -200,
           msg: "删除失败"
     };
    }

  }
  //获取jsapiconfig
  async getJsApiConfig(appkey,url){
    var ak=appkey || "wx4c91e81bbb6039cd";

    var timestamp = Math.floor(Date.now()/1000); //精确到秒
    var ticket=await this.cacheManager["WxCache"].cacheJsConfigTicket(ak);
    var noncestr='Wm3WZYTPz0wzccnW';
    var str='jsapi_ticket=' + ticket + '&noncestr=' + noncestr + '&timestamp=' + timestamp + '&url=' + url;
    var signstr=sha1(str);
    return {
          appid:ak,
          nonceStr:noncestr,
          timestamp:timestamp,
          url:url,
          jsapi_ticket:ticket,
          signature:signstr
    };
  }
  // //发送模板消息
  // async sendTmplMsg(){
  //
  // }
  //创建服务号自定义菜单
  async createWxMenu(appkey,menuObj){
    var ak=appkey || "wx4c91e81bbb6039cd";
    console.log("createWxMenu.........................");
    var acck=await this.getWxAccessKey(ak);
    console.log("access key..............");
    console.log(acck);
    console.log("access key..............");
    var createMenuUrl="https://api.weixin.qq.com/cgi-bin/menu/create?access_token={ACCESS_TOKEN}";
		createMenuUrl=createMenuUrl.replace(/\{ACCESS_TOKEN\}/g,acck);
    var menuObjTmp={
       "button":[
         {
                      "type":"view",
                      "name":"知产服务在线",
                      "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ak+"&redirect_uri=http%3A%2F%2Fboss.gongsibao.com&response_type=code&scope=snsapi_userinfo&state="+ak+"&#wechat_redirect"
         },
      ]

    };
    menuObj=menuObj || menuObjTmp;

    var out=await this.restClient.execPost(menuObj,createMenuUrl);
    return out.stdout;

  }
  //删除服务号自定义菜单
  async deleteWxMenu(appkey){
    var ak=appkey || "wx4c91e81bbb6039cd";
    var acck=await this.getWxAccessKey(ak);
    var createMenuUrl="https://api.weixin.qq.com/cgi-bin/menu/delete?access_token={ACCESS_TOKEN}";
		createMenuUrl=createMenuUrl.replace(/\{ACCESS_TOKEN\}/g,acck);
    var out=await this.restClient.execGet('',createMenuUrl);
    return out.stdout;
  }
  //查询微信订单
  async queryWxOrder(idkey){
    var self=this;
    var p=new Promise((resv,rej)=>{
       self.wxpay.queryOrder({ out_trade_no:idkey}, function(err, order){
        if(err){
          return rej(err);
        }else{
          return resv(order);
        }
      });
    });
    console.log(idkey);
    return p;
  }


  //关闭预付款单据
  async closeWxOrder(idkey){
    var self=this;
    var p=new Promise((resv,rej)=>{
      self.wxpay.closeOrder({ out_trade_no:idkey}, function(err, order){
        if(err){
          return rej(err);
        }else{
          return resv(order);
        }
      });
    });
    return p;
  }
  //创建一个js预付款单
  async createJsUnifiedOrder(desc,amount,notify_url,product_id,openid,attach,out_trade_no){
    var self=this;
    if(settings.env=="dev"){
      amount=0.01;
    }else{
      amount==Number(amount);
      //amount=0.01;
    }
		var nc={}
    if(!out_trade_no){
      var u=uuidv4();
      out_trade_no=u.replace(/\-/g,"");
    }
		var order={
				body: desc,
				out_trade_no: out_trade_no,
				total_fee: Number(amount)*100,
				notify_url: notify_url,
				product_id: product_id,
				openid:openid,
        attach:attach,
		};
　　 nc.out_trade_no=out_trade_no;//把oid传到客户端，付款成功后，传递到服务端，确认付款成功
    var promise=new Promise(function(resv,rej){
      self.wxpay.getBrandWCPayRequestParams(order,function(err,paramWxJsPay){
  			console.log(paramWxJsPay);
        if(err){
          return rej(err);
        }else{
          nc.wxpayParam=paramWxJsPay;
          return resv(nc);
        }
  		});
    });
    return promise;
  }
  //创建一个预付款单
  async createUnifiedOrder(desc,amount,notify_url,product_id,attach,out_trade_no){
    if(settings.env=="dev"){
      amount=0.01;
    }else{
      amount==Number(amount);
      //amount=0.01;
    }
    if(!out_trade_no){
      var u=uuidv4();
      out_trade_no=u.replace(/\-/g,"");
    }

    var self=this;
    var promise=new Promise(function(resv,rej){
      self.wxpay.createUnifiedOrder({
        body: desc,
        out_trade_no: out_trade_no,
        total_fee: Number(amount)*100,
        spbill_create_ip: '192.168.2.210',
        notify_url: notify_url,
        trade_type: 'NATIVE',
        product_id: product_id,
        attach:attach,
      }, function(err, result){
         if(err){
           return rej(err);
         }else{
           var qrurl=settings.apiconfig.qcurl.replace("{address}",result.code_url);
           result.qrurl=qrurl;
           result.tradekey=out_trade_no;
           return resv(result);
         }
      });
    });
    return promise;
  }

  async updateNotifyOpenId(id, notifyOpenId) {
    logCtl.info({
      optitle:"更新客户updateNotifyOpenId信息",
      op:"service/impl/wxSve/updateNotifyOpenId",
      content:"id="+id+",,notifyOpenId="+notifyOpenId,
      clientIp:""
    });
    var user = await this.userSve.findById(id);
    if(user && !user.notifyOpenId) {
      user.notifyOpenId = notifyOpenId;
      await user.save();
    }
  }
}
module.exports=WxService;
// var wxs=new WxService();
// (async()=>{
//   var ak="wxdc08c441c9fdb7a7";
//   var result=await wxs.deleteWxMenu(ak);
//   // var menuObjTmp={
//   //    "button":[
//   //      {
//   //                   "type":"view",
//   //                   "name":"电子签约",
//   //                   "url":"https://ec.gongsibao.com/h5"
//   //      },
//   //   ]
//   //
//   // };
//   // var result= await wxs.createWxMenu(ak,menuObjTmp);
//   console.log(result);
// })()

// console.log("xxxx");
// var wxs=new WxService();
// (async()=>{
//   var result= await wxs.makeQrWithScene("wxdc08c441c9fdb7a7",1000);
//   console.log(result);
// })()
// //sendTmplMsg2 (touser,tid,data,appid,pagepath) {
// var data={
//                     "first": {
//                          "value":"测试first",
//                          "color":"#173177"
//                      },
//                      "keyword1":{
//                          "value":"测试keynote1",
//                          "color":"#173177"
//                      },
//                      "keyword2": {
//                          "value":"测试keynote2",
//                          "color":"#173177"
//                      },
//                      "remark":{
//                          "value":"测试remark",
//                          "color":"#173177"
//                      }
//
// };
// wxs.sendTmplMsg2("ozFDk0ywZa9HehiAItgkbTXR2bxA","VeqWpbYKzdVvtcJoa5JGcWWK_Hl7qoHCxk25KhIxklo",data,"wxda6eab8429128ccd","page/main/index").then(d=>{
//   console.log("dele ok");
//
//
// });

// wxs.getJsApiConfig(null,"http://boss.gongsibao.com/").then(d=>{
//   console.log(d);
// });
