const CacheBase=require("../cache.base");
const system=require("../../system");
const wxFunc=require("../../service/wxsvr");
const OpenplatformWxop =  require("../../wxop/impl/openplatformWxop");
/**
 * 微信开放平台 公众号或小程序的接口调用凭据(授权方令牌)缓存（2小时后失效）
 */
class WxauthorizeraccesstokenCache extends CacheBase{
   constructor(){
     super();
     this.prefix="wx_authorizer_access_token_";
     this.restClient=system.getObject("util.restClient");
   }
   async get(appid){//公众号或小程序的appid
      var key = this.prefix+appid;
      var result = await this.redisClient.get(key);
      var obj = null;
      var time = Date.parse(new Date())/1000;
      if(result){
         obj=JSON.parse(result);
         if(!obj.time){
            obj = null;
         }
      }
      if(!obj || obj.time<=time){//无缓存 或 缓存令牌失效
         var openplatform = new OpenplatformWxop();
         var newobj = await openplatform.api_authorizer_token({authorizer_appid:appid});
         if(newobj && newobj.expires_in){
            if(newobj.expires_in>500){
               newobj["time"]= time+newobj.expires_in-500;
            }else{
               newobj["time"]= time+newobj.expires_in;
            }
            var newobjstring=JSON.stringify(newobj);
            await this.redisClient.set(key,newobjstring);
            return newobj;
         }else{
            return null;
         }
      }else{//有缓存 且 未失效
         return obj;
      }
      
      
   }
   async set(appid,result){
      var key = this.prefix+appid;
      var time = Date.parse(new Date())/1000;
      if(result.expires_in>500){
         result["time"]= time+result.expires_in-500;
      }else{
         result["time"]= time+result.expires_in;
      }
      var resultstring=JSON.stringify(result);
      await this.redisClient.set(key,resultstring);
      return result;
   }
   async del(appid){
      var key = this.prefix+appid;
      await this.redisClient.delete(key);
   }
}
module.exports=WxauthorizeraccesstokenCache;
