const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
class UserCache extends CacheBase {
  constructor() {
    super();
    this.userDao = system.getObject("db.auth.userDao");
    this.channelDao = system.getObject("db.common.channelDao");
  }
  isdebug () {
    return settings.env == "dev";
  }
  desc () {
    return "缓存本地应用对象";
  }
  prefix () {
    return "g_userlocal_cm:"
  }
  async buildCacheVal (cachekey, inputkey, val, ex, ...items) {
    const configValue = await this.userDao.model.findAll({
      where: { userName: inputkey, app_id: settings.pmappid, isEnabled: true },
      attributes: ['id', 'userName', 'nickName', 'headUrl', 'jwtkey', 'jwtsecret', 'created_at', 'isSuper', 'isAdmin', 'isAllocated', 'mail', 'mobile', 'opath', 'ptags'],
      include: [
        { model: this.db.models.company, attributes: ['id', 'name', 'companykey', 'appids', "code"], raw: true },
        { model: this.db.models.role, as: "Roles", attributes: ["id", "code"], }
      ],
    });

    if (configValue && configValue[0]) {
      let data = JSON.parse(JSON.stringify(configValue[0]));
      if (data.company.id != 1 && data.company.appids) {
        let tmpids = data.company.appids.split(",")
        let tmpid = tmpids[0]
        if (tmpid && tmpid != "" && tmpids.length == 1) {
          let app = await this.db.models.app.findById(tmpid)
          data.defaultAppkey = app.appkey
        }
      }
      let channelDatas = await this.channelDao.findAll({});
      channelDatas = JSON.parse(JSON.stringify(channelDatas));
      channelDatas.forEach(item => {
        if (item.userids && item.userids.split(",").includes(data.id.toString())) {
          data.channel = {
            id: item.id,
            code: item.code,
            name: item.name
          }
        }
      });
      // 获取渠道信息
      return JSON.stringify(data);
    }
    return null;
  }
}
module.exports = UserCache;