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));
  }
  async update (p, q, req) {
    let u = await super.update(p, q, req)
    //缓存失效
    await this.cacheManager["CompanyCache"].invalidate(p.companykey)
    let company = await this.cacheManager["CompanyCache"].cache(p.companykey)
    return system.getResult(company)
  }

  async getMyApps (p, q, req) {
    let userfind = await this.cacheManager["UserCache"].cache(p.username)
    let isSuper = userfind.isSuper
    if (userfind.company.appids && userfind.company.appids != "") {
      let appsarray = userfind.company.appids.split(",")
      let appidsquery = appsarray.map(astr => {
        return astr.split("|")[0]
      })
      let apps = await this.service.getMyApps(appidsquery, isSuper)
      return system.getResult(apps)
    } else {
      return []
    }
  }
  async bindApps (p, q, req) {
    let appids = p.appids
    let cmpid = p.postcmpid
    let appids2 = appids.map(item => {
      return item.appid + "|" + item.title
    })
    let appidstrs = appids2.join(",")
    await this.service.bindApps(appidstrs, cmpid)
    return system.getResult(appids)
  }
  async setOrgs (p, q, req) {
    //let companynew=await this.service.findById(p.company_id)
    let orgs = await this.service.setOrgs(p)
    return system.getResult(orgs)
  }
  async getOrgs (p, q, req) {
    //let companynew=await this.cacheManager["CompanyCache"].cache(req.xctx.fromcompanykey)
    let companynew = await this.service.findById(p.company_id)
    let orgjsonstr = companynew.orgJson
    let rtnjson = null
    if (orgjsonstr && orgjsonstr != "") {
      rtnjson = JSON.parse(companynew.orgJson)
    } else {
      rtnjson = []
    }
    return system.getResult({ orgJson: rtnjson })
  }
  async getWatchOrgNodes (p, q, req) {
    let wns = await this.service.getWatchOrgNodes(p.company_id)
    return wns
  }

  async refQuery (pobj, qobj, req) {
    let rtn = await this.service.refQuery(pobj);
    return rtn
  }

}
module.exports = CompanyCtl;
