const CacheBase=require("../cache.base");
const system=require("../../system");
var settings=require("../../../config/settings");
const WxopBase = require("../../wxop/wxop.base");
const OpenplatformWxop =  require("../../wxop/impl/openplatformWxop");
/**
 * 第三方平台component_access_token
 * 第三方平台component_access_token是第三方平台的下文中接口的调用凭据，也叫做令牌（component_access_token）。
 * 每个令牌是存在有效const WxopBase = require("../wxop.base");小时）的，且令牌的调用不是无限制的，请第三方平台做好令牌的管理，在令牌快过期时（比如1小时50分）再进行刷新。
 */
class WxcomponentaccesstokenCache extends CacheBase{
   constructor(){
     super();
     this.prefix="wx_component_access_token_";
     this.appDao=system.getObject("db.appDao");
   //   this.OpenplatformWxop=system.getObject("wxop.openplatformWxop");
     this.wxopenplatformconfig = settings.wxopenplatformconfig;
   }
   async get(){
      var key = this.prefix+this.wxopenplatformconfig.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_component_token();
         console.log(newobj);
         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(result){
      var key = this.prefix+this.wxopenplatformconfig.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+this.wxopenplatformconfig.appid;
      await this.redisClient.delete(key);
   }
}
module.exports=WxcomponentaccesstokenCache;

