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 getMyApps(appids,isSuper){
    let appsrtn=null
      if(isSuper){
           appsrtn=this.db.models.app.findAll({where:
            {
              id:{[this.db.Op.ne]:settings.pmappid}
            }
          })
      }else{
        appsrtn=this.db.models.app.findAll({where:
          {
            id:{[this.db.Op.in]:appids}
          }
        })
      }
      return appsrtn
  }
  async bindApps(appids,companyid){
    var self=this
    return this.db.transaction(async function (t) {
      let u = await self.dao.update({appids:appids,id:companyid},t)
      return appids
    })
  }
  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:{[self.db.Op.like]:`%${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})
       //需要添加访客角色

       if (roleids && roleids.length > 0) {
        if (roleids.indexOf(settings.pmroleid["pr"]) < 0) {
          roleids.push(settings.pmroleid["pr"])
        }
      }
       let rs=await self.db.models.role.findAll({where:{id:{[self.db.Op.in]:roleids}},transaction:t})
        for(let u of us){
          await u.setRoles(rs,{transaction:t})
          //令用户缓存失效
          await self.cacheManager["UserCache"].invalidate(u.userName) 
        }
      }
      let companytmp=await self.dao.model.findOne({where:{id:p.company_id},transaction:t});
      return {orgJson:JSON.parse(companytmp.orgJson)}
    })
  }
}
module.exports = CompanyService;
