const CacheBase=require("../cache.base");
const system=require("../../system");
//缓存首次登录的赠送的宝币数量
class ApiAccuCache extends CacheBase{
   constructor(){
     super();
     this.apitradeDao=system.getObject("db.callcount.apitradeDao");
   }
   desc(){
     return "API累计调用次数和累计余额";
  }
  prefix(){
    return "api_accu:";
  }
   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(srckey){
     var apikey=srckey.split("_")[0];
     var key=this.prefix+srckey;
     const cachedVal= await this.redisClient.hgetall(key);
     if(!cachedVal || cachedVal=="undefined"){
        var count= await this.apitradeDao.model.count({
           where:{
            srcappkey:apikey,
             tradeType:"consume",
           }
         });
        var amount=await this.apitradeDao.model.sum("amount",{
           where:{
            srcappkey:apikey,
           }
        });
        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=ApiAccuCache;
