const CacheBase=require("../cache.base");
const system=require("../../system");
//缓存首次登录的赠送的宝币数量
class ApiCallCountCache extends CacheBase{
   constructor(){
     super();
     this.apitradeDao=system.getObject("db.common.apitradeDao");
   }
   desc(){
     return "API调用次数";
  }
  prefix(){
    return "api_call:";
  }
   async addCallCount(apikey,callpath,n){
     var key=this.prefix+apikey+"_"+callpath;
     var result=await this.redisClient.hincrby(key,"callcount",n);
     return result;
   }
   async addCallBalance(apikey,callpath,n){
     var key=this.prefix+apikey+"_"+callpath;
     var result=await this.redisClient.hincrby(key,"amount",n);
     return result;
   }
   async getApiCallCount(apikey,callpath){
     var key=this.prefix+apikey+"_"+callpath;
     const cachedVal= await this.redisClient.hgetall(key);
     if(!cachedVal || cachedVal=="undefined"){
        var count= await this.apitradeDao.model.count({
           where:{
            srcappkey:apikey,
             op:callpath,
             tradeType:"consume",
           }
         });
        var amount=await this.apitradeDao.model.sum("amount",{
           where:{
            srcappkey:apikey,
             op:callpath,
             tradeType:"consume",
           }
        });
        var map={"callcount":count?count:0,"amount":amount?amount:0};
        this.redisClient.hmset(key,map);
        //缓存当前应用所有的缓存key及其描述
        this.redisClient.sadd(this.cacheCacheKeyPrefix, [key + "|" + this.desc]);
        return map;
     }else{
        return cachedVal;
     }

   }
}
module.exports=ApiCallCountCache;
