const CacheBase = require("../cache.base");
const system = require("../../system");
//缓存首次登录的赠送的宝币数量
class LoopbackCache extends CacheBase {
  constructor() {
    super();
    this.prefix = "loopbackpic:";
    this.loopbackDao = system.getObject("db.loopplayDao");
    this.companyDao = system.getObject("db.companyDao");
    this.sitethemeDao = system.getObject("db.sitethemeDao");
  }
  /**
   * 获取轮播图列表
   * @param {*} hostname 域名
   * @param {*} themeName 主题编码
   * @param {*} loopType 轮播类型，PC、YD
   */
  async cacheLoopback(hostname, themeName, loopType) {
    var sLoopType = loopType || "PC";
    const key = this.prefix + hostname + sLoopType + themeName;
    var configValue = await this.redisClient.get(key);
    if (!configValue || configValue == "undefined") {
      console.log("uiconfig no cache....");
      var company = await this.companyDao.getCompanyInfoByHostname(hostname);
      if (company) {
        var loopWhere = {
          where: { company_id: company.id, loopplayType: sLoopType },
          attributes: ["id", "code", "title", "leftimg", "orderNo", "skipUrl", "loopplayType"]
          , raw: true
        };
        if (sLoopType == "PC") {
          var themeItem = null;
          var themeid;
          //如果themeName不为空，那么就按照themeName查询出theme
          if (themeName) {
            themeItem = await this.sitethemeDao.model.findOne({ where: { isEnabled: 1, siteTheme: themeName } });
            themeid = themeItem.id;
          } else {
            themeid = company.sitetheme_id;
          }
          loopWhere.where["sitetheme_id"] = themeid;
        }
        //按照themeid,去查询出当前的轮播图
        var lbs = await this.loopbackDao.model.findAll(loopWhere);
        if (!lbs) {
          loopWhere.where.company_id = 1;
          if (sLoopType == "PC") {
            loopWhere.where.sitetheme_id = 1;
          }
          lbs = await this.loopbackDao.model.findAll(loopWhere);
        }
        configValue = lbs;
        if (lbs.length > 0) {
          await this.redisClient.setWithEx(key, JSON.stringify(lbs), 120);
        }
      } else {
        configValue = "";
      }
      return configValue;
    } else {
      configValue = JSON.parse(configValue);
      console.log("uiconfig already cache....");
    }
    return configValue;
  }
}
module.exports = LoopbackCache;
