const CacheBase=require("../cache.base");
const system=require("../../system");
//缓存首次登录的赠送的宝币数量
class ApiAccuCache extends CacheBase{
   constructor(){
     super();
     this.apitradeDao=system.getObject("db.apitradeDao");
     this.prefix="api_accu_";
     this.desc="API累计调用次数和累计余额";
   }
   async addCallCount(apikey,n){
     var key=this.prefix+apikey;
     var result=await this.redisClient.hincrby(key,"callcount",n);
     return result;
   }
   async addCallBalance(apikey,n){
     var key=this.prefix+apikey;
     var result=await this.redisClient.hincrby(key,"amount",n);
     return result;
   }
   async getApiCallAccu(apikey){
     var key=this.prefix+apikey;
     const cachedVal= await this.redisClient.hgetall(key);
     if(!cachedVal || cachedVal=="undefined"){
        var count= await this.apitradeDao.model.count({
           where:{
             app_id:apikey,
             tradeType:"consume",
           }
         });
        var amount=await this.apitradeDao.model.sum("amount",{
           where:{
             app_id:apikey,
           }
        });
        var map={"callcount":count?count:0,"amount":amount?amount:0};
        this.redisClient.hmset(key,map);
        return map;
     }else{
        return cachedVal;
     }
   }
}
module.exports=ApiAccuCache;
