const CacheBase=require("../cache.base");
const system=require("../../system");
//缓存首次登录的赠送的宝币数量
class ApiCallCountCache extends CacheBase{
   constructor(){
     super();
     this.apitradeDao=system.getObject("db.apitradeDao");
     this.prefix="api_call_";
     this.desc="API调用次数";
   }
   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:{
             app_id:apikey,
             op:callpath,
             tradeType:"consume",
           }
         });
        var amount=await this.apitradeDao.model.sum("amount",{
           where:{
             app_id:apikey,
             op:callpath,
             tradeType:"consume",
           }
        });
        var map={"callcount":count?count:0,"amount":amount?amount:0};
        this.redisClient.hmset(key,map);
        return map;
     }else{
        return cachedVal;
     }

   }
}
module.exports=ApiCallCountCache;
