var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");

class CompanyCtl extends CtlBase {
  constructor() {
    super("common", CtlBase.getServiceName(CompanyCtl));
    this.userS=system.getObject("service.auth.userSve");
  }

  async initNewInstance(pobj, queryobj, req) {
    var rtn = {};
    return system.getResult(rtn);
  }
  //to do租户在创建公司的时候，需要同时维护平台下面，用户所属租户是当前租户的公司
  //当删除公司时，需要同时删除公司关联的APP，还有用户关联的公司
  async create(p,q,req){
     var user=await this.userS.findOne({id:p.userid});
     var uuidstr=this.getUUID();
     p.companykey=uuidstr;
     var company=await this.service.create(p,user);
     req.session.tocompany=company;
     return system.getResult(company);
  }
  async update(p,q,req){
    //修改重新刷新页面，初始化页面的公司信息
    var rtn=await super.update(p,q,req);
    req.session.company=p;
    return system.getResult(rtn);
  }
  async buyApp(p,q,req){
     var cmpid=req.session.tocompany.id;
     var user=req.session.user;
     var cmpfind=await this.service.buyApp(p,cmpid,user);
     req.session.tocompany=cmpfind;
     return system.getResult(cmpfind.apps);
  }
  async giveupApp(p,q,req){
    var comid=p.compid;
    var appid=p.appid;
    var rtn=await this.service.giveupApp(comid,appid);
    return system.getResult(rtn);
  }
  //设置当前用户选择的公司为当前公司
  async settocompany(p,q,req){
     p.isCurrent=true;
     req.session.tocompany=p;
     var cmp= await this.service.settocompany(p);
     return system.getResult(cmp);
  }
  async findAndCountAll(p,q,req){
     var comps=await this.service.findAndCountAll(p,q,req);
     var rtns=[];
     for(var cmp of comps){
       if(cmp.id!=settings.platformcompanyid){
        var rtntmp={
          id:cmp.id,
          name:cmp.name,
          companykey:cmp.companykey,
          description:cmp.description,
          logoUrl:cmp.logoUrl,
          isCurrent:cmp.usercompany.isCurrent,
          apps:cmp.apps?cmp.apps:[]
        }
        rtns.push(rtntmp);
       }
     }
     var rtn = {};
     rtn.results = {count:rtns.length,rows:rtns};
     rtn.aggresult = {};
     return system.getResult(rtn);
  }
}
module.exports = CompanyCtl;
