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 = await this.db.models.app.findAll({
        where:
        {
          id: { [this.db.Op.ne]: settings.pmappid }
        }
      })
    } else {
      appsrtn = await 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
    })
  }
  buildNoPositionNode (treejson, rtnArray) {
    treejson.forEach((n) => {
      if (n.children) {
        this.buildNoPositionNode(n.children, rtnArray)
      }
      if (typeof n.isPosition == "undefined") {
        rtnArray.push(n)
      } else {
        if (!n.isPosition) {
          rtnArray.push(n)
        }
      }

    })
  }
  async getWatchOrgNodes (cmid) {
    let rtn = []
    let companynew = await this.findById(cmid)
    let orgjsonstr = companynew.orgJson
    if (orgjsonstr && orgjsonstr != "") {
      let treejson = JSON.parse(companynew.orgJson)
      this.buildNoPositionNode(treejson, rtn)
    }
    return rtn
  }

  async setOrgs (p, cmk) {
    var self = this
    let curNodeData = p.curdata
    let opathstr = curNodeData.orgpath
    let oldNodeData = p.olddata//老的节点数据
    let strjson = JSON.stringify(p.orgJson)
    p.id = p.company_id
    p.orgJson = strjson
    let oldopath = ''
    if (!oldNodeData) {//如果不传老对象，表示当前操作是删除节点操作,检查是否存在用户，如果已经存在
      //那么就提示不能删除
      let us = await self.db.models.user.findOne({ where: { opath: { [self.db.Op.like]: `%${opathstr}%` } } })
      if (us) {
        let companytmp = await this.dao.model.findOne({ where: { id: p.company_id } });
        return { orgJson: JSON.parse(companytmp.orgJson) }
      } else {
        let u = await this.dao.update(p)
        let companytmp = await this.dao.model.findOne({ where: { id: p.company_id } });
        return { orgJson: JSON.parse(companytmp.orgJson) }
      }
    } else {
      oldopath = oldNodeData.orgpath == '' ? '123456' : oldNodeData.orgpath
    }
    return this.db.transaction(async function (t) {

      //更新组织机构
      let u = await self.dao.update(p, t)
      //更新，还得传输当前节点,查询出当前节点的角色
      //按照当前节点的opath查询出所有的用户，更新这些用户的角色信息

      if (curNodeData) {
        if (curNodeData.isPosition) {
          let us = await self.db.models.user.findAll({ where: { opath: { [self.db.Op.like]: `%${oldopath}%` } }, 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 })
            //if (opathstr != oldopath) {
            u.opath = opathstr + "/" + u.userName
            u.ptags = curNodeData.ptags
            u.save({ transaction: t })
            // }
            //令用户缓存失效
            await self.cacheManager["UserCache"].invalidate(u.userName)
          }
        } else {//不是岗位节点,检查修改后的路径是否和原始一致，如果不一致，那么需要查出原始的用户数据
          //把原来的路径替换当前新的code
          if (opathstr != oldopath) {
            let us2 = await self.db.models.user.findAll({ where: { opath: { [self.db.Op.like]: `%${oldopath}%` } }, transaction: t })
            for (let u of us2) {
              let curpath = u.opath
              let newpath = curpath.replace(oldNodeData.code, curNodeData.code)
              u.opath = newpath
              u.save({ 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;
