const system = require("../../../system");
const Dao = require("../../dao.base");
class AppDao extends Dao {
  constructor() {
    super(Dao.getModelName(AppDao));
  }
  async findOneById(id, t) {
    var sqlWhere = {
      where: { id: id },
      attributes: ["id", "appkey", "secret", "domainName"], raw: true
    };
    if (t) {
      sqlWhere.transaction = t;
    }
    var app = await this.model.findOne(sqlWhere);
    return app;
  }
  async findOne(appKey, secret, t) {
    var tmpAttributes = [`id`,
      `appkey`,
      `name`,
      `domainName`,
      `homePage`,
      `docUrl`,
      `authUrl`,
      `logoUrl`,
      `bkimageUrl`,
      `showimgUrl`,
      `detailimgUrl`,
      `description`,
      `isEnabled`,
      `isPublish`,
      `isCommon`,
      `appType`,
      `uiconfigUrl`,
      `opCacheUrl`,
      `notifyCacheCountUrl`];
    if (t) {
      var app = await this.model.findOne({ where: { appkey: appKey, secret: secret }, attributes: tmpAttributes, raw: true }, { transaction: t });
      return app;
    } else {
      var app = await this.model.findOne({ where: { appkey: appKey, secret: secret }, attributes: tmpAttributes, raw: true });
      return app;
    }

  }
  async findOne2(appKey, t) {
    var tmpAttributes = [`id`,
      `appkey`,
      `name`,
      `domainName`,
      `homePage`,
      `docUrl`,
      `authUrl`,
      `logoUrl`,
      `bkimageUrl`,
      `showimgUrl`,
      `detailimgUrl`,
      `description`,
      `isEnabled`,
      `isPublish`,
      `isCommon`,
      `isSaas`,
      `appType`,
      `uiconfigUrl`,
      `opCacheUrl`,
      `notifyCacheCountUrl`];
    if (t) {
      var app = await this.model.findOne({ where: { appkey: appKey }, attributes: tmpAttributes, raw: true }, { transaction: t });
      return app;
    } else {
      var app = await this.model.findOne({ where: { appkey: appKey }, attributes: tmpAttributes, raw: true });
      return app;
    }

  }
  async findAndCountAll(qobj, t) {
    if(qobj.codepath.indexOf("comapps")>=0){
      var rtn={};
      var comp=await this.db.models.company.findOne({where:{companykey:qobj.search.companykey}});
      var apps=await comp.getApps();
      rtn.results={rows:apps,count:apps.length};
      rtn.aggresult={};
      return rtn;
    }else{
      return super.findAndCountAll(qobj, t);
    }
  }
  extraWhere(obj, w, qc, linkAttrs) {
    if (obj.codepath && obj.codepath != "") {
      if (obj.codepath.indexOf("pmgmyapps") > 0) {//说明是应用管理员的查询
        w["creator_id"] = obj.userid;
      }
    }
    if (linkAttrs.length > 0) {
      var search = obj.search;
      var lnkKey = linkAttrs[0];
      var strq = "$" + lnkKey.replace("~", ".") + "$";
      w[strq] = { [this.db.Op.like]: "%" + search[lnkKey] + "%" };

    }
    return w;
  }

}
module.exports = AppDao;
