const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");
const uiconfig = system.getUiConfig2(settings.appKey);
class AppService extends ServiceBase {
  constructor() {
    super("common", ServiceBase.getDaoName(AppService));
    //this.appDao=system.getObject("db.appDao");
    this.userS = system.getObject("service.auth.userSve");
    this.tradeD = system.getObject("db.common.apitradeDao");
  }
  async getApp(appkey) {
    return this.cacheManager["AppCache"].cache(appkey, null);
  }
  async findAllApps(uid) {
    var apps=null;
    var dicRtn = {};
    var wheresql= {};
    if(uid){
      wheresql[this.db.Op.and]={
        [this.db.Op.or]:
          [
            {isPublish:false, creator_id: uid},
            {isEnabled: true,isPublish:true}
          ],
      };
      apps = await this.dao.model.findAll({ 
        where: wheresql, 
        attributes: ['id', 'name', 'appkey', 'showimgUrl', 'appType', 'docUrl','homePage'] });
    }else{
          wheresql= {isEnabled: true,isPublish:true};
          apps = await this.dao.model.findAll({ 
                  where: wheresql, 
                  attributes: ['id', 'name', 'appkey', 'showimgUrl', 'appType', 'docUrl','homePage'] });
    }
    for (var app of apps) {
      var tmk = uiconfig.config.pdict.app_type[app.appType];
      if (!dicRtn[tmk]) {
        dicRtn[tmk] = [];
        dicRtn[tmk].push(app);
      } else {
        dicRtn[tmk].push(app);
      }
    }
    return dicRtn;
  }
  async resetPass(pobj) {
    var appid = pobj.appid;
    var uobj = { password: pobj.password }
    return await this.userS.dao.model.update(uobj, { where: { userName: pobj.userName, app_id: pobj.appid } });
  }
  async createAdminUser(pobj) {
    var u = { userName: pobj.userName, password: pobj.password, app_id: pobj.appid, isAdmin: true, mobile: pobj.mobile };
    var rtn = await this.userS.register(u);
    return rtn;
  }
  async create(pobj, qobj, req) {
    var self = this;
    return this.db.transaction(async function (t) {
      var app = await self.dao.create(pobj, t);
      //创建role
      const Role = self.db.models.role;
      //to do 由于有了租户的概念，所以目前不能创建属于特定租户的角色，进入后台后应该可以获取当前租户信息
      // await Role.create(
      //   { name: "普通", code: "common", isSystem: 1, app_id: app.id }, { transaction: t }
      // );
      return app;
    });
  }
  async findAndCountAll(obj) {
    var self = this;
    const apps = await super.findAndCountAll(obj);
    for (let i = 0; i < apps.results.rows.length; i++) {
      var a = apps.results.rows[i];
      var appkey = a.appkey;
      var apicallAccu = await this.cacheManager["ApiAccuCache"].getApiCallAccu(appkey);
      a.apiCallCount = apicallAccu.callcount;
      a.amount = apicallAccu.amount;
    }
    return apps;
  }
  async recvNotificationForCacheCount(pobj) {
    console.log(pobj);
    return;
  }
  async fetchApiCallData(curappkey) {
    //当前APP,呼出发生的调用次数和累积应付
    //var apicallAccu= await this.cacheManager["ApiAccuCache"].getApiCallAccu(curappkey);

    //当前APP,呼出发生的调用次数和累积应付
    var apicallAccuCount = await this.tradeD.model.count({
      where: {
        srcappkey: curappkey,
        tradeType: "consume",
      }
    });
    var apicallAccuAmount = await this.tradeD.model.sum("amount", {
      where: {
        srcappkey: curappkey,
        tradeType: "consume",
      }
    });

    //当前APP对外提供服务，累积发生的调用次数及累积应收
    var count = await this.tradeD.model.count({
      where: {
        destappkey: curappkey,
        tradeType: "consume",
      }
    });
    var amount = await this.tradeD.model.sum("amount", {
      where: {
        destappkey: curappkey,
      }
    });
    var rtn = {
      apioutcallcount: apicallAccuCount,
      apioutcallamount: apicallAccuAmount,
      apiincallcount: count,
      apiincallamount: amount,
    }
    return rtn;
  }
}
module.exports = AppService;
