const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");
class CompanyService extends ServiceBase {
  constructor() {
    super("common", ServiceBase.getDaoName(CompanyService));
  }
  async setOrgs(p,cmk) {
    var self=this
    return this.db.transaction(async function (t) {
      let strjson = JSON.stringify(p.orgJson)
      p.id = p.company_id
      p.orgJson = strjson
      //更新组织机构
      let u = await self.dao.update(p,t)
      //更新，还得传输当前节点,查询出当前节点的角色
      //按照当前节点的opath查询出所有的用户，更新这些用户的角色信息
      let curNodeData=p.curdata
      if(curNodeData && curNodeData.isPosition){
        let opathstr=curNodeData.orgpath
        let us=await self.db.models.user.findAll({where:{opath:opathstr},transaction:t})
        //查询出角色
        let roleids=curNodeData.roles
        let rs=await self.db.models.role.findAll({where:{id:{[self.db.Op.in]:roleids},app_id:p.app_id,company_id:p.company_id},transaction:t})
        for(let u of us){
          await u.setRoles(rs,{transaction:t})
        }
        // users.forEach((u)=>{
        //   await u.setRoles(rs, { transaction: t });
        // })
      }
      //用户缓存也要失效
      //缓存失效
      await self.cacheManager["CompanyCache"].invalidate(cmk)
      let companytmp=await self.dao.model.findOne({where:{companykey:cmk},transaction:t});
      return {orgJson:JSON.parse(companytmp.orgJson)}
    })
  }
}
module.exports = CompanyService;
