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) {
    const self = this;
    return this.db.transaction(async (t) => {
      const strjson = JSON.stringify(p.orgJson);
      p.id = p.company_id;
      p.orgJson = strjson;
      // 更新组织机构
      const u = await self.dao.update(p, t);
      // 更新，还得传输当前节点,查询出当前节点的角色
      // 按照当前节点的opath查询出所有的用户，更新这些用户的角色信息
      const curNodeData = p.curdata;
      if (curNodeData && curNodeData.isPosition) {
        const opathstr = curNodeData.orgpath;
        const us = await self.db.models.user.findAll({ where: { opath: opathstr }, transaction: t });
        // 查询出角色
        const roleids = curNodeData.roles;
        const 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 (const u of us) {
          await u.setRoles(rs, { transaction: t });
        }
        // users.forEach((u)=>{
        //   await u.setRoles(rs, { transaction: t });
        // })
      }
      // 用户缓存也要失效
      // 缓存失效
      await self.cacheManager.CompanyCache.invalidate(cmk);
      const companytmp = await self.dao.model.findOne({ where: { companykey: cmk }, transaction: t });
      return { orgJson: JSON.parse(companytmp.orgJson) };
    });
  }
}
module.exports = CompanyService;
