var system=require("../../system")
const http=require("http")
const querystring = require('querystring');
var settings=require("../../../config/settings");
const CtlBase = require("../ctl.base");
const logCtl=system.getObject("web.oplogCtl");
class UserCtl extends CtlBase{
   constructor(){
     super(CtlBase.getServiceName(UserCtl));
     //this.loginS=system.getObject("service.userSve");
     this.restS=system.getObject("util.restClient");
     this.smsS=system.getObject("util.smsClient");
   }
  //  async update(ueryobj,qobj,req){
  //    if(qobj.ecompany_id && qobj.ecompany_id!=""){
  //      //为了实现下个页面的跳转获取参数
  //      if(req.session){
  //        req.session.ecompany_id=qobj.ecompany_id;
  //      }
  //    }
  //    var results=await super.update(ueryobj,qobj,req);
  //    return results;
  //  }
   async loginUser(qobj,pobj,req) {
     return super.findById(req.session.user.id);
   }
   //获取验证码，发送给指定手机
   async fetchVcode(qobj,pobj,req){
      var mobile= pobj.mobile;
      //生成一个验证码，发送
      var vcode=await this.service.getUidStr(6,10);
      await this.smsS.sendMsg(mobile,vcode);
      return system.getResult2({vcodestr:vcode});
   }
   async checkLogin(qobj,req){
      if(req.session.user){
        var tmp={
          id:req.session.user.id,
          nickName:req.session.user.nickName,
          mobile : req.session.user.mobile,
          isAdmin:req.session.user.isAdmin,
        }
        return system.getResult2(tmp,req);
      }else{
        var x={
          status:-99,
          msg:"no login"
        };
        req.session.user=null;
        req.session.destroy();
        return system.getResult2(x,req);
      }
   }
   async exit(qobj,req){
     req.session.user=null;
     req.session.destroy();
     return system.getResult2("exit");
   }
   async register(qobj,pobj,req){
      console.log(pobj.u);
      var u=await this.service.register(pobj.u);
      //req.session.user=u;
      return system.getResult2(u);
   }
   async login(qobj,pobj,req){
       //state为p_app表中appkey
       var existedUser=await this.service.getUserByUserNamePwd(pobj.u);
       if(existedUser!=null){
         req.session.user=existedUser;
        }
        return system.getResult2(existedUser);
   }
   async getUserInfo(accessToken, openId) {
      let reqUrl = 'https://api.weixin.qq.com/sns/userinfo';
      let params = {
        access_token: accessToken,
        openid: openId,
        lang: 'zh_CN'
      };

      var data=querystring.stringify(params);
      var rtn=await this.restS.execGet(data,reqUrl);
      return JSON.parse(rtn.stdout);
    }
   async getToken(code,req,state) {
     if(settings.env=="prod"){
       let reqUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token';
       console.log(state);
       var appobj=await this.cacheManager["AppCache"].cacheApp(state);
       console.log(appobj);
       let params = {
         appid: appobj.appid,
         secret: appobj.secret,
         code: code,
         grant_type: 'authorization_code'
       };
       var data=querystring.stringify(params);
       var rtn=await this.restS.execGet(data,reqUrl);
       return JSON.parse(rtn.stdout);
     }else{
       var rtn={
          "access_token":"ACCESS_TOKEN",
          "expires_in":7200,
          "refresh_token":"REFRESH_TOKEN",
          "openid":"xxyy",
          "scope":"SCOPE",
          "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
       }
       return rtn;
     }
    }
    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('');
    }
    
}
module.exports=UserCtl;
