var system=require("../../system")
var settings=require("../../../config/settings");
const WxopBase = require("../wxop.base");
const logCtl = system.getObject("web.oplogCtl");
/**
 * 公众号消息推送
 * zhuangbing
 * 2019.07.24
 */
class PushmsgWxop extends WxopBase{
   constructor(){
     super();
     this.cacheManager=system.getObject("db.cacheManager");
     this.openplatformWxop = system.getObject("wxop.openplatformWxop");
     this.publicplatformWxop = system.getObject("wxop.publicplatformWxop");
     this.wxappSve = system.getObject("service.wxappSve");
     this.wxuserSve = system.getObject("service.wxuserSve");
     this.userSve = system.getObject("service.userSve");
     this.companySve = system.getObject("service.companySve");
   }
   async test(obj,req){
    var access_token_obj = await this.cacheManager["WxauthorizeraccesstokenCache"].get("wx5411ca0e225f2772");
    if(!access_token_obj  || !access_token_obj.authorizer_access_token){
      return "success";
    }
    var url = await this.publicplatformWxop.getOauthLink({company_id:4});
    console.log(url);
    var buttonObj={
            "button":[
              {    
                "type":"view",
                "name":"商标查询",
                "url":"http://igtest.gongsibao.com/mobiletmsearch"
              },
              {    
                "type":"view",
                "name":"商标报告",
                "url":"http://igtest.gongsibao.com/mobilereport"
              },
              {    
                "type":"view",
                "name":"知圈圈",
                "url":url
              }]
    };
    var res = await this.publicplatformWxop.menu_create({access_token:access_token_obj.authorizer_access_token,buttonObj:buttonObj});
    return res;
   }

   /**
    * 验证全网测试
    */
   async checkWeixinAllNetworkCheck(result){
    // logCtl.info({
    //   optitle: "wxop微信开放平台 全网测试 result",
    //   op: "/base/wxop/impl/pushmsgWxop.js/checkWeixinAllNetworkCheck",
    //   content: JSON.stringify(result),
    //   clientIp: ""
    // });
    try {
      if(result.MsgType=="text"){
        if(result.Content=="TESTCOMPONENT_MSG_TYPE_TEXT"){
         var replyMsg = await this.publicplatformWxop.replyMsg2({
           appid:"wx570bc396a51b8ff8",openid:result.FromUserName,
           content:result.Content+"_callback"
         });
         if(replyMsg){
          logCtl.info({
            optitle: "wxop微信开放平台 全网测试 replyMsg",
            op: "/base/wxop/impl/pushmsgWxop.js/checkWeixinAllNetworkCheck",
            content: replyMsg.toString(),
            clientIp: ""
          });
           return replyMsg;
         }
        }else if(result.Content.indexOf("QUERY_AUTH_CODE")>=0){
           var auth_code = result.Content.split(":")[1];
           //获取第三方平台调用凭据 -- component_access_token
           var component_access_token_obj = await this.cacheManager["WxcomponentaccesstokenCache"].get();
           if(component_access_token_obj && component_access_token_obj.component_access_token){
            //使用授权码换取公众号或小程序的接口调用凭据和授权信息 ---》authorizer_appid authorizer_access_token expires_in authorizer_refresh_token 
            var authorization_info_obj = await this.openplatformWxop.api_query_auth({
              component_access_token:component_access_token_obj.component_access_token,
              authorization_code:auth_code
            });
            logCtl.info({
             optitle: "wxop微信开放平台 全网测试 使用授权码换取公众号或小程序的接口调用凭据和授权信息 authorization_info_obj",
             op: "/base/wxop/impl/pushmsgWxop.js/checkWeixinAllNetworkCheck",
             content: JSON.stringify(authorization_info_obj),
             clientIp: ""
           });
           if(authorization_info_obj && authorization_info_obj.authorization_info){
             var authorization_info = authorization_info_obj.authorization_info;
             var self = this;
             var a = await self.publicplatformWxop.custom_send({
               access_token:authorization_info.authorizer_access_token,
               msgObj:{
                 "touser":result.FromUserName,
                 "msgtype":"text",
                 "text":
                 {
                   "content":auth_code+"_from_api"
                 }
               }
             });
             logCtl.info({
              optitle: "wxop微信开放平台 全网测试 客服消息",
              op: "/base/wxop/impl/pushmsgWxop.js/checkWeixinAllNetworkCheck",
              content: JSON.stringify(a),
              clientIp: ""
            });
             
           }
            
          }
        }
      }
    } catch (e) {
      logCtl.error({
        optitle: "微信开放平台 全网测试 异常",
        op: "/base/wxop/impl/pushmsgWxop.js/checkWeixinAllNetworkCheck",
        content: e.stack ,
        clientIp: ""
      });
      return "success";
    }
     
   }
   /**
    * 接收消息事件（例如关注公众号）
    */
   async receiveMsgAndEvent(pobj,obj){
      try {
          logCtl.info({
            optitle: "微信开放平台接收消息事件obj-info",
            op: "/base/wxop/impl/PushmsgWxop.js/receiveMsgAndEvent",
            content: JSON.stringify(obj)+"###################"+JSON.stringify(pobj) ,
            clientIp: ""
          });
          
          var result = await super.decryptMsg(obj.xml,pobj.msg_signature,pobj.timestamp,pobj.nonce);//获取解密信息
          logCtl.info({
            optitle: "wxop微信开放平台接收解密消息result-info",
            op: "/base/wxop/impl/pushmsgWxop.js/receiveEmpowerMsg",
            content: JSON.stringify(result) ,
            clientIp: ""
          });
          if(result){
            result=result.xml;
            if(result.ToUserName=="gh_3c884a361561"){//全网发布测试
              if(result.Content.indexOf("QUERY_AUTH_CODE")>=0){
                logCtl.info({
                  optitle: "wxop微信开放平台 全网测试 result",
                  op: "/base/wxop/impl/pushmsgWxop.js/checkWeixinAllNetworkCheck",
                  content: JSON.stringify(result),
                  clientIp: ""
                });
                this.checkWeixinAllNetworkCheck(result);
                return "";
              }else{
                var res = await this.checkWeixinAllNetworkCheck(result);
                return res;
              }
              
            }
            //appid mobile openid 
            //获取access_token by:appid
            var access_token_obj = await this.cacheManager["WxauthorizeraccesstokenCache"].get(obj.appid);
            if(!access_token_obj  || !access_token_obj.authorizer_access_token){
              return "success";
            }
            //获取微信用户基本信息（包括UnionID机制） by:access_token openid
            var wxuserinfo = await this.publicplatformWxop.api_user_info({
              access_token:access_token_obj.authorizer_access_token,
              appid:obj.appid,openid:pobj.openid
            });
            logCtl.info({
              optitle: "wxop微信开放平台获取用户信息",
              op: "/base/wxop/impl/pushmsgWxop.js/receiveEmpowerMsg",
              content: JSON.stringify(wxuserinfo) ,
              clientIp: ""
            });
            if(!wxuserinfo || (wxuserinfo.errmsg && wxuserinfo.errmsg!="ok")){
              return "success";
            }
            //获取wxapp信息
            var wxapp = await this.wxappSve.dao.model.findOne({where:{appid:obj.appid,authorized_status:"authorized"},raw:true});
            logCtl.info({
              optitle: "wxop微信开放平台获取app信息",
              op: "/base/wxop/impl/pushmsgWxop.js/receiveEmpowerMsg",
              content: JSON.stringify(wxapp) ,
              clientIp: ""
            });
            if(!wxapp || !wxapp.company_id){
              return "success";
            }
            if(result.Event=="SCAN"){//扫码进入
              var mobile = "";
              var company_id = wxapp.company_id;
              if(result.EventKey){
                var keys = result.EventKey.split("_");
                if(keys.length>0){
                  mobile=keys[0];
                  // company_id=keys[1];
                }
              }
              // if(!mobile || !company_id){
              //   return "success";
              // }
              //新建/更新用户
              var userobj = {
                appid:obj.appid,openid:pobj.openid,nick_name:wxuserinfo.nickname,head_img:wxuserinfo.headimgurl,
                mobile:mobile,sex:wxuserinfo.sex,country:wxuserinfo.country,province:wxuserinfo.province,language:wxuserinfo.language,
                subscribe_status:"subscribe",company_id:company_id
              };
              var res = await this.wxuserSve.subscribeEditWxUser(userobj);
              logCtl.info({
                optitle: "wxop微信开放平台 editWxUserInfo userobj+res",
                op: "/base/wxop/impl/pushmsgWxop.js/receiveEmpowerMsg",
                content: JSON.stringify(userobj)+"#################"+JSON.stringify(res) ,
                clientIp: ""
              });
            }else if(result.Event=="subscribe" ){//订阅
              var mobile = "";
              var company_id = wxapp.company_id;
              if(result.EventKey){
                var keys = result.EventKey.split("_");
                if(keys.length>1){
                  mobile=keys[1];
                  // company_id=keys[2];
                }
              }
              // if(!mobile || !company_id){
              //   return "success";
              // }
              //新建/更新用户
              var userobj = {
                appid:obj.appid,openid:pobj.openid,nick_name:wxuserinfo.nickname,head_img:wxuserinfo.headimgurl,
                mobile:mobile,sex:wxuserinfo.sex,country:wxuserinfo.country,province:wxuserinfo.province,language:wxuserinfo.language,
                subscribe_status:"subscribe",company_id:company_id
              };
              var res = await this.wxuserSve.subscribeEditWxUser(userobj);
              logCtl.info({
                optitle: "wxop微信开放平台 editWxUserInfo userobj+res 2",
                op: "/base/wxop/impl/pushmsgWxop.js/receiveEmpowerMsg",
                content: JSON.stringify(userobj)+"$$$$$$$$$$$$$$$"+JSON.stringify(res),
                clientIp: ""
              });
              var replyMsg = await this.publicplatformWxop.replyMsg({
                appid:obj.appid,company_id:company_id,title:"测试图文消息",description:"图文消息描述",
                openid:pobj.openid,
                picUrl:"https://gsb-zc.oss-cn-beijing.aliyuncs.com//zc_238415589395610622019271446162公司宝logo.png"
              });
              if(replyMsg){
                return replyMsg;
              }
            }else if(result.Event=="unsubscribe"){//取消订阅
              //新建/更新用户
              var userobj = {
                appid:obj.appid,openid:pobj.openid,nick_name:wxuserinfo.nickname,head_img:wxuserinfo.headimgurl,
                sex:wxuserinfo.sex,country:wxuserinfo.country,province:wxuserinfo.province,language:wxuserinfo.language,
                subscribe_status:"unsubscribe"
              };
              var res = await this.wxuserSve.unsubscribeEditWxUser(userobj);
              logCtl.info({
                optitle: "wxop微信开放平台 editWxUserInfo 2",
                op: "/base/wxop/impl/pushmsgWxop.js/receiveEmpowerMsg",
                content: JSON.stringify(res),
                clientIp: ""
              });
            }else if(result.Event=="CLICK"){//自定义菜单点击事件
              if(result.EventKey=="aboutus"){//关于我们
                var replyMsg = await this.publicplatformWxop.replyMsg({
                  replyType:2,appid:obj.appid,company_id:company_id,openid:pobj.openid,
                  content:"偏旁部首是一款在线学习汉字的字典类教学工具，用互联网技术帮助儿童用更有趣更简单的方式学习、认识汉字以及了解汉字演变历史和中华汉字文化。适合3-12岁童学使用学习。\n所属公司：北京联大共享科技有限公司"+
                  "\n合作联系\n张老师微信：540381744，添加好友时，请加备注。"
                });
                
                if(replyMsg){
                  logCtl.info({
                    optitle: "wxop微信开放平台 editWxUserInfo replyMsg 2",
                    op: "/base/wxop/impl/pushmsgWxop.js/receiveEmpowerMsg",
                    content: replyMsg.toString(),
                    clientIp: ""
                  });
                  return replyMsg;
                }
              }
            }
          }
          return "success";
      } catch (e) {
          logCtl.error({
            optitle: "微信开放平台接收消息事件异常",
            op: "/base/wxop/impl/pushmsgWxop.js/receiveMsgAndEvent",
            content: e.stack ,
            clientIp: ""
          });
          return "success";
      }
    
   }

   /**
    * 获取公众号二维码（临时）
    */
   async getQr(obj,req){
     try {
        var user = req.session.user;
        if(user){
          var company_id = user.company_id;
          var company = await this.companySve.dao.model.findOne({where:{id:company_id},raw:true});
          if(!company){
            return {code:-101,msg:"未知的公司"}
          }
          if(!company.appid){
            return {code:-102,msg:"未绑定进度推送公众号"}
          }
          var wxapp = await this.wxappSve.dao.model.findOne({where:{appid:company.appid,authorized_status:"authorized"},raw:true});
          if(!wxapp){
            return {code:-1,msg:"未绑定进度推送公众号"};
          }
          var access_token_obj = await this.cacheManager["WxauthorizeraccesstokenCache"].get(wxapp.appid);
          console.log(access_token_obj);
          if(!access_token_obj  || !access_token_obj.authorizer_access_token){
            return {code:-2,msg:"获取接口调用凭据失败"};
          }
          var qrObj={
            appid:wxapp.appid,access_token:access_token_obj.authorizer_access_token,scene:obj.scene
          };
          var qr = await this.publicplatformWxop.makeQrWithScene(qrObj);
          return {code:1,data:qr};
        }else{
          return {code:-100,msg:"用户数据为空"};
        }
     } catch (e) {
      logCtl.error({
        optitle: "微信开放平台 获取公众号二维码（临时）异常",
        op: "/base/wxop/impl/pushmsgWxop.js/getQr",
        content: e.stack ,
        clientIp: ""
      });
      return {code:-200,msg:"操作失败"};
     }
     
     
   }
   /**
    * 进度消息推送（服务进度变化时执行）
    * user
    */
   async pushMsg(obj){
     try {
        var company_id = obj.company_id;
        if(!obj.company_id){
          return {code:-12,msg:"company_id参数错误"};
        }
        var mobile = obj.mobile;
        
        if(!obj.title){
          return {code:-6,msg:"title参数错误"};
        }
        if(!obj.itemName){
          return {code:-7,msg:"itemName参数错误"};
        }
        if(!obj.progress){
          return {code:-8,msg:"progress参数错误"};
        }
        // if(!obj.customer){
        //   return {code:-9,msg:"customer参数错误"};
        // }
        // if(!obj.orderNum){
        //   return {code:-10,msg:"orderNum参数错误"};
        // }
        if(!mobile){
          return {code:-1,msg:"mobile参数错误"};
        }
        var user = await this.userSve.dao.model.findOne({
          where:{company_id:obj.company_id,
            [this.userSve.db.Op.or]: [{ mobile: mobile }, { userName: mobile }] 
          },
          raw:true
        });
        if(!user){
          return {code:-3,msg:"用户数据为空"};
        }
        if(!user.notifyOpenId){
          return {code:-4,msg:"该用户未关注公众号"};
        }
        var wxuser = await this.wxuserSve.dao.model.findOne({where:{openid:user.notifyOpenId,subscribe_status:"subscribe"},raw:true}); 
        if(!wxuser){
          return {code:-5,msg:"该用户未关注公众号"};
        }
        if(!wxuser.appid){
          return {code:-11,msg:"微信用户错误"};
        }
        var access_token_obj = await this.cacheManager["WxauthorizeraccesstokenCache"].get(wxuser.appid);
        if(!access_token_obj  || !access_token_obj.authorizer_access_token){
          return {code:-2,msg:"获取接口调用凭据失败"};
        }
        var time = await this.getTime();
        var msgobj={
          access_token:access_token_obj.authorizer_access_token,
          touser:wxuser.openid,
          queryStr:"",
          data:{
              first: {value:obj.title},//标题
              keyword1: { value: obj.itemName },//业务名称
              keyword2: { value: obj.progress },//业务进度
              // keyword3: { value: obj.customer },//客户姓名
              // keyword4: { value: obj.orderNum },//订单编号
              // keyword5: { value: time },//更新时间
              remark:{value:obj.remark||""}//备注
          }
        }
        var oauthLink = await this.publicplatformWxop.getOauthLink({company_id:company_id});
        if(oauthLink){
          msgobj["url"] = oauthLink;
        }
        return this.publicplatformWxop.sendTmplMsg(msgobj);
     } catch (e) {
        logCtl.error({
          optitle: "微信开放平台 模板消息推送 异常",
          op: "/base/wxop/impl/pushmsgWxop.js/pususerhMsg",
          content: e.stack ,
          clientIp: ""
        });
        return {code:-200,msg:"操作失败"};
      }
      
   }

   async getTime(){//获取时间
      var date=new Date();
      var year=date.getFullYear();
      var month=date.getMonth()+1;
      var day=date.getDate();
      var hour=date.getHours();
      var minute=date.getMinutes();
      var second=date.getSeconds();
      //这样写显示时间在1~9会挤占空间；所以要在1~9的数字前补零;
      if (hour<10) {
        hour='0'+hour;
      }
      if (minute<10) {
        minute='0'+minute;
      }
      if (second<10) {
        second='0'+second;
      }
      var x=date.getDay();//获取星期
      var time=year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second;
      return time;
  }
   
}
module.exports=PushmsgWxop;
// var task = new PushmsgWxop();
// var obj ={"ToUserName":"gh_3c884a361561","FromUserName":"ozy4qt5QUADNXORxCVipKMV9dss0","CreateTime":"1566012083","MsgType":"text","Content":"TESTCOMPONENT_MSG_TYPE_TEXT","MsgId":"6725970682033617358"};
// task.test({},null).then(d=>{
//   console.log("dddddddddddddddddddddddddd");
//   console.log(d);
// })