const system = require("../system")
const settings = require("../../config/settings.js");
class CacheBase {
  constructor() {
    this.redisClient = system.getObject("util.redisClient");
    this.desc = this.desc();
    this.prefix = this.prefix();
    this.cacheCacheKeyPrefix = "s_sadd_appkeys:" + settings.appKey + "_cachekey";
    this.isdebug = this.isdebug();
  }
  isdebug() {
    return false;
  }
  desc() {
    throw new Error("子类需要定义desc方法，返回缓存描述");
  }
  prefix() {
    throw new Error("子类需要定义prefix方法，返回本缓存的前缀");
  }
  async cache(inputkey, val, ex, ...items) {
    const cachekey = this.prefix + inputkey;
    var cacheValue = await this.redisClient.get(cachekey);
    if (!cacheValue || cacheValue == "undefined" || cacheValue == "null" || this.isdebug) {
      var objval = await this.buildCacheVal(cachekey, inputkey, val, ex, ...items);
      if (!objval || (objval.status && objval.status != 0)) {
        return objval;
      }
      if (ex) {
        await this.redisClient.setWithEx(cachekey, JSON.stringify(objval), ex);
      } else {
        await this.redisClient.set(cachekey, JSON.stringify(objval));
      }
      //缓存当前应用所有的缓存key及其描述
      this.redisClient.sadd(this.cacheCacheKeyPrefix, [cachekey + "|" + this.desc]);
      return objval;
    } else {
      this.redisClient.set(cachekey, cacheValue, ex);
      return JSON.parse(cacheValue);
    }
  }
  async getCache(inputkey, ex) {
    const cachekey = this.prefix + inputkey;
    var cacheValue = await this.redisClient.get(cachekey);
    if (!cacheValue || cacheValue == "undefined" || cacheValue == "null") {
      return system.getResultFail(system.cacheInvalidation, "cache is invalidation")
    } else {
      if (ex) {
        this.redisClient.set(cachekey, cacheValue, ex);
      }
      return JSON.parse(cacheValue);
    }
  }
  async invalidate(inputkey) {
    const cachekey = this.prefix + inputkey;
    this.redisClient.delete(cachekey);
    return 0;
  }
  async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
    throw new Error("子类中实现构建缓存值的方法，返回字符串");
  }
}
module.exports = CacheBase;
