package com.sptg.gateway.controller.permissions;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.sptg.common.core.beans.PageBean;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.common.core.constant.SysLogConstant;
import com.sptg.common.core.util.TreeUtil;import com.sptg.common.core.util.WebUtils;
import com.sptg.common.security.annotation.Security;
import com.sptg.common.security.enums.DataFormatEnum;
import com.sptg.common.security.service.SecurityServiceInterface;
import com.sptg.estate.api.dto.ResidentialDto;
import com.sptg.estate.api.dto.RoomDto;
import com.sptg.estate.api.dto.UnitDto;
import com.sptg.estate.api.dto.UserDto;
import com.sptg.estate.api.entity.Residential;
import com.sptg.estate.api.entity.Room;
import com.sptg.estate.api.entity.Unit;
import com.sptg.estate.api.entity.User;
import com.sptg.estate.api.feigns.ResidentialFeign;
import com.sptg.estate.api.feigns.RoomFeign;
import com.sptg.estate.api.feigns.UnitFeign;
import com.sptg.estate.api.feigns.UserFeign;
import com.sptg.permissions.api.constant.PermissionsSecurityToken;
import com.sptg.permissions.api.dto.OrgDto;
import com.sptg.permissions.api.entity.Account;
import com.sptg.permissions.api.entity.Organization;
import com.sptg.permissions.api.feigns.OrgFeign;
import com.sptg.statistics.api.constant.SysLogMenuConstant;
import com.sptg.statistics.api.entity.SysOperationLog;
import com.sptg.statistics.api.feigns.SysOperationLogFeign;
import lombok.AllArgsConstructor;
import org.apache.poi.ss.formula.OperationEvaluationContext;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * title: OrgManageController
 * package: com.sptg.gateway.controller.permissions
 * description: 机构管理-控制器
 *
 *
 *
 */
@RestController
@AllArgsConstructor
public class OrgManageController {

    private final SecurityServiceInterface<Account> securityServiceInterface;
    private final OrgFeign orgFeign;
    private final SysOperationLogFeign sysOperationLogFeign;
    private final UnitFeign unitFeign;
    private final RoomFeign roomFeign;
    private final UserFeign userFeign;
    private final ResidentialFeign residentialFeign;

    /**
     * 功能描述: 根据Pid获取子机构列表
     * @param dto
     * {
     *     pid          :   必填
     *     excludeOwn   :   默认1 { 1:不查询自己, 其他:查询 }
     *     isTreeSort   :   默认1 { 1:树形排序,其他:不排序 }
     * }
     * @return ResultBean<Organization>
     *
     *
     */
    @GetMapping(value = "/permissions/org/getSubListByPid")
    @Security(format = DataFormatEnum.JSON)
    public ResultBean<Organization> getSubListByPid(OrgDto dto){
        //  参数校验
        if (null == dto || null == dto.getPid()){
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        Organization org = this.orgFeign.getOrgById(dto.getPid());
        //  获取当前用户信息
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setPosition(onLineUser.getOrgPosition());
        List<Organization> list = this.orgFeign.getSubListByPid(dto);
        if (null != org.getOrgType() && org.getOrgType() == OperationConstant.THREE && dto.getIsShowFlag() != OperationConstant.TWO){
            ResidentialDto resDto = new ResidentialDto();
            resDto.setEstatePid(dto.getPid());
            List<Organization> resList = getResidentialOrgListByPid(resDto);
            if (resList != null && resList.size() > 0){
                list.addAll(resList);
            }
        }
        //  判断是否查询自己
        if (dto.getExcludeOwn() != OperationConstant.ONE){
//            list.add(0,org);
            List<Organization> orgList = new ArrayList<>();
            org.setSubList(list);
            orgList.add(org);
            return new ResultBean<>(ResultEnum.SUCCESS, orgList);
        }else{
            return new ResultBean<>(ResultEnum.SUCCESS,list);
        }
        //  判断是否需要树形排序
//        if (dto.getIsTreeSort() == OperationConstant.ONE){
//            list = TreeUtil.tree(list);
//        }
//        return new ResultBean<>(ResultEnum.SUCCESS,list);
    }

    public List<Organization> getResidentialOrgListByPid(ResidentialDto dto){
        List<Organization> list = new ArrayList<>();
        ResultBean<Residential> resBean = this.residentialFeign.getListByCondition(dto);
        List<Residential> resList = resBean.getList();
        if (null != resList && resList.size() > 0){
            resList.forEach(item -> {
                list.add(this.orgFeign.getOrgById(item.getId()));
            });
            return list;
        }
        return list;
    }

    @GetMapping(value = "/permissions/org/getOrgTreeByPid")
    @Security(format = DataFormatEnum.JSON)
    public ResultBean<List<Map<String, Object>>> getOrgTreeByPid(OrgDto dto){
        //  参数校验
        if (null == dto || null == dto.getPid()){
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        //  获取当前用户信息
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        Organization organization = this.orgFeign.getOrgById(dto.getPid());
        List list;
        if (organization.getFlag() == OperationConstant.TWO){
            ResidentialDto residentialDto = new ResidentialDto();
            if (organization.getOrgType() == OperationConstant.THREE){
                residentialDto.setEstatePosition(organization.getPosition());
            }else{
                residentialDto.setOrgPosition(organization.getPosition());
            }
            ResultBean<Residential> residentialResultBean = this.residentialFeign.findListByPosition(residentialDto);
            list = residentialResultBean.getList();
        }else{
            dto.setPosition(onLineUser.getOrgPosition());
            list = this.orgFeign.getSubListByPid(dto);
        }
        List<Map<String, Object>> subTree = null;
        if (list != null && list.size() > 0) {
            List<Map<String, Object>> maps = beanToMap(list);
            subTree = getTree(dto, maps);
        }
        //  判断是否查询自己
        //  判断是否需要树形排序
        if (dto.getExcludeOwn() != OperationConstant.ONE && dto.getIsTreeSort() == OperationConstant.ONE){
            BeanMap beanMap = BeanMap.create(organization);
            if (dto.getIsShowFlag() != 2 && organization.getOrgType() == OperationConstant.THREE){
                getResidential(dto, beanMap);
            }
            if (subTree != null){
                ArrayList subList = (ArrayList) beanMap.get("subList");
                if (subList != null){
                    subTree.addAll(subList);
                }
                beanMap.put("subList", subTree);
            }
            List<Map<String, Object>> tree = new ArrayList<>();
            tree.add(beanMap);
            return new ResultBean(ResultEnum.SUCCESS,tree);
        }else{
            return new ResultBean(ResultEnum.SUCCESS,subTree);
        }

    }

    /**
     * 递归查询子机构
     * @param dto
     * @param list
     * @return
     */
    public List<Map<String, Object>> getTree(OrgDto dto, List<Map<String, Object>> list){
        list.forEach(item -> {
            dto.setPid(Long.parseLong(item.get("id").toString()));
            List<Organization> subList;
            Organization itemOrg = this.orgFeign.getOrgById(Long.parseLong(item.get("id").toString()));
            if (dto.getIsShowFlag() != 2 && itemOrg != null && itemOrg.getFlag() == OperationConstant.ONE && itemOrg.getOrgType() == OperationConstant.THREE){
                //物业机构，要添加小区
                getResidential(dto, item);
            }
            subList = this.orgFeign.getSubListByPid(dto);
            if (subList != null && subList.size() > 0){
                List<Map<String, Object>> maps = beanToMap(subList);
                getTree(dto, maps);

                ArrayList itemSubList = (ArrayList) item.get("subList");
                if (itemSubList != null){
                    itemSubList.addAll(maps);
                    item.put("subList", itemSubList);
                }else{
                    item.put("subList", maps);
                }

//                item.setSubList(subList);
//                List<Map<String, Object>> tree1 = getTree(dto, maps);
            }
            //flag{1：机构，2：小区，3：部门}
            if (subList.size() == 0){
                if ((item.get("flag") != null && "2".equals(item.get("flag").toString())) || (item.get("isAssign") != null && "1".equals(item.get("isAssign").toString()))){
                    getUnitOrRoom(dto, item);
                }
            }
        });
        return list;
    }

    /**
     *
     * @param dto OrgDto
     * @param item 物业机构map
     */
    public void getResidential(OrgDto dto, Map<String, Object> item){
        ResidentialDto residentialDto = new ResidentialDto();
        residentialDto.setEstatePosition(item.get("position").toString());
        residentialDto.setEstatePid(Long.parseLong(item.get("id").toString()));
//        ResultBean<Residential> resultBean = this.residentialFeign.findListByPosition(residentialDto);
        ResultBean<Residential> resultBean = this.residentialFeign.getListByCondition(residentialDto);
        List<Residential> residentialList = resultBean.getList();
        if (residentialList != null && residentialList.size() > 0){
            List<Map<String, Object>> maps = beanToMap(residentialList);
            item.put("subList", maps);
            maps.forEach(map -> {
                getUnitOrRoom(dto, map);
            });
        }
    }

    public void getUnitOrRoom(OrgDto dto ,Map<String, Object> map){
        Organization userOrg = this.orgFeign.getOrgById(this.securityServiceInterface.getOnLineUser().getOrgId());
        Integer isShowFlag = dto.getIsShowFlag();
        if (isShowFlag == 5){//显示到单元
            UnitDto unitDto = new UnitDto();
            Residential residential = this.residentialFeign.findResidentialById(Long.parseLong(map.get("id").toString()));
            if (userOrg.getOrgType() == OperationConstant.THREE){
                unitDto.setEstatePosition(residential.getEstatePosition());
            }else{
                unitDto.setOrgPosition(residential.getOrgPosition());
            }
            ResultBean<Unit> resultBean = this.unitFeign.findListByPosition(unitDto);
            List<Unit> unitList = resultBean.getList();
            if (unitList != null && unitList.size() > 0){
                List<Map<String, Object>> maps = beanToMap(unitList);
                map.put("subList", maps);
            }
        }

        if (isShowFlag == 0){//要显示到房间
            UnitDto unitDto = new UnitDto();
            Residential residential = this.residentialFeign.findResidentialById(Long.parseLong(map.get("id").toString()));
            if (userOrg.getOrgType() == OperationConstant.THREE){
                unitDto.setEstatePosition(residential.getEstatePosition());
            }else{
                unitDto.setOrgPosition(residential.getOrgPosition());
            }
            ResultBean<Unit> resultBean = this.unitFeign.findListByPosition(unitDto);
            List<Unit> unitList = resultBean.getList();
            if (unitList != null && unitList.size() > 0){
                List<Map<String, Object>> maps = beanToMap(unitList);
//                        item.put("subList", maps);
                maps.forEach(unitMap -> {
                    RoomDto roomDto = new RoomDto();
                    Unit unit = this.unitFeign.findUnitById(Long.parseLong(unitMap.get("id").toString()));
                    if (userOrg.getOrgType() == OperationConstant.THREE){
                        roomDto.setEstatePosition(unit.getEstatePosition());
                    }else{
                        roomDto.setOrgPosition(unit.getOrgPosition());
                    }
                    ResultBean<Room> resultBeanRoom = this.roomFeign.findListByPosition(roomDto);
                    List<Room> roomList = resultBeanRoom.getList();
                    if (roomList != null &&  roomList.size() > 0){
                        List<Map<String, Object>> mapsRoom = beanToMap(roomList);
                        unitMap.put("subList", mapsRoom);
                    }
                });
                map.put("subList", maps);
            }
        }
    }

    public List<Map<String, Object>> beanToMap(List list){
        List<Map<String, Object>> mapList = new ArrayList<>();
//         ArrayList tt = (ArrayList) list.get(0);
        list.forEach(bean -> {
            BeanMap map = BeanMap.create(bean);
            boolean add = mapList.add(map);
        });
        return mapList;
    }

    /**
     * 功能描述: 分页查询机构列表
     * @param dto
     * {
     *      id      :   选填，主键
     * }
     * @param pageBean 分页信息,必填
     * @return ResultBean<Page>
     *
     *
     */
    @GetMapping(value = "/permissions/org/pagingQuery")
    @Security(token = PermissionsSecurityToken.ORGANIZATION_MANAGE,format = DataFormatEnum.JSON)
    public ResultBean<Page> pagingQuery(OrgDto dto,PageBean<Organization,OrgDto> pageBean){
        //  参数校验
        dto = null == dto ? new OrgDto() : dto;
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setPosition(onLineUser.getOrgPosition());
        pageBean.setDto(dto);
        Page<Organization> page = this.orgFeign.pagingQuery(pageBean);
        return new ResultBean<>(ResultEnum.SUCCESS,page);
    }

    /**
     * 功能描述: 修改机构状态
     * @param dto
     * {
     *     id       :   必填
     *     isEnable :   必填 { 1 : 启用 ,2 : 禁用 }
     * }
     * @return ResultBean<Boolean>
     *
     *
     */
    @PostMapping(value = "/permissions/org/updateIsEnable")
    @Security(token = PermissionsSecurityToken.ORGANIZATION_IS_ENABLE,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> updateIsEnable(OrgDto dto){
        if (null == dto || null == dto.getId() || null == dto.getIsEnable()){
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        Organization oldObj = this.orgFeign.getOrgById(dto.getId());
        if (oldObj == null){
            return new ResultBean<>(ResultEnum.NOT_FIND);
        }
        //  获取当前用户
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setPosition(onLineUser.getOrgPosition());
        ResultBean<Boolean> resultBean=this.orgFeign.updateIsEnable(dto);
        if(null != resultBean && resultBean.getCode().equals(ResultEnum.SUCCESS.getCode())){
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            Organization newObj = this.orgFeign.getOrgById(dto.getId());
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ORGANIZATION_MANAGE, SysLogConstant.ALTER_EVENT,
                    WebUtils.getIp(),dto.getIsEnable()==1?"启动机构":"禁用机构",dto,onLineUser,oldObj,newObj);
            sysOperationLogFeign.info(sysOperationLog);
            /*-------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    /**
     * 功能描述: 删除机构
     * @param dto
     * {
     *     id   :   必填
     * }
     * @return ResultBean<Boolean>
     *
     *
     */
    @PostMapping(value = "/permissions/org/deleteEntity")
    @Security(token = PermissionsSecurityToken.ORGANIZATION_DELETE,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> deleteEntity(OrgDto dto){
        if (null == dto || null == dto.getId()){
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        Organization oldObj = this.orgFeign.getOrgById(dto.getId());
        if (oldObj == null){
            return new ResultBean<>(ResultEnum.NOT_FIND);
        }
        //  获取当前用户
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setPosition(onLineUser.getOrgPosition());
        //  只删除机构
        dto.setFlag(OperationConstant.ONE);
        dto.setStatus(OperationConstant.MINUS_ONE);
        ResultBean<Boolean> resultBean=this.orgFeign.deleteEntity(dto);
        if( null != resultBean && resultBean.getCode().equals(ResultEnum.SUCCESS.getCode())){
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ORGANIZATION_MANAGE, SysLogConstant.DELETE_EVENT,
                    WebUtils.getIp(),dto,onLineUser,oldObj);
            sysOperationLogFeign.info(sysOperationLog);
            /*-------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    /**
     * 功能描述: 根据机构名称模糊查询
     * @param dto
     * {
     *     name :   必填
     * }
     * @return ResultBean<Organization>
     *
     *
     */
    @GetMapping(value = "/permissions/org/getListByLikeName")
    @Security(format = DataFormatEnum.JSON)
    public ResultBean<Organization> getListByLikeName(OrgDto dto){
        if (null == dto){
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        //  获取当前用户
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setPosition(onLineUser.getOrgPosition());
        List<Organization> orgList = this.orgFeign.selectListByLikeName(dto);

        Organization userOrg = this.orgFeign.getOrgById(onLineUser.getOrgId());
        //类型为物业，若当前账号为机构子公司，则获取所有的物业公司合并一起返回
        if (null != dto.getOrgType() && dto.getOrgType() == OperationConstant.THREE && userOrg.getOrgType() == OperationConstant.ONE && userOrg.getId() != OperationConstant.ONE){
            dto.setPosition("0/1/");
            dto.setOrgType(OperationConstant.THREE);
            List<Organization> list = this.orgFeign.selectListByCondition(dto);
            orgList.addAll(list);
        }

        return new ResultBean<>(ResultEnum.SUCCESS, orgList);
    }

    /**
     * 功能描述:查询机构列表
     * @return ResultBean<Organization>
     *
     *
     */
    @GetMapping(value = "/permissions/org/getList")
    @Security(format = DataFormatEnum.JSON)
    public ResultBean<Organization> getList(){
        OrgDto dto = new OrgDto();
        dto.setFlag(OperationConstant.ONE);
        //  获取当前用户
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setPosition(onLineUser.getOrgPosition());
        List<Organization> orgList = this.orgFeign.selectListByCondition(dto);

        Organization userOrg = this.orgFeign.getOrgById(onLineUser.getOrgId());
        //若为机构子公司，则获取所有的物业公司合并一起返回
        if (userOrg.getOrgType() == OperationConstant.ONE && userOrg.getId() != OperationConstant.ONE){
            dto.setPosition("0/1/");
            dto.setOrgType(OperationConstant.THREE);
            List<Organization> list = this.orgFeign.selectListByCondition(dto);
            orgList.addAll(list);
        }
        return new ResultBean<>(ResultEnum.SUCCESS,orgList);
    }

    /**
     * 功能描述: 创建机构
     * @param dto 机构信息
     * @return ResultBean<Organization>
     *
     *
     */
    @PostMapping(value = "/permissions/org/add")
    @Security(token = PermissionsSecurityToken.ORGANIZATION_INSERT,format = DataFormatEnum.JSON)
    public ResultBean<Organization> addEntity(OrgDto dto){
        //  参数校验
        if (null == dto || StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getRegionArea())){
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        //  获取当前用户
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setPosition(onLineUser.getOrgPosition());
        dto.setCreateAccountId(onLineUser.getId());
        dto.setFlag(OperationConstant.ONE);
        dto.setCode("O");
        //机构类型 { 1：内部,2：广告,3：物业, 4：社区, 5: 园区 }
        if ((dto.getOrgType() == OperationConstant.TWO || dto.getOrgType() == OperationConstant.THREE || dto.getOrgType() == OperationConstant.FOUR || dto.getOrgType() == OperationConstant.FIVE) && dto.getPid() == null){
            //如果是新建物业或者广告商，则pid为空，隐形挂在常运智慧科技下面，方便常运智慧管理（常运智慧id为1）
            Organization org = this.orgFeign.getOrgById(1L);
            dto.setPid(org.getId());
            dto.setPosition(org.getPosition());
        }
        ResultBean<Organization> resultBean=this.orgFeign.addEntity(dto);
        if(null != resultBean && resultBean.getCode().equals(ResultEnum.SUCCESS.getCode())){
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ORGANIZATION_MANAGE, SysLogConstant.ADD_EVENT,
                    WebUtils.getIp(),dto,onLineUser,dto);
            sysOperationLogFeign.info(sysOperationLog);
            /*-------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    /**
     * 功能描述: 修改机构信息
     * @param dto 机构信息
     * @return ResultBean<Boolean>
     *
     *
     */
    @PostMapping(value = "/permissions/org/edit")
    @Security(token = PermissionsSecurityToken.ORGANIZATION_INSERT,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> editEntity(OrgDto dto){
        if (null == dto || null == dto.getId() || StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getRegionArea())){
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        Organization oldObj = this.orgFeign.getOrgById(dto.getId());
        if (oldObj == null){
            return new ResultBean<>(ResultEnum.NOT_FIND);
        }
        //  获取当前用户
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setPosition(onLineUser.getOrgPosition());
        dto.setFlag(OperationConstant.ONE);
        ResultBean<Boolean> resultBean=this.orgFeign.editEntity(dto);
        if(null != resultBean && resultBean.getCode().equals(ResultEnum.SUCCESS.getCode())){
            Organization newObj = this.orgFeign.getOrgById(dto.getId());
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ORGANIZATION_MANAGE, SysLogConstant.ALTER_EVENT,
                    WebUtils.getIp(),dto,onLineUser,oldObj,newObj);
            sysOperationLogFeign.info(sysOperationLog);
            /*-------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }


    /**
     * 功能描述: 根据Id 获取权限信息
     * @param orgId 主键
     * @return ResultBean<Organization>
     *
     *
     */
    @GetMapping(value = "/permissions/org/get/{orgId}")
    @Security(token = PermissionsSecurityToken.ORGANIZATION_MANAGE,format = DataFormatEnum.JSON)
    public ResultBean<Organization> getOrgById(@PathVariable(value = "orgId") Long orgId){
        Organization org = this.orgFeign.getOrgById(orgId);
        if (null != org){
            //  权限校验
            Account onLineUser = this.securityServiceInterface.getOnLineUser();
            if (!org.getPosition().startsWith(onLineUser.getOrgPosition())){
                return new ResultBean<>(ResultEnum.FORBIDDEN);
            }
        }
        return new ResultBean<>(ResultEnum.SUCCESS,org);
    }

    /**
     * 功能描述: 机构迁移
     * @param dto
     * {
     *     id   :   必填,
     *     pid  :   必填
     * }
     * @return ResultBean<Boolean>
     *
     *
     */
    @PostMapping(value = "/permissions/org/transfer")
    public ResultBean<Boolean> transfer(OrgDto dto){
        if (null == dto || null == dto.getId()){
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        Organization oldObj = this.orgFeign.getOrgById(dto.getId());
        if (oldObj == null){
            return new ResultBean<>(ResultEnum.NOT_FIND);
        }
        //  获取当前用户
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setPosition(onLineUser.getOrgPosition());
//        ResultBean<Boolean> resultBean=this.orgFeign.updatePid(dto);
        ResultBean<Boolean> resultBean = this.organizationChange(dto);
        if( null != resultBean && resultBean.getCode().equals(ResultEnum.SUCCESS.getCode())){
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            Organization newObj = this.orgFeign.getOrgById(dto.getId());
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ORGANIZATION_MANAGE, SysLogConstant.ALTER_EVENT,
                    WebUtils.getIp(),"机构id("+dto.getId()+")迁移至机构id("+dto.getPid()+")",dto,onLineUser,oldObj,newObj);
            sysOperationLogFeign.info(sysOperationLog);
            /*-------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    /**
     * 上级机构发生改变
     * @param orgDto
     * @return
     */
    @Transactional(rollbackFor = Throwable.class)
    @LcnTransaction
    public ResultBean<Boolean> organizationChange(OrgDto orgDto){
        Organization org = this.orgFeign.getOrgById(orgDto.getId());
        Integer orgType = org.getOrgType();
        if (orgDto.getPid() == null && orgType == OperationConstant.THREE){
            orgDto.setPid(1L);//挂在常运智慧下，作为顶级
        }
        //机构数据更新
        ResultBean<Boolean> resultBean1 = this.orgFeign.updatePid(orgDto);
        //获取所有关联的小区、单元、房间、住户列表
        ResidentialDto residentialDto = new ResidentialDto();
        UnitDto unitDto = new UnitDto();
        RoomDto roomDto = new RoomDto();
        UserDto userDto = new UserDto();
        if (orgType == OperationConstant.THREE){
            residentialDto.setEstatePosition(org.getPosition());
            unitDto.setEstatePosition(org.getPosition());
            roomDto.setEstatePosition(org.getPosition());
            userDto.setEstatePosition(org.getPosition());
        }else{
            residentialDto.setOrgPosition(org.getPosition());
            unitDto.setOrgPosition(org.getPosition());
            roomDto.setOrgPosition(org.getPosition());
            userDto.setOrgPosition(org.getPosition());
        }
        ResultBean<Residential> resResultBean = this.residentialFeign.findListByPosition(residentialDto);
        ResultBean<Unit> unitResultBean = this.unitFeign.findListByPosition(unitDto);
        ResultBean<Room> roomResultBean = this.roomFeign.findListByPosition(roomDto);
        ResultBean<User> userResultBean = this.userFeign.findListByPosition(userDto);
        List<Residential> residentialList = resResultBean.getList();
        List<Unit> unitList = unitResultBean.getList();
        List<Room> roomList = roomResultBean.getList();
        List<User> userList = userResultBean.getList();

        //小区数据更新
        Organization oldParent = this.orgFeign.getOrgById(org.getPid());
        Organization newParent = this.orgFeign.getOrgById(orgDto.getPid());
        String oldPidPosition = oldParent.getPosition();
        String newPidPosition = newParent.getPosition();
        if (residentialList != null && residentialList.size() > 0) {
            residentialList.forEach(residential -> {
                String resiPosition;
                if (orgType == OperationConstant.THREE){
                    resiPosition = residential.getEstatePosition().replace(oldPidPosition, newPidPosition);
                    residential.setEstatePosition(resiPosition);
//                    residential.setEstatePid(newParent.getId());
//                    residential.setEstatePidName(newParent.getName());
                }else{
                    resiPosition = residential.getOrgPosition().replace(oldPidPosition, newPidPosition);
                    residential.setOrgPosition(resiPosition);
//                    residential.setOrgPid(newParent.getId());
//                    residential.setOrgPidName(newParent.getName());
//                    residential.setRootOrgId(newParent.getRootOrgId());
                    //同步更改机构表中的物业数据
                    Organization residentialOrg = this.orgFeign.getOrgById(residential.getId());
                    residentialOrg.setPosition(resiPosition);
//                    residentialOrg.setPid(newParent.getId());
//                    residentialOrg.setParentName(newParent.getName());
//                    residentialOrg.setRootOrgId(newParent.getRootOrgId());
                    this.orgFeign.updateEntity(residentialOrg);
                }
                boolean updateResiResult = this.residentialFeign.updateEntity(residential);
            });
        }

        //单元数据更新
        if (unitList != null && unitList.size() > 0) {
            unitList.forEach(unit -> {
                String unitPosition;
                if (orgType == OperationConstant.THREE){
                    unitPosition = unit.getEstatePosition().replace(oldPidPosition, newPidPosition);
                    unit.setEstatePosition(unitPosition);
                }else{
                    unitPosition = unit.getOrgPosition().replace(oldPidPosition, newPidPosition);
                    unit.setOrgPosition(unitPosition);
                }
                boolean updateUnitResult = this.unitFeign.updateEntity(unit);
            });
        }

        //房间数据更新
        if (roomList != null && roomList.size() > 0) {
            roomList.forEach(room -> {
                String roomPosition;
                if (orgType == OperationConstant.THREE){
                    roomPosition = room.getEstatePosition().replace(oldPidPosition, newPidPosition);
                    room.setEstatePosition(roomPosition);
                }else{
                    roomPosition = room.getOrgPosition().replace(oldPidPosition, newPidPosition);
                    room.setOrgPosition(roomPosition);
                }
                boolean updateRoomResult = this.roomFeign.updateEntity(room);
            });
        }
        //住户数据更新
        if (userList != null && userList.size() > 0) {
            userList.forEach(user -> {
                String userPosition;
                if (orgType == OperationConstant.THREE){
                    userPosition = user.getEstatePosition().replace(oldPidPosition, newPidPosition);
                    user.setEstatePosition(userPosition);
                }else{
                    userPosition = user.getOrgPosition().replace(oldPidPosition, newPidPosition);
                    user.setOrgPosition(userPosition);
                }
                boolean updateUserResult = this.userFeign.updateEntity(user);
            });
        }
        return new ResultBean(ResultEnum.SUCCESS, true);
    }
}
