const system = require("../../../system");
var settings = require("../../../../config/settings");
const uuidv4 = require('uuid/v4');
// var crypto = require('crypto');
/**
 * 飞书小程序相关接口
 */
class UtilsFeishuService{
  constructor() {
    this.execClient = system.getObject("util.execClient");
    this.cacheManager = system.getObject("db.common.cacheManager");
    this.utilsAuthSve = system.getObject("service.utilsSve.utilsAuthSve");
    this.appConfig={
      app_id:"cli_9e28dcb1d637100d",
      app_secret:"zL1uRrWFzwhFbLWZrmSuCh72JGjJXQg0"
    }
  };
  //飞书事件消息通知解密
  // async notifyDecrypt(str){
  //   var pobj = {};
  //   str = str.toString('utf8');
    
  //   return pobj;
  // }
  //飞书通知
  async notify(pobj){
    if(!pobj || !pobj.type){
      return system.getResultFail("参数错误");
    }
    if(pobj.type=="url_verification"){//表示这是一个验证请求 
      return this.subscribeVerification(pobj);
    }
    if(pobj.type=="event_callback"){//事件回调
      if(!pobj.event){
        return system.getResultFail("event参数错误");
      }
      var event = pobj.event;
      if(event.type=="app_ticket"){//app_ticket 事件
        return this.receiveAppTicket(pobj);
      }else{
        return system.getResultFail("未知事件");
      }
    }
    return system.getResultFail("未知事件");
  }
  //订阅验证
  async subscribeVerification(pobj){
    if(pobj && pobj.challenge){
      return {"challenge":pobj.challenge};
    }else{
      return {};
    }
  }
  //接收app_ticket
  async receiveAppTicket(pobj){
    if(pobj && pobj.event && pobj.event.app_ticket && pobj.event.type && pobj.event.type=="app_ticket"){
      //将app_ticket保存到缓存
      await this.cacheManager["feishuAppTicketCache"].set(pobj.event.app_ticket);
      return system.getResultSuccess();
    }
    return system.getResultFail();
  }
  //重新推送app_ticket（主动触发)
  async resendAppTicket(){
    var url = "https://open.feishu.cn/open-apis/auth/v3/app_ticket/resend";
    var pobj = {
      app_id:this.appConfig.app_id,//应用唯一标识，创建应用后获得
      app_secret:this.appConfig.app_secret//应用秘钥，创建应用后获得
    };
    var rtn = await this.execClient.execPost(pobj, url);
    if (!rtn || !rtn.stdout) {
      return system.getResult(null, "execPost data is empty");
    }
    var result = JSON.parse(rtn.stdout);
    if(result.code==0){
      return system.getResultSuccess();
    }
    return system.getResult(null, "execPost data is empty.错误码："+result.code);
  }
  //获取app_access_token（应用商店应用）
  async getAppAccessToken(){
    var appAccessToken = await this.cacheManager["feishuAppAccessTokenCache"].get();
    if(appAccessToken){
      return system.getResultSuccess(appAccessToken);
    }
    var app_ticket = await this.cacheManager["feishuAppTicketCache"].get();
    if(!app_ticket){
      await this.resendAppTicket();//重新推送app_ticket
      return system.getResultFail("app_ticket不存在");
    }
    var url = "https://open.feishu.cn/open-apis/auth/v3/app_access_token";
    var obj = {
      app_id:this.appConfig.app_id,//应用唯一标识，创建应用后获得
      app_secret:this.appConfig.app_secret,//应用秘钥，创建应用后获得
      app_ticket:app_ticket//平台定时推送给应用的临时凭证，通过事件监听机制获得，详见订阅事件
    };
    var rtn = await this.execClient.execPost(obj, url);
    if (!rtn || !rtn.stdout) {
      return system.getResult(null, "execPost data is empty");
    }
    var result = JSON.parse(rtn.stdout);
    if(result.code==0 && result.app_access_token){
      //缓存AppAccessToken
      await this.cacheManager["feishuAppAccessTokenCache"].set(result.app_access_token,result.expire);
      return system.getResultSuccess(result.app_access_token);
    }
    return system.getResultFail("获取appAccessToken失败");
  }


  //------------------------飞书网页开发---------------------------------------------------------------
  //获取登录用户身份
  async getUserAccessToken(obj){
    var resData = {};
    if(obj.open_id){
      //缓存中获取登录用户身份
      resData = await this.cacheManager["feishuUserAccessTokenCache"].get(obj.open_id);
    }
    //缓存中存在 直接返回
    if(resData && resData.access_token){
      return system.getResultSuccess(resData);
    }
    if(!obj.code){
      return system.getResultFail("code参数不能为空");
    }
    if(!obj.app_access_token){
      return system.getResultFail("app_access_token参数不能为空");
    }
    var url = "https://open.feishu.cn/open-apis/authen/v1/access_token";
    var fsObj={
      app_access_token:obj.app_access_token,//应用的 app_access_token，必须与请求身份验证中的应用保持一致
      grant_type:"authorization_code",//在本流程中，此值为 authorization_code
      code:obj.code //来自请求身份验证(新)流程，用户扫码登录后会自动302到redirect_uri并带上此参数
    };
    var rtn = await this.execClient.execPost(fsObj, url);
    if (!rtn || !rtn.stdout) {
      return system.getResult(null, "execPost data is empty");
    }
    var result = JSON.parse(rtn.stdout);
    if(result.code==0 && result.data){
      //缓存AppAccessToken
      await this.cacheManager["feishuUserAccessTokenCache"].set(result.data,result.data.open_id);
      return system.getResultSuccess(result.data);
    }
    return system.getResult(null, "获取飞书登录用户身份失败");
  }
  //获取用户信息
  async getUserInfo(pobj){
    if(!pobj.user_access_token){
      return system.getResultFail("user_access_token参数不能为空")
    }
    var url = "https://open.feishu.cn/open-apis/authen/v1/user_info";
    var obj = {
      user_access_token:pobj.user_access_token
    };
    var rtn = await this.execClient.execFeishuGet(obj, url);
    if (!rtn || !rtn.stdout) {
      return system.getResult(null, "execPost data is empty");
    }
    var result = JSON.parse(rtn.stdout);
    if(result.code==0 && result.data){
      return system.getResultSuccess(result.data);
    }
    return system.getResult(null, "获取飞书用户信息失败");
  }
  //------------------------飞书网页开发-------结束--------------------------------------------------------
  //------------------------飞书小程序开发---------------------------------------------------------------
  //获取登录用户身份 session_key 和 openId
  async tokenLoginValidate(obj){
    var resData = {};
    if(obj.open_id){
      //缓存中获取登录用户身份
      resData = await this.cacheManager["feishuUserAccessTokenCache"].get(obj.open_id);
    }
    //缓存中存在 直接返回
    if(resData && resData.access_token){
      return system.getResultSuccess(resData);
    }
    if(!obj.code){
      return system.getResultFail("code参数不能为空");
    }
    if(!obj.app_access_token){
      return system.getResultFail("app_access_token参数不能为空");
    }
    var url = "https://open.feishu.cn/open-apis/mina/v2/tokenLoginValidate";
    var fsObj={
      token:obj.app_access_token,//应用的 app_access_token，必须与请求身份验证中的应用保持一致
      code:obj.code //来自请求身份验证(新)流程，用户扫码登录后会自动302到redirect_uri并带上此参数
    };
    var rtn = await this.execClient.execFeishuPost(fsObj, url);
    if (!rtn || !rtn.stdout) {
      return system.getResult(null, "execPost data is empty");
    }
    var result = JSON.parse(rtn.stdout);
    if(result.code==0 && result.data){
      //缓存AppAccessToken
      await this.cacheManager["feishuUserAccessTokenCache"].set(result.data,result.data.open_id);
      return system.getResultSuccess(result.data);
    }
    return system.getResult(null, "获取飞书登录用户身份失败");
  }
  //------------------------飞书小程序开发------结束---------------------------------------------------------

  getUUID() {
    var uuid = uuidv4();
    var u = uuid.replace(/\-/g, "");
    return u;
  }
  //用户登录/获取userpin
  async checkAndLogin(pobj){
    // return system.getResultSuccess(null,"测试");
    try {
      if(!pobj.code){
        return system.getResultFail(-100, "code参数不能为空");
      }
      
      //获取 app_access_token（应用商店应用）
      var appAccessTokenRes = await this.getAppAccessToken();
      if(appAccessTokenRes.status!=0){
        return appAccessTokenRes;
      }
      var app_access_token = appAccessTokenRes.data;
  
      //获取飞书登录用户身份
      var userAccessTokenParams = {
        "code":pobj.code,"app_access_token":app_access_token,"open_id":pobj.open_id || ""
      };
      // var userAccessTokenRes = await this.getUserAccessToken(userAccessTokenParams);
      var userAccessTokenRes = await this.tokenLoginValidate(userAccessTokenParams);
      if(userAccessTokenRes.status!=0){
        return userAccessTokenRes;
      }
      var userAccessTokenObj = userAccessTokenRes.data;
      
      //获取飞书用户信息
      var userInfoParams={
        user_access_token:userAccessTokenObj.access_token
      };
      var userInfoRes = await this.getUserInfo(userInfoParams);
      if(userInfoRes.status!=0){
        return userInfoRes;
      }
      var userInfoObj = userInfoRes.data;

      //帐号登录---若用户信息已存在 则返回userpin 不存在则返回空
      var loginByUserNameParams={
            "appInfo":pobj.appInfo,
            "actionType": "getLoginByUserName",
            "actionBody":    {
              "openId":userAccessTokenObj.open_id,
              "channelUserId":userAccessTokenObj.open_id,// Y 渠道用户ID
              "channelUserName":userInfoObj.name,// N 渠道用户名
              "nickName":userInfoObj.name, // N 用户昵称
              "head_url":userInfoObj.avatar_url //头像

            }
      };
      var loginByUserNameRes = await this.getLoginByUserName(loginByUserNameParams);
      if(loginByUserNameRes && loginByUserNameRes.status==0){
        loginByUserNameRes.data.open_id = userAccessTokenObj.open_id;
        // loginByUserNameRes.data.session_key = userAccessTokenObj.session_key;
        return loginByUserNameRes;//获取userpin直接返回
      }
      // // 获取飞书用户信息
      // var userInfoParams={
      //   user_access_token:userAccessTokenObj.access_token
      // };
      // var userInfoRes = await this.utilsFeishuSve.getUserInfo(userInfoParams);
      // if(userInfoRes.status!=0){
      //   return userInfoRes;
      // }
      // var userInfoObj = userInfoRes.data;
      
    } catch (e) {
      return system.getResultFail(-200,e.stack);  
    }
    return system.getResultFail(-100,"获取userpin失败");
  }

  //渠道通过账户进行登录，有则返回用户信息，没有则创建用户------>供后端调用
  async getLoginByUserName(pobj){
    pobj.actionBody.userpin = this.getUUID();
    var tmpOpResult = await this.utilsAuthSve.getLoginByUserName(pobj, pobj.actionBody);
    if (tmpOpResult.status != 0 && tmpOpResult.status != 2060) {
        return tmpOpResult;
    }
    var opResult = system.getResultSuccess({ userpin: pobj.actionBody.userpin });
    if (tmpOpResult.status == 2060) {
        opResult.msg = tmpOpResult.msg;
        opResult.data.userpin = tmpOpResult.data.userpin;
    }
    return opResult;
  }
}
module.exports = UtilsFeishuService;
// var task = new UtilsFeishuService();
// var pobj = {
//   "appInfo":{
//       "id":17,
//       "app_hosts":"gsbweb.qifu.gongsibao.com",
//       "app_code":"gsbweb",
//       "app_name":"公司宝官网web应用",
//       "uapp_id":"22",
//       "uapp_key":"201912141625",
//       "uapp_secret":"8cbb846776874167b5c7e01cd0116c66",
//       "contact_name":"宋毅",
//       "contact_mobile":"15010929366",
//       "contact_email":null,
//       "is_enabled":1,
//       "is_sign":0,
//       "pay_type":"10",
//       "delivery_type":"10",
//       "created_at":"2020-03-11T22:13:48.000Z",
//       "version":0,
//       "token":"4ea34fccd85b442da189d0086849c0e2"
//   },
//   "actionType": "getLoginByUserName",
//   "actionBody":    {
//     "openId":"ou_ed97ab357af62082e54c972051888229",
//     "channelUserId":"ou_ed97ab357af62082e54c972051888229",
//     "channelUserName":"庄冰",
//     "nickName":"庄冰"
//   }
// };
// task.getLoginByUserName(pobj).then(res=>{
//   console.log(res,"ddddddddddddddddddddddddddddddd");
// })

