var system=require("../../system")
const http=require("http")
var fs=require("fs");
const querystring = require('querystring');
var settings=require("../../../config/settings");
const AppletBase =require("../applet.base");
const cryptoJS = require("crypto-js");
const logCtl=system.getObject("web.oplogCtl");
var path = require('path');
// var iconv = require('iconv-lite');
class wxApplet extends AppletBase{
   constructor(){
     super();
     this.userSve=system.getObject("service.userSve");
     this.partnerinfoSve=system.getObject("service.partnerinfoSve");
     this.ossClient=system.getObject("util.ossClient");
     this.statisticalrateSve=system.getObject("service.statisticalrateSve");
     this.uploadCtl=system.getObject("web.uploadCtl");
     this.gsbIcSearchApi=system.getObject("api.gsbicsearch");
   }
   async 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('');
   }
   async checkAndLogin(o,obj,req){
     var wxSession = await this.code2Session(obj,req);
     console.log(obj);
     var iv=obj.detail.iv;
     var encryptedData=obj.detail.encryptedData;
     console.log(wxSession);
     var decryptObj={
       encryptedData:encryptedData,
       iv:iv,
       sessionKey:wxSession.session_key
     };
     console.log(decryptObj);
     var decryptData= await this.decryptData(decryptObj);
     console.log(decryptData);
     if(decryptData && decryptData.openId){
       console.log("wx ------------------------------------ login");
       var existedUser = await this.userSve.getUserByOpenId(decryptData.openId,"wxda6eab8429128ccd");
       if( obj.apptype == 'storeapp' ){//微商城
         existedUser = await this.userSve.getUserByOpenId(decryptData.openId,"wx9a01a96463f3f356");
         }
        if( obj.apptype == 'boss' ){//boss智能助手
           existedUser = await this.userSve.getUserByOpenId(decryptData.openId,"wx5ab0a6c0311e6b1e");
        }
        if( obj.apptype == 'wssy' ){//微商水印
          existedUser = await this.userSve.getUserByOpenId(decryptData.openId,"wxccd57cb1f8585c77");
        }
        if( obj.apptype == 'yzc' ){//ie标
          existedUser = await this.userSve.getUserByOpenId(decryptData.openId,"wx025e704bdb495dda");
        }
        if( obj.apptype == 'sbjf' ){
          existedUser = await this.userSve.getUserByOpenId(decryptData.openId,"wx4f4451f470fb3d43");
        }
        if( obj.apptype == 'jsb' ){//计税宝
          existedUser = await this.userSve.getUserByOpenId(decryptData.openId,"wx28bd24fe4aaf5bf2");
        }
       if( obj.apptype == 'mryz' ){//每日易照
         existedUser = await this.userSve.getUserByOpenId(decryptData.openId,"wxf622b54d5f62fcdb");
       }
       console.log(existedUser);
       if(existedUser!=null){
         console.log("already existed............");
         this.cacheManager["AppletUserinfoCache"].set(decryptData.openId,JSON.stringify(existedUser));
       }else{
         var random=Math.floor(Math.random () * 900) + 100;
         var userInfo=obj.userInfo;
         if(decryptData.unionId==obj.from){
           obj.from="";
         }
         var uid=await this.getUidStr(10,60);
         var wxUserInfo={
             serviceCustomerCount:random,
             nickName:decryptData.nickName,
             description:decryptData.country+"-"+decryptData.province+"-"+decryptData.city,
             openId:decryptData.openId,
             unionId:decryptData.unionId?decryptData.unionId:"artificial_"+uid,
             onlyCode:decryptData.unionId?decryptData.unionId:"artificial_"+uid,
             userName:decryptData.nickName,
             headUrl:decryptData.avatarUrl,
             referrerOnlyCode:obj.from,
             companyOnlyCode:decryptData.unionId?decryptData.unionId:"artificial_"+uid,
             // sex:userInfo.sex==1?"male":"female",
             // from:userInfo.province+","+userInfo.city+","+userInfo.country,
             appKey:decryptData.watermark.appid,
          };
          console.log("wxUserInfo-----------------------------------------------------");
          console.log(wxUserInfo);
         //创建用户信息
         var userRisgered=await this.userSve.login(wxUserInfo);
         console.log("userRisgered------------------------------------------");
         console.log(userRisgered);
         this.cacheManager["AppletUserinfoCache"].set(decryptData.openId,JSON.stringify(userRisgered));
         //
         // //返回要跳转的具体应用的地址
         // var app=await this.appSve.getApp(state);
         // req.session.app=app;
         // return app.homePage;
       }
     }
     return decryptData;
   }

   async getUserInfo(obj,req){
     var openid = obj.openId;
     await this.cacheManager["AppletUserinfoCache"].del(openid);
     return this.cacheManager["AppletUserinfoCache"].get(openid);
   }
   async updateUserInfo(obj,req){
     var openid = req.openId;
     var uinfo=req.uinfo;
     await this.userSve.dao.updateByWhere(uinfo,{where:{id:uinfo.id}});
     await this.cacheManager["AppletUserinfoCache"].del(openid);
     return this.cacheManager["AppletUserinfoCache"].get(openid);
   }
   async getUserStatisticGroupByApp(obj){
     return this.userSve.getUserStatisticGroupByApp();
   }
   async checkSignature(obj,obj2){//小程序客服 合伙人
     console.log("checkSignaturecheckSignaturecheckSignaturecheckSignaturecheckSignature");
     console.log(obj);
     if(!obj2){
       var signature = obj["signature"];
       var timestamp = obj["timestamp"];
       var nonce = obj["nonce"];
       // String echostr=request.getParameter("echostr");
       var echostr = obj["echostr"];
       var token = "czhdzconline201811261737";//xJ2cAt72B0ayUdBFMPTXCHO8hQIMCVSDAchprk2tshn
       var tmpArr = [token, timestamp, nonce];
       tmpArr.sort();
       console.log(tmpArr);
       var tmpStr = tmpArr.join("");

       tmpStr = cryptoJS.SHA1(tmpStr).toString();
       console.log(tmpStr);
       logCtl.error({
          optitle:"checkSignature方法测试 非异常,signature="+signature+"content:"+tmpStr+"timestamp="+timestamp+",nonce="+nonce+"type="+typeof obj.echostr,
          op:"wxapplet/impl/wxApplet/checkSignature",
          content:obj["echostr"],
          clientIp:echostr
        });

       if (tmpStr == signature ) {
           return echostr;
       } else {
           return false;
       }
       return false;
     }else{
       logCtl.error({
          optitle:"checkSignature方法测试2 非异常,obj2.MsgType="+obj2.MsgType+"FromUserName="+obj2.FromUserName,
          op:path.dirname(__filename) + '/gzh.jpg',
          content:obj2.FromUserName,
          clientIp:obj2.Content
        });
       if(obj2.MsgType=="event" && obj2.Event=="user_enter_tempsession"){
         var text="欢迎使用创知厚德知产客服\n回复1，关注公众号，获取服务实时进度\n回复2，获取客服热线\n回复3，获取公司地址";
         var obj={'touser':obj2.FromUserName,'msgtype':'text','text':{content:text}};
         this.sendCustomerMessage(obj);
       }else{
         if(obj2.MsgType=="text" && obj2.Content){
           try {
             var imagePath = path.dirname(__filename) + '/gzh.jpg';
             if(obj2.Content=="1"){//关注公众号，获取服务实时进度
               logCtl.error({
                  optitle:"checkSignature方法测试==1 非异常,material.id="
                });
               var material = await this.uploadTempMaterial(imagePath);
               if(material && material.media_id){
                 var o={'touser':obj2.FromUserName,'msgtype':'image','image':{'media_id':material.media_id}}
                 this.sendCustomerMessage(o);
               }
             }else if(obj2.Content=="2"){//获取客服已电话
               logCtl.error({
                  optitle:"checkSignature方法测试==2 非异常,material.id="
                });
               var text="4006-798-9999";
               var obj={'touser':obj2.FromUserName,'msgtype':'text','text':{content:text}};
               this.sendCustomerMessage(obj);
             }else if(obj2.Content=="3"){//获取公司地址
               logCtl.error({
                  optitle:"checkSignature方法测试==3 非异常,material.id="
                });
               var text="北京市朝阳区创远路36号院10号楼1层102";
               var obj={'touser':obj2.FromUserName,'msgtype':'text','text':{content:text}};
               this.sendCustomerMessage(obj);
             }else{
               return "success"
             }
           } catch (e) {
             logCtl.error({
                optitle:"checkSignature方法测试3 非异常,material.id="+material.media_id,
                op:"wxapplet/impl/wxApplet/checkSignature",
                content:e.stack,
                clientIp:''
              });
           }
         }
       }
     }

  }
  async getWxMobile(o,obj,req){
    // var obj=JSON.parse(obj.d);
    console.log("obj---req......");
    console.log(obj);
    var wxSession = await this.code2Session(obj,req);
    var iv=obj.iv;
    var encryptedData=obj.encryptedData;
    console.log("encryptedData+++++++++++++++++++++++++++++");
    console.log(wxSession);
    var decryptObj={
      encryptedData:encryptedData,
      iv:iv,
      sessionKey:wxSession.session_key
    };
    console.log("decryptObj++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
    console.log(decryptObj);
    var decryptData= await this.decryptData(decryptObj);
    console.log(decryptData);
    return decryptData;
  }
  async hhrApply(obj,req){
    var openid = obj.openId;
    var mobile = obj.mobile;
    try {
      var user = await this.userSve.findOne({openId:openid});
      // user = JSON.parse(user);
      user = user.dataValues;
      // var partnerinfo = await this.partnerinfoSve.findOne({user_id:user.id,app_id:user.app_id});
      if(user.mobile!="" && user.mobile!=null){
        return {msg:"existed",code:"2"};
      }else{
        var obj ={id:user.id,mobile:mobile}
        await this.userSve.dao.model.update(obj,{where:{id:obj.id}});
        await this.cacheManager["AppletUserinfoCache"].del(openid);
        return {msg:"success",code:"1"};
      }
    } catch (e) {
      return {msg:"fail",code:"-1"};
    }

  }
  async getAppletQr(obj){//微商城 appType:1合伙人 2微商城 3boss 5 易知產,  page ,scene
    console.log("11111111111");
    console.log(obj);
    var type=obj.appType?Number(obj.appType):2;
    var access = await this.getAccessToken(type);
    var that=this;
    if(access.access_token){
      // var scene="1"+obj.uid;
      // if(obj.orderNum){
      //   scene="3"+obj.orderNum
      // }
      var scene = obj.scene;
      if(obj.uid){
        scene="1"+obj.uid;
      }
      if(obj.orderNum){
        scene="3"+obj.orderNum
      }
      var o={
        scene:scene,
        page:obj.page?obj.page:"pages/shop/index",
        is_hyaline:false
      };
      console.log(o.page);
      var base64 = await this.getWXACodeUnlimit(access.access_token,o);
      console.log(base64);
      if(base64){
        var img = base64;
        try {
          var fileName = "qr_"+new Date().getTime()+scene+".png";
          var filePath = '/tmp/' + fileName;
          var dataBuffer = new Buffer(img, 'base64');
          var result=null;
          // fs.writeFile(filePath, dataBuffer,function (err, data) {
          //     if (err) {
          //         console.log(err);
          //     }
          //     result= await that.ossClient.upfile(fileName,filePath);
          // });
          var r = await this.writeFile(filePath, dataBuffer);
          if(r=="success"){
            var result= await that.ossClient.upfile(fileName,filePath);
            console.log(result);
            fs.unlink(filePath,e=>{
              console.log("fail");
            });
            return result.url;
          }else{
            return null;
          }
        } catch (e) {
          logCtl.error({
             optitle:"生成二维码异常error",
             op:"wxapplet/impl/wxApplet/getAppletQr",
             content:e.stack,
             clientIp:""
           });
          return null;
        }
      }
    }else{
      return access;
    }
  }
  async getBossAppletQr(obj){//Boss
    var access = await this.getAccessToken(3);
    var that=this;
    if(access.access_token){
      var cn=obj.customerNum?obj.customerNum:"82438282";
      var scene=cn;
      if(obj.orderNum){
        scene=scene+";"+obj.orderNum
      }
      var o={
        scene:scene,
        page:"pages/main/index",
        is_hyaline:true
      };
      var base64 = await this.getWXACodeUnlimit(access.access_token,o);
      if(base64){
        var img = base64;
        try {
          var fileName = "qr_boss_"+new Date().getTime()+obj.customerNum+".png";
          var filePath = '/tmp/' + fileName;
          var dataBuffer = new Buffer(img, 'base64');
          var result=null;
          var r = await this.writeFile(filePath, dataBuffer);
          if(r=="success"){
            var result= await that.ossClient.upfile(fileName,filePath);
            fs.unlink(filePath,e=>{
              console.log("fail");
            });
            return result.url;
          }else{
            return null;
          }

        } catch (e) {
          logCtl.error({
             optitle:"生成boss二维码异常error",
             op:"wxapplet/impl/wxApplet/getBossAppletQr",
             content:e.stack,
             clientIp:""
           });
          return null;
        }
      }
    }else{
      return access;
    }
  }
  async writeFile(filePath,dataBuffer){
    var promise=new Promise(function(resv,rej){
      fs.writeFile(filePath, dataBuffer,function (err, data) {
          if (err) {
            rej(err);
              // console.log(err);
          }else{
            resv("success");
          }

      });
    });
    return promise;
  }
  async getStatisticData(){
    return this.statisticalrateSve.getStatisticData();
  }
  async getUploadConfig(obj,obj2){
    var openid = obj.openId;
    var user = await this.cacheManager["AppletUserinfoCache"].get(openid);
    if(user){
      user=JSON.parse(user);
      if(user.app && user.app.appid && user.app.appid == "wxda6eab8429128ccd"){
          var data = await this.uploadCtl.getOssConfig();
          return {code:1,data:data};
      }else{
        return {code:-2,data:""};
      }
    }
    return {code:-1,data:""};
  }
  //post
  async getCompanyInfoByLikeName(obj,req){
    try {
      console.log("---------------------getCompanyInfoByLikeName------------------------------");
      var openid = req.openid;
      if(!openid){
        return {code:-1,msg:"openid参数有误"};
      }
      console.log(openid);
      var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
      console.log(userInfo);
      if(userInfo){
        userInfo=JSON.parse(userInfo);
        console.log(userInfo);
        var appkey=userInfo.app.appid;
        var data={
          appKey:appkey,
          pagesize:req.ps?req.ps:5,
          page:req.cp?req.cp:0,
          companyName:req.likestr,
        };
        var company =await this.gsbIcSearchApi.companynamesearch(data);
        if(company.status==0){
          return {code:1,data:company.data.list};
        }else{
          return {code:-3};
        }

      }else{
        return {code:-2,msg:"删除失败"};
      }
    } catch (e) {
      console.log("openShop===========error");
      console.log(e);
      //日志记录
      logCtl.error({
         optitle:"大数据获取公司异常,openid="+openid,
         op:"wxapplet/impl/wxApplet/getCompanyInfoByLikeName",
         content:e.stack,
         clientIp:req.clientIp
       });
      return {
           code: -200,
           msg: "删除失败"
     };
    }

  }

  //post
  async getCompanyInfoByCompanyName(obj,req){
    try {
      console.log("---------------------getCompanyInfoByLikeName------------------------------");
      var openid = req.openid;
      if(!openid){
        return {code:-1,msg:"openid参数有误"};
      }
      console.log(openid);
      var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
      console.log(userInfo);
      if(userInfo){
        userInfo=JSON.parse(userInfo);
        console.log(userInfo);
        var appkey=userInfo.app.appid;
        var data={
          appKey:appkey,
          companyName:req.companyName,
        };
        var company =await this.gsbIcSearchApi.companynameonesearch(data);
        if(company.status==0){
          return {code:1,data:company.data.list};
        }else{
          return {code:-3};
        }

      }else{
        return {code:-2,msg:"删除失败"};
      }
    } catch (e) {
      console.log("openShop===========error");
      console.log(e);
      //日志记录
      logCtl.error({
         optitle:"大数据获取公司异常,openid="+openid,
         op:"wxapplet/impl/wxApplet/getCompanyInfoByLikeName",
         content:e.stack,
         clientIp:req.clientIp
       });
      return {
           code: -200,
           msg: "删除失败"
     };
    }

  }

  async checkWxSignature(obj,obj2){
    console.log("checkSignaturecheckSignaturecheckSignaturecheckSignaturecheckSignature");
    console.log(obj2);
    if(!obj2){
      return "success";
    }else{
      logCtl.error({
         optitle:"checkSignature方法测试33 非异常,obj2.MsgType="+obj2.MsgType+";"+obj2.Content,
         op:"wxapplet/impl/wxApplet/checkSignature",
         content:obj2.Event,
         clientIp:''
       });
      if(obj2.MsgType=="event" && obj2.Event=="user_enter_tempsession"){
        var text="欢迎使用创知厚德知产客服\n回复1，关注公众号，获取服务实时进度\n回复2，获取客服热线\n回复3，获取公司地址";
        var obj={'touser':obj2.FromUserName,'msgtype':'text','text':{content:text}};
        this.sendCustomerMessage(obj,3);
      }else{
        if(obj2.MsgType=="text" && obj2.Content){
          try {
            var imagePath = path.dirname(__filename) + '/gzh.jpg';
            if(obj2.Content=="1"){//关注公众号，获取服务实时进度
              var material = await this.uploadTempMaterial(imagePath,3);
              if(material && material.media_id){
                var o={'touser':obj2.FromUserName,'msgtype':'image','image':{'media_id':material.media_id}}
                this.sendCustomerMessage(o,3);
              }
            }else if(obj2.Content=="2"){//获取客服已电话
              var text="4006-798-9999";
              var obj={'touser':obj2.FromUserName,'msgtype':'text','text':{content:text}};
              this.sendCustomerMessage(obj,3);
            }else if(obj2.Content=="3"){//获取公司地址
              var text="北京市朝阳区创远路36号院10号楼1层102";
              var obj={'touser':obj2.FromUserName,'msgtype':'text','text':{content:text}};
              this.sendCustomerMessage(obj,3);
            }else{
              return "success"
            }
          } catch (e) {
            logCtl.error({
               optitle:"checkSignature方法测试3 非异常,material.id=",
               op:"wxapplet/impl/wxApplet/checkSignature",
               content:e.stack,
               clientIp:''
             });
          }
        }
      }
    }
  }
  async getCropperPic(qobj,obj,req){
      var that = this;
      var base64 = obj.base64;
      if(base64){
        if(base64.indexOf(";base64,")>0){
          base64 = base64.split(";base64,")[1];
        }
        var img = base64;
        var uid=await this.getUidStr(6,60);
        try {
          var fileName = "zc_cropper"+new Date().getTime()+uid+".jpg";
          var filePath = '/tmp/' + fileName;
          var dataBuffer = new Buffer(img, 'base64');
          console.log(dataBuffer);
          var result=null;
          var r = await this.writeFile(filePath, dataBuffer);
          if(r=="success"){
            var result= await that.ossClient.upfile(fileName,filePath);
            fs.unlink(filePath,e=>{
              console.log("fail");
            });
            return result.url;
          }else{
            return null;
          }

        } catch (e) {
          logCtl.error({
            optitle:"获取切图异常error",
            op:"ctl.base.js+++++getCropperPic",
            content:e.stack,
            clientIp:""
          });
          return null;
        }
      }
  }
  
}
module.exports=wxApplet;
