package com.hotent.uc.manager.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.hotent.base.cache.CacheManager;
import com.hotent.base.cache.ICache;
import com.hotent.base.cache.annotation.Cacheable;
import com.hotent.base.conf.SaaSConfig;
import com.hotent.base.constants.CacheKeyConst;
import com.hotent.base.context.BaseContext;
import com.hotent.base.exception.BaseException;
import com.hotent.base.handler.MultiTenantHandler;
import com.hotent.base.handler.MultiTenantIgnoreResult;
import com.hotent.base.jms.JmsProducer;
import com.hotent.base.jwt.JwtTokenHandler;
import com.hotent.base.manager.impl.BaseManagerImpl;
import com.hotent.base.model.CommonResult;
import com.hotent.base.query.*;
import com.hotent.base.util.*;
import com.hotent.base.util.time.DateFormatUtil;
import com.hotent.base.util.time.DateUtil;
import com.hotent.uc.api.model.IUser;
import com.hotent.uc.dao.*;
import com.hotent.uc.exception.HotentHttpStatus;
import com.hotent.uc.exception.RequiredException;
import com.hotent.uc.manager.*;
import com.hotent.uc.model.*;
import com.hotent.uc.params.common.OrgExportObject;
import com.hotent.uc.params.group.GroupIdentity;
import com.hotent.uc.params.org.OrgAuthVo;
import com.hotent.uc.params.org.OrgPostVo;
import com.hotent.uc.params.org.OrgUserVo;
import com.hotent.uc.params.org.OrgVo;
import com.hotent.uc.params.orgRole.OrgRoleVo;
import com.hotent.uc.params.orgRole.RoleOrgVo;
import com.hotent.uc.params.post.PostDueVo;
import com.hotent.uc.params.user.UserUnderVo;
import com.hotent.uc.params.user.UserVo;
import com.hotent.uc.util.AuthFilterUtil;
import com.hotent.uc.util.ContextUtil;
import com.hotent.uc.util.OrgUtil;
import com.hotent.uc.vo.OrgTreeVo;
import io.jsonwebtoken.Claims;
import org.apache.commons.collections.CollectionUtils;
import org.apache.logging.log4j.util.Strings;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import poi.util.ExcelUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 *
 * <pre>
 *
 * 描述：组织架构 处理实现类
 * 构建组：eip平台-bpmx-platform
 * 作者:ray
 * 邮箱:zhangyg@jee-soft.cn
 * 日期:2016-06-28 15:13:03
 * 版权：广州宏天软件有限公司
 * </pre>
 */
@Service
public class OrgManagerImpl extends BaseManagerImpl<OrgDao, Org> implements OrgManager {
	protected static Logger logger = LoggerFactory.getLogger(OrgManagerImpl.class);
	@Autowired
	OrgParamsManager orgParamsService;
	@Autowired
	OrgUserManager orgUserService;
	@Autowired
	UserUnderManager userUnderService;
	@Autowired
	UserUnderManager userUnderManager;
	@Autowired
	UserManager userService;
	@Autowired
	OrgPostManager orgPostService;
	@Autowired
	OrgPostDao orgPostDao;
	@Autowired
	OrgRoleManager orgRoleService;
	@Autowired
	DemensionManager demensionService;
	@Autowired
	ParamsManager paramsSerivce;
	@Autowired
	OrgAuthManager orgAuthService;
	@Autowired
	OrgJobManager orgJobService;
	@Autowired
	OrgJobDao orgJobDao;
	@Autowired
	RoleManager roleService;
	@Autowired
	OrgRoleManager orgRoleManager;
	@Autowired
	DemensionManager DemensionManager;
	@Autowired
	PropertiesService propertiesService;
	@Autowired
	OrgParamsDao orgParamsDao;
	@Autowired
	OrgPostManager postService;
	@Autowired
	OrgUserManager orgUserManager;
	@Autowired
	DemensionManager demService;
	@Resource
	OrgUserDao orgUserDao;
	@Resource
	RoleManager roleManager;
	@Resource
	UserManager userManager;
	@Autowired
	OrgExternalSettingManager orgExternalSettingManager;
	@Autowired
	OrgManager orgService;
	@Resource
	JwtTokenHandler jwtTokenHandler;
	@Autowired
	DemensionManager demensionManager;
	@Autowired
	SaaSConfig saaSConfig;
	@Resource
	BaseContext baseContext;

	OrgExternalManager orgExternalManager;
	@Autowired
	JmsProducer jmsProducer;
	// 子节点
	static List<Org> childOrg = new ArrayList<Org>();

	public Org getByCode(String code) {
		return baseMapper.getByCode(code);
	}

	public List<Org> getOrgListByUserId(String userId) {
		return baseMapper.getOrgListByUserId(userId);
	}

	public List<Org> getOrgListByAccount(String account) throws Exception {
		User user = userService.getByAccount(account);
		return baseMapper.getOrgListByUserId(user.getId());
	}

	@Override
	@Cacheable(value = CacheKeyConst.EIP_UC_USER_MAIN_ORG, key = "#demId + '-' + #userId")
	public Org getMainGroup(String userId, String demId) {
		if (BeanUtils.isNotEmpty(demId)) {
			if (BeanUtils.isEmpty(demensionService.get(demId))) {
				Demension sysDemension = demensionService.getByCode(demId);
				if (BeanUtils.isNotEmpty(sysDemension)) {
					demId = sysDemension.getId();
				}
			}
		} else {
			Demension sysDemension = demensionService.getDefaultDemension();
			if (BeanUtils.isNotEmpty(sysDemension)) {
				demId = sysDemension.getId();
			}
		}
		List<Org> list = baseMapper.getMainOrgListByUser(userId, StringUtil.isEmpty(demId)?null:demId);
		if (BeanUtils.isEmpty(list)) {
			list = baseMapper.getOrgListByUserId(userId);
		}
		return BeanUtils.isEmpty(list) ? null : list.get(0);
	}

	@Override
	@Transactional
	public void removeByIds(String... ids) {
		super.removeByIds(ids);
		for (String id : ids) {
			// 删除组织参数
			orgParamsService.removeByOrgId(id);
			// 删除组织岗位
			orgPostService.delByOrgId(id);
			// 删除组织用户
			orgUserService.delByOrgId(id);
			// 删除下属
			userUnderService.delByOrgId(id);
			// 删除分级组织管理
			orgAuthService.delByOrgId(id);
		}

		// 查找子节点
		List<Org> allList = this.getAll();
		childOrg.removeAll(childOrg);
		for (String id : ids) {
			treeOrgList(allList, id);
		}
		// 删除子节点
		String[] childIds = new String[childOrg.size()];
		for (int i = 0; i < childOrg.size(); i++) {
			String id = childOrg.get(i).getId();
			childIds[i] = id;
			this.remove(id);
		}

		// 子组织中相关数据的删除
		for (String childId : childIds) {
			orgParamsService.removeByOrgId(childId);
			orgPostService.delByOrgId(childId);
			orgUserService.delByOrgId(childId);
			userUnderService.delByOrgId(childId);
			orgAuthService.delByOrgId(childId);
		}
	}

	@Override
	@Transactional
	public void updateByOrg(Org org) throws SQLException {
		String extName = org.getPathName().substring(0, org.getPathName().indexOf("/" + org.getName()));
		String extId = org.getPath().substring(0, org.getPath().indexOf("." + org.getId()));
		this.update(org);

		String[] ids = { org.getId() };

		// 查找子节点
		List<Org> allList = this.getAll();
		List<Org> cList = new ArrayList<Org>();
		for (String id : ids) {
			getChild(allList, id, cList);
		}
		// 更新子节点
		String[] childIds = new String[cList.size()];
		// 子节点是递归往上找的数据，最孙的节点排在list前面，遍历时，先从一级子节点进行修改
		for (int i = cList.size() - 1; i >= 0; i--) {
			String id = cList.get(i).getId();
			childIds[i] = id;
			Org c = this.get(id);
			if (c.getParentId().equals(org.getId())) {// 一级子组织
				c.setPathName(org.getPathName() + "/" + c.getName());
				c.setPath(org.getPath() + c.getId() + ".");
				c.setDemId(org.getDemId());
			} else {// 二级及以下组织
				String pName = org.getName();
				String pId = org.getId();
				Org p = this.get(c.getParentId());
				String pathName = p.getPathName().substring(p.getPathName().indexOf("/" + pName),
						p.getPathName().length()) + "/" + c.getName();
				String path = p.getPath().substring(p.getPath().indexOf("." + pId), p.getPath().length()) + c.getId()
						+ ".";
				c.setPathName(extName + pathName);
				c.setPath(extId + path);
				c.setDemId(org.getDemId());
			}
			this.update(c);
		}

	}

	/**
	 * 获取某个父节点下面的所有子节点
	 *
	 * @param orgList
	 * @param pid
	 * @return
	 */
	public static List<Org> treeOrgList(List<Org> orgList, String parentId) {
		for (Org org : orgList) {
			// 遍历出父id等于参数的id，add进子节点集合
			if (parentId.equals(org.getParentId())) {
				// 递归遍历下一级
				treeOrgList(orgList, org.getId());
				childOrg.add(org);
			}
		}
		return childOrg;
	}

	@Override
	public List<Org> getByParentId(String parentId) {
		List<Org> rtnList = new ArrayList<Org>();
		List<Org> allList = this.getAll();
		return getChild(allList, parentId, rtnList);
	}

	/**
	 * 获取某个父节点下面的所有子节点
	 *
	 * @param orgList
	 * @param pid
	 * @return
	 */
	public static List<Org> getChild(List<Org> orgList, String parentId, List<Org> rtnList) {
		for (Org org : orgList) {
			// 遍历出父id等于参数的id，add进子节点集合
			if (parentId.equals(org.getParentId())) {
				// 递归遍历下一级
				getChild(orgList, org.getId(), rtnList);
				rtnList.add(org);
			}
		}
		return rtnList;
	}

	public List<Org> getByOrgName(String orgName) {
		return baseMapper.getByOrgName(orgName);
	}

	@Override
	public List<Org> getByPathName(String pathName) {
		return baseMapper.getByPathName(pathName);
	}

	@Override
	public List<Org> getByParentAndDem(QueryFilter queryFilter) {
		return baseMapper.getByParentAndDem(convert2Wrapper(queryFilter, currentModelClass()));
	}

	@Override
	public List<Org> getByParentAndDemTemp(QueryFilter queryFilter) {
		return baseMapper.getByParentAndDemTemp(convert2Wrapper(queryFilter, currentModelClass()));
	}
	@Override
	public Org getByDemIdAndSonId(String demId, String sonId) {
		return baseMapper.getByDemIdAndSonId(demId, sonId);
	}

	@Override
	public List<Org> getMainOrgListByUser(String userId, String demId) {
		return baseMapper.getMainOrgListByUser(userId, demId);
	}

	@Override
	public List<Org> getOrgListByDemId(String demId) {
		User currentUser = ContextUtil.getCurrentUser();
		currentUser = userManager.getById(currentUser.getId());
		Integer dataScope = currentUser.getDataScope();
		String provinceCode = currentUser.getProvinceCode();
		String cityCode = currentUser.getCityCode();
		String countyCode = currentUser.getCountyCode();
		return baseMapper.getOrgListByDemId(demId,dataScope,provinceCode,cityCode,countyCode);
	}

	@Override
	public List<Org> getUserOrg(String userId, String demId, Boolean isMain) {
		Map<String, Object> params = new HashMap<String, Object>();
		if (BeanUtils.isNotEmpty(isMain)) {
			if (isMain) {
				params.put("isMain", "1");
			} else {
				params.put("isMain", "0");
			}
		}
		if (StringUtil.isNotEmpty(demId)) {
			params.put("demId", demId);
		}
		params.put("userId", userId);
		return baseMapper.getUserOrg(params);
	}

	@Override
	@Transactional
	public CommonResult<String> addOrg(OrgVo orgVo) throws Exception {
		if (StringUtil.isEmpty(orgVo.getName())) {
			throw new BaseException("添加组织失败，组织名称【name】不能为空！");
		}
		if (StringUtil.isEmpty(orgVo.getCode())) {
			throw new BaseException("添加组织失败，组织编码【code】不能为空！");
		}
		if (orgVo.getCode().contains(",")) {
			throw new BaseException("组织编码中不能包含英文逗号‘,’");
		}
		if (StringUtil.isEmpty(orgVo.getDemId())) {
			throw new BaseException("添加组织失败，维度id【demId】不能为空！");
		}
		if (baseMapper.getCountByCode(orgVo.getCode())>0) {
			throw new BaseException("添加组织失败，组织编码[" + orgVo.getCode() + "]已存在！");
		}
		Demension dem = demensionService.get(orgVo.getDemId());
		if (BeanUtils.isEmpty(dem)) {
			throw new BaseException("添加组织失败，根据输入的demId[" + orgVo.getDemId() + "]没有找到对应的维度信息！");
		}
		Org pOrg = null;
		if (!"0".equals(orgVo.getParentId()) && StringUtil.isNotEmpty(orgVo.getParentId())) {
			pOrg = this.get(orgVo.getParentId());
			if (BeanUtils.isEmpty(pOrg)) {
				throw new BaseException("添加组织失败，根据输入的parentId[" + orgVo.getParentId() + "]没有找到对应的组织信息！");
			}
			if (BeanUtils.isEmpty(pOrg) && !pOrg.getDemId().equals(orgVo.getDemId())) {
				throw new BaseException("添加组织失败，根据输入demId与所输入的父组织所对应的维度id不一致！");
			}
		}
		String orgTypeStr = "";
		if(orgVo.getOrgType().equals(0) || orgVo.getOrgType().equals(2) || orgVo.getOrgType().equals(3)) {
			orgTypeStr = "0,2,3";
		}
		boolean sameNameFlag = this.queryExistsNameBySameLevel(orgVo.getId(), orgVo.getParentId(), orgVo.getName(), orgTypeStr);
		if(sameNameFlag) {
			throw new RuntimeException("更新组织失败，在本层已经包含相同的组织名称，组织名称【" + orgVo.getName() + "】！");
		}
		Org o = new Org();
		if(orgVo.getId()!=null){
			o.setId(orgVo.getId());
		}else{
			o.setId(UniqueIdUtil.getSuid());
		}
		o.setCode(orgVo.getCode());
		o.setName(orgVo.getName());
		o.setDemId(orgVo.getDemId());
		o.setJoinExtSystemType(orgVo.getJoinExtSystemType());
		if(!StringUtils.isEmpty(orgVo.getJoinExtSystemSyndir())){
			o.setJoinExtSystemSyndir(orgVo.getJoinExtSystemSyndir());
		}
		if (StringUtils.isEmpty(orgVo.getParentId())) {
			o.setParentId("0");
		} else {
			o.setParentId(orgVo.getParentId());
		}
		if (StringUtil.isNotEmpty(orgVo.getGrade())) {
			o.setGrade(orgVo.getGrade());
		}
		if (BeanUtils.isNotEmpty(orgVo.getOrderNo())) {
			o.setOrderNo(orgVo.getOrderNo());
		}
		if (BeanUtils.isEmpty(pOrg)) {
			o.setPathName("/" + orgVo.getName());
			o.setPath(orgVo.getDemId() + "." + o.getId() + ".");
		} else {
			o.setPath(pOrg.getPath() + o.getId() + ".");
			o.setPathName(pOrg.getPathName() + "/" + orgVo.getName());
		}
		o.setLimitNum(orgVo.getLimitNum().intValue());
		o.setExceedLimitNum(orgVo.getExceedLimitNum().intValue());
		o.setOrgType(orgVo.getOrgType());
		//查询上级组织类型
		Org parentOrg = getById(orgVo.getParentId());
		if(parentOrg!=null) {
			if(Org.ORG_TYPE_DEP.equals(parentOrg.getOrgType())) {
				o.setSuperiorOrgId(parentOrg.getSuperiorOrgId());
				o.setSuperiorDepId(orgVo.getParentId());
			} else {
				o.setSuperiorOrgId(orgVo.getParentId());
			}
		}
		o.setDataScope(orgVo.getDataScope());
		o.setProvinceCode(orgVo.getProvinceCode());
		o.setCityCode(orgVo.getCityCode());
		o.setCountyCode(orgVo.getCountyCode());
		this.create(o);
		return new CommonResult<String>(true, "添加组织成功！", o.getId());
	}

	@Override
	//@Transactional
	public CommonResult<String> addOrgs(List<OrgVo> orgVos) throws Exception {
		//获取组织集合code，查询已存在的组织信息
        try {
            List<String> codes = orgVos.stream().map(o -> o.getCode()).distinct().collect(Collectors.toList());
            List<Org> orgList = this.getOrgListByCodes(codes);

            //List<Org> list = new ArrayList<>();
            for (OrgVo orgVo: orgVos ){
                Org or = orgList.stream().filter(org -> org.getCode().equals(orgVo.getCode())).findAny().orElse(null);
                //当前组织信息若存在则不添加
                if (or==null) {
                    if (StringUtil.isEmpty(orgVo.getName())) {
                        throw new BaseException("添加组织失败，组织名称【name】不能为空！");
                    }
                    if (StringUtil.isEmpty(orgVo.getCode())) {
                        throw new BaseException("添加组织失败，组织编码【code】不能为空！");
                    }
                    if (orgVo.getCode().contains(",")) {
                        throw new BaseException("组织编码中不能包含英文逗号‘,’");
                    }
                    if (StringUtil.isEmpty(orgVo.getDemId())) {
                        throw new BaseException("添加组织失败，维度id【demId】不能为空！");
                    }
                    if (baseMapper.getCountByCode(orgVo.getCode())>0) {
                        throw new BaseException("添加组织失败，组织编码[" + orgVo.getCode() + "]已存在！");
                    }
                    Demension dem = demensionService.get(orgVo.getDemId());
                    if (BeanUtils.isEmpty(dem)) {
                        throw new BaseException("添加组织失败，根据输入的demId[" + orgVo.getDemId() + "]没有找到对应的维度信息！");
                    }
                    Org pOrg = null;
                    if (!"0".equals(orgVo.getParentId()) && StringUtil.isNotEmpty(orgVo.getParentId())) {
                        pOrg = this.get(orgVo.getParentId());
                        if (BeanUtils.isEmpty(pOrg)) {
                            throw new BaseException("添加组织失败，根据输入的parentId[" + orgVo.getParentId() + "]没有找到对应的组织信息！");
                        }
                        if (BeanUtils.isEmpty(pOrg) && !pOrg.getDemId().equals(orgVo.getDemId())) {
                            throw new BaseException("添加组织失败，根据输入demId与所输入的父组织所对应的维度id不一致！");
                        }
                    }
                    String orgTypeStr = "";
                    if(orgVo.getOrgType().equals(0) || orgVo.getOrgType().equals(2) || orgVo.getOrgType().equals(3)) {
                        orgTypeStr = "0,2,3";
                    }
                    boolean sameNameFlag = false;
                    try {
                        sameNameFlag = this.queryExistsNameBySameLevel(orgVo.getId(), orgVo.getParentId(), orgVo.getName(), orgTypeStr);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    if(sameNameFlag) {
                        throw new RuntimeException("更新组织失败，在本层已经包含相同的组织名称，组织名称【" + orgVo.getName() + "】！");
                    }
                    Org o = new Org();
                    if(orgVo.getId()!=null){
                        o.setId(orgVo.getId());
                    }else{
                        o.setId(UniqueIdUtil.getSuid());
                    }
                    o.setCode(orgVo.getCode());
                    o.setName(orgVo.getName());
                    o.setDemId(orgVo.getDemId());
                    o.setJoinExtSystemType(orgVo.getJoinExtSystemType());
                    if(!StringUtils.isEmpty(orgVo.getJoinExtSystemSyndir())){
                        o.setJoinExtSystemSyndir(orgVo.getJoinExtSystemSyndir());
                    }
                    if (StringUtils.isEmpty(orgVo.getParentId())) {
                        o.setParentId("0");
                    } else {
                        o.setParentId(orgVo.getParentId());
                    }
                    if (StringUtil.isNotEmpty(orgVo.getGrade())) {
                        o.setGrade(orgVo.getGrade());
                    }
                    if (BeanUtils.isNotEmpty(orgVo.getOrderNo())) {
                        o.setOrderNo(orgVo.getOrderNo());
                    }
                    if (BeanUtils.isEmpty(pOrg)) {
                        o.setPathName("/" + orgVo.getName());
                        o.setPath(orgVo.getDemId() + "." + o.getId() + ".");
                    } else {
                        o.setPath(pOrg.getPath() + o.getId() + ".");
                        o.setPathName(pOrg.getPathName() + "/" + orgVo.getName());
                    }
                    o.setLimitNum(orgVo.getLimitNum().intValue());
                    o.setExceedLimitNum(orgVo.getExceedLimitNum().intValue());
                    o.setOrgType(orgVo.getOrgType());
                    //查询上级组织类型
                    Org parentOrg = getById(orgVo.getParentId());
                    if(parentOrg!=null) {
                        if(Org.ORG_TYPE_DEP.equals(parentOrg.getOrgType())) {
                            o.setSuperiorOrgId(parentOrg.getSuperiorOrgId());
                            o.setSuperiorDepId(orgVo.getParentId());
                        } else {
                            o.setSuperiorOrgId(orgVo.getParentId());
                        }
                    }
                    this.save(o);
                }
            }
        } catch (RuntimeException e) {
            throw new RuntimeException(e);
        }
        return new CommonResult<String>(true, "批量添加组织成功！", null);
	}

	@Override
	@Transactional
	public CommonResult<String> deleteOrg(String codes) throws Exception {
		if (StringUtils.isEmpty(codes)) {
			throw new BaseException(HotentHttpStatus.REUIRED.description() + "：组织代码必填！");
		}
		String message = "";
		String[] codeArr = codes.split(",");
		for (String code : codeArr) {
			Org o = this.getByCode(code);
			if (BeanUtils.isEmpty(o)) {
				message += "编码为【" + code + "】的组织不存在；";
				continue;
			}
			String[] ids = { o.getId() };
			removeByIds(ids);

		}
		if (StringUtils.isEmpty(message)) {
			message = "删除组织成功！";
		} else {
			message = "部分删除成功，其中" + message;
		}
		return new CommonResult<String>(true, message, "");
	}

	@Override
	@Transactional
	public CommonResult<String> updateOrg(OrgVo orgVo) throws Exception {
		if (orgVo.getExceedLimitNum()==1){
			if(orgVo.getLimitNum() < orgVo.getNowNum()){
				throw new RuntimeException("更新组织失败，当前组织人数超出限编人数！");
			}
		}
		if (StringUtil.isEmpty(orgVo.getCode())) {
			throw new RuntimeException("更新组织失败，组织编码【code】必填！");
		}
		Org o = this.getByCode(orgVo.getCode());
		if (BeanUtils.isEmpty(o)) {
			throw new RuntimeException("更新组织失败，根据组织编码【" + orgVo.getCode() + "】没有找到对应的组织！");
		}
		Demension dem = demensionService.get(orgVo.getDemId());
		if (StringUtil.isNotEmpty(orgVo.getDemId()) && BeanUtils.isEmpty(dem)) {
			throw new RuntimeException("更新组织失败，根据输入的demId【" + orgVo.getDemId() + "】没有找到对应的维度信息！");
		}
		String orgTypeStr = "";
		if(orgVo.getOrgType().equals(0) || orgVo.getOrgType().equals(2) || orgVo.getOrgType().equals(3)) {
			orgTypeStr = "0,2,3";
		}
		boolean sameNameFlag = this.queryExistsNameBySameLevel(orgVo.getId(), orgVo.getParentId(), orgVo.getName(), orgTypeStr);
		if(sameNameFlag) {
			throw new RuntimeException("更新组织失败，在本层已经包含相同的组织名称，组织名称【" + orgVo.getName() + "】！");
		}
		Org pOrg = null;
		if (StringUtil.isNotEmpty(orgVo.getParentId()) && !"0".equals(orgVo.getParentId())) {
			pOrg = this.get(orgVo.getParentId());
			if (BeanUtils.isEmpty(pOrg)) {
				throw new RuntimeException("更新组织失败，根据输入的parentId【" + orgVo.getDemId() + "】没有找到对应的组织信息！");
			}
			if (StringUtil.isNotEmpty(orgVo.getDemId()) && BeanUtils.isNotEmpty(pOrg)
					&& !pOrg.getDemId().equals(orgVo.getDemId())) {
				throw new RuntimeException("更新组织失败，根据输入demId与所输入的父组织所对应的维度id不一致！");
			}
		}
		if (StringUtil.isNotEmpty(orgVo.getName())) {
			o.setName(orgVo.getName());
		}
		if (StringUtil.isNotEmpty(orgVo.getGrade())) {
			o.setGrade(orgVo.getGrade());
		}
		if (BeanUtils.isNotEmpty(orgVo.getOrderNo())) {
			o.setOrderNo(orgVo.getOrderNo());
		}

		if (BeanUtils.isEmpty(pOrg)) {
			if (StringUtil.isNotEmpty(orgVo.getName())) {
				o.setPathName("/" + orgVo.getName());
			}
			if (StringUtil.isNotEmpty(orgVo.getDemId())) {
				o.setPath(orgVo.getDemId() + "." + o.getId() + ".");
				o.setDemId(orgVo.getDemId());
			}
		} else {
			o.setPath(pOrg.getPath() + o.getId() + ".");
			o.setPathName(pOrg.getPathName() + "/" + orgVo.getName());
			o.setDemId(orgVo.getDemId());
			o.setParentId(pOrg.getId());
		}
		o.setLimitNum(orgVo.getLimitNum().intValue());
		o.setExceedLimitNum(orgVo.getExceedLimitNum().intValue());
		o.setOrgType(orgVo.getOrgType());
		if(orgVo.getJoinExtSystemSyndir()!=null){
			o.setJoinExtSystemSyndir(orgVo.getJoinExtSystemSyndir());
		}
		o.setJoinExtSystemType(orgVo.getJoinExtSystemType());
		//查询上级组织类型
		Org parentOrg = getById(orgVo.getParentId());
		if(parentOrg!=null) {
			if(Org.ORG_TYPE_DEP.equals(parentOrg.getOrgType())) {
				o.setSuperiorOrgId(parentOrg.getSuperiorOrgId());
				o.setSuperiorDepId(orgVo.getParentId());
			} else {
				o.setSuperiorOrgId(orgVo.getParentId());
			}
		}
		o.setDataScope(orgVo.getDataScope());
		o.setProvinceCode(orgVo.getProvinceCode());
		o.setCityCode(orgVo.getCityCode());
		o.setCountyCode(orgVo.getCountyCode());
		this.updateByOrg(o);
		return new CommonResult<String>(true, "组织更新成功！", "");
	}

	@Override
	public Org getOrg(String code) throws Exception {
		if (StringUtils.isEmpty(code)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "：组织编码code必填！");
		}
		Org o = this.getByCode(code);
		if (BeanUtils.isEmpty(o)) {
			throw new RuntimeException("根据输入的组织编码没有找到对应的组织信息！");
		}
		o = this.get(o.getId());
		String pId = o.getParentId();
		String demId = o.getDemId();
		Demension d = demensionService.get(demId);
		if (d != null && !StringUtil.isEmpty(d.getDemCode())) {
			o.setDemCode(d.getDemCode());
		}
		if ("0".equals(pId) || StringUtil.isEmpty(pId)) {
			o.setParentOrgName(d.getDemName());
		} else {
			o.setParentOrgName(this.get(pId).getName());
		}
		List<OrgParams> params = this.getOrgParams(o.getCode());
		if (BeanUtils.isNotEmpty(params)) {
			Map<String, Object> map = new HashMap<String, Object>();
			for (OrgParams param : params) {
				map.put(param.getAlias(), param.getValue());
			}
			o.setParams(map);
		}
		return o;
	}

	@Override
	@Transactional
	public CommonResult<String> saveOrgParams(String orgCode, List<ObjectNode> params) throws Exception {
		if (StringUtils.isEmpty(orgCode)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "：组织编码orgCode必填！");
		}
		Org org = this.getByCode(orgCode);
		if (BeanUtils.isEmpty(org)) {
			throw new RuntimeException("根据输入的组织编码没有找到对应的组织信息！");
		}
		orgParamsService.removeByOrgId(org.getId());
		// 判断输入的key是否存在
		for (ObjectNode o : params) {
			String key = o.get("alias").asText();
			Params p = paramsSerivce.getByAlias(key);
			if (BeanUtils.isEmpty(p)) {
				throw new RuntimeException("【" + key + "】参数key不存在！");
			}
			if (!p.getType().equals("2")) {
				throw new RuntimeException("【" + key + "】对应的【用户组织扩展参数】类型不是【组织参数】类型！");
			}
		}
		try {
			orgParamsService.saveParams(org.getId(), params);
		} catch (Exception e) {
			if (e.getMessage().indexOf("ORA-12899") > -1) {
				throw new RuntimeException("保存失败，参数值过长");
			} else {
				throw e;
			}
			// TODO: handle exception
		}
		return new CommonResult<String>(true, "保存组织参数成功！", "");
	}

	@Override
	public List<OrgParams> getOrgParams(String orgCode) throws Exception {
		Org o = this.getByCode(orgCode);
		if (BeanUtils.isEmpty(o)) {
			throw new RuntimeException("根据输入的组织编码没有找到对应的组织信息！");
		}
		List<OrgParams> list = orgParamsService.getByOrgId(o.getId());
		return list;
	}

	@Override
	public CommonResult<OrgParams> getParamByAlias(String orgCode, String alias) throws Exception {
		Org o = this.getByCode(orgCode);
		if (BeanUtils.isEmpty(o)) {
			throw new RuntimeException("根据输入的组织编码没有找到对应的组织信息！");
		}
		OrgParams p = orgParamsService.getByOrgIdAndAlias(o.getId(), alias);
		if (BeanUtils.isEmpty(p)) {
			throw new RuntimeException("根据输入的参数别名【" + alias + "】没有找到对应的参数信息");
		}
		return new CommonResult<OrgParams>(true, "获取完毕！", p);
	}

	@Override
	@Transactional
	public CommonResult<String> addOrgUser(OrgUserVo orgUserVo) throws Exception {
		if (StringUtil.isEmpty(orgUserVo.getAccount())) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "：用户帐号account必填！");
		}
		if (StringUtil.isEmpty(orgUserVo.getOrgCode())) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "：组织编码orgCode必填！");
		}
		User u = userService.getByAccount(orgUserVo.getAccount());
		if (BeanUtils.isEmpty(u)) {
			throw new RuntimeException("没有找到对应的用户！");
		}
		if (BeanUtils.isNotEmpty(orgUserVo.getIsCharge())
				&& !(orgUserVo.getIsCharge() != 1 || orgUserVo.getIsCharge() != 0)) {
			throw new RuntimeException("isCharge只能为0或1");
		}
		if (BeanUtils.isNotEmpty(orgUserVo.getIsMaster())
				&& !(orgUserVo.getIsMaster() != 1 || orgUserVo.getIsMaster() != 0)) {
			throw new RuntimeException("isMaster只能为0或1");
		}
		Org o = this.getByCode(orgUserVo.getOrgCode());
		if (BeanUtils.isEmpty(o)) {
			throw new RuntimeException("没有找到对应的组织！");
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", u.getId());
		map.put("orgId", o.getId());
		List<OrgUser> list = orgUserService.getByParms(map);
		if (BeanUtils.isEmpty(list)) {
			OrgUser orgUser = new OrgUser();
			orgUser.setId(UniqueIdUtil.getSuid());
			orgUser.setUserId(u.getId());
			orgUser.setOrgId(o.getId());
			orgUser.setDemId(o.getDemId());
			orgUser.setIsRelActive(1);
			if (BeanUtils.isEmpty(orgUserVo.getIsCharge())) {
				orgUser.setIsCharge(0);
			} else {
				orgUser.setIsCharge(orgUserVo.getIsCharge());
			}

			if (BeanUtils.isEmpty(orgUserVo.getIsMaster())) {
				orgUser.setIsMaster(0);
			} else {
				orgUser.setIsMaster(orgUserVo.getIsMaster());
			}
			//查询用户在该维度下，是否有主组织
			List<OrgUser> l = orgUserService.getOrgUserMaster(u.getId(), o.getDemId());
			//已有主组织，但是当前组织是指定的主组织。则将原来的主组织取消
			if (BeanUtils.isNotEmpty(l) && orgUserVo.getIsMaster() == 1) {
				OrgUser ou = l.get(0);
				ou.setIsMaster(0);
				orgUserService.update(ou);
				//没有主组织，则将当前组织设定为主组织
			}else if (BeanUtils.isEmpty(l)) {
				orgUser.setIsMaster(1);
			}

			orgUserService.create(orgUser);
		} else {
			User user = userService.getByAccount(orgUserVo.getAccount());
			Org org = getByCode(orgUserVo.getOrgCode());
			throw new RuntimeException("用户【" + user.getFullname() + "("+orgUserVo.getAccount()+")】已存在组织【" + org.getName() + "("+orgUserVo.getOrgCode()+")】中");
		}
		return new CommonResult<String>(true, "加入用户成功", "");
	}

	@Override
	@Transactional
	public CommonResult<String> delOrgUser(String ids) throws Exception {
		if (StringUtil.isEmpty(ids)) {
			throw new RuntimeException("id值不能为空！");
		}
		String[] orgUserIds = ids.split(",");
		Boolean isDele = false;
		StringBuilder str = new StringBuilder();
		for (String id : orgUserIds) {// 将用户在该组织下的所有相关下属删除
			OrgUser obj = orgUserService.get(id);
			if (BeanUtils.isNotEmpty(obj)) {
				//清除用户主组织缓存
				orgUserService.removeUserMainOrgCache(obj.getUserId());
				userService.removeUserGroupsCache(obj.getUserId());
				orgUserService.removeUserMainOrgCache("", obj.getUserId());
				userUnderService.delByUserIdAndOrgId(obj.getUserId(), obj.getOrgId());
				isDele = true;
			} else {
				str.append(id);
				str.append("，");
			}
		}
		String msg = StringUtil.isEmpty(str.toString()) ? "用户取消加入成功！" : "部分用户取消加入成功，id为：" + str.toString() + "的数据不存在！";
		orgUserService.removeByIds(orgUserIds);
		return new CommonResult<String>(isDele, msg, "");
	}

	@Override
	public CommonResult<Boolean> getUserIsMaster(String account, String demCode) throws Exception {
		if (StringUtils.isEmpty(account)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "：用户帐号account必填！");
		}
		User u = userService.getByAccount(account);
		if (BeanUtils.isEmpty(u)) {
			throw new RuntimeException("根据输入的account没有找到对应的用户信息");
		}
		if (StringUtils.isEmpty(demCode)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "：维度编码demCode必填！");
		}
		Demension d = demensionService.getByCode(demCode);
		if (BeanUtils.isEmpty(d)) {
			throw new RuntimeException("根据输入的demCode没有找到对应的维度信息");
		}
		List<OrgUser> orgUsers = orgUserService.getOrgUserMaster(u.getId(), d.getId());
		if (BeanUtils.isEmpty(orgUsers)) {
			return new CommonResult<Boolean>(true, "用户在【" + d.getDemCode() + "】下没有主组织", false);
		} else {
			return new CommonResult<Boolean>(true, "用户在【" + d.getDemCode() + "】下存在主组织", true);
		}
	}

	@Override
	@Transactional
	public CommonResult<String> setMaster(String account, String postCode) throws Exception {
		OrgPost post = orgPostService.getByCode(postCode);
		if (BeanUtils.isEmpty(post)) {
			throw new RuntimeException("根据输入的岗位编码没有找到对应的岗位信息");
		}
		User u = userService.getByAccount(account);
		if (BeanUtils.isEmpty(u)) {
			throw new RuntimeException("根据输入的用户帐号没有找到对应的用户");
		}
		OrgUser orgUser = orgUserService.getOrgUser(post.getOrgId(), u.getId(), post.getId());
		if (BeanUtils.isEmpty(orgUser)) {
			throw new RuntimeException("对不起，该用户目前还不是该岗位下的人员！");
		}
		orgUserService.setMaster(orgUser.getId());
		return new CommonResult<String>(true, "操作成功！", "");
	}

	@Override
	public List<OrgTree> getTreeDataByDem(String demCode, String pOrgCode) throws Exception {
		if (StringUtil.isEmpty(demCode)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + ":维度编码demCode必填");
		}
		Demension d = demensionService.getByCode(demCode);
		if (BeanUtils.isEmpty(d)) {
			throw new RuntimeException("根据输入的demCode没有找到对应的维度");
		}
		Org p = this.getByCode(pOrgCode);
		if (StringUtil.isNotEmpty(pOrgCode) && BeanUtils.isEmpty(p)) {
			throw new RuntimeException("根据输入的pOrgCode没有找到组织");
		}
		List<OrgTree> orgTree = new ArrayList<OrgTree>();
		String pId = "0";
		if (BeanUtils.isNotEmpty(p)) {
			pId = p.getId();
		}
		// DefaultQueryFilter filter = new DefaultQueryFilter();
		QueryFilter filter = QueryFilter.build();
		PageBean page = new PageBean();
		page.setPageSize(PageBean.WITHOUT_PAGE);
		filter.setPageBean(page);
		filter.addParams("demId", d.getId());
		// filter.addParamsFilter("parentId", pId);
		List<Org> groupList = this.getByParentAndDem(filter);
		List<Org> rtnList = new ArrayList<Org>();
		getChild(groupList, pId, rtnList);
		for (Org group : rtnList) {
			OrgTree groupTree = new OrgTree(group);
			orgTree.add(groupTree);
		}
		return orgTree;
	}

	@Override
	@Transactional
	public CommonResult<String> setOrgCharge(String account, String orgCode, Boolean isCharge) throws Exception {
		if (StringUtil.isEmpty(account)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + ":用户帐号account必填");
		}
		if (StringUtil.isEmpty(orgCode)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + ":组织编码orgCode必填");
		}
		User u = userService.getByAccount(account);
		Org o = this.getByCode(orgCode);
		if (BeanUtils.isEmpty(u)) {
			throw new RuntimeException("根据输入的用户帐号没有获取到用户！");
		}
		if (BeanUtils.isEmpty(o)) {
			throw new RuntimeException("根据输入的组织编码没有获取到对应组织！");
		}

		List<OrgUser> orgUserList = orgUserService.getListByOrgIdUserId(o.getId(), u.getId());
		if (BeanUtils.isEmpty(orgUserList)) {
			throw new RuntimeException("用户【" + account + "】与组织【" + orgCode + "】不存在关系");
		}
		orgUserService.setCharge(u.getId(), isCharge, o.getId());
		return new CommonResult<String>(true, "操作成功", "");
	}

	@Override
	@Transactional
	public CommonResult<String> addUserUnders(UserUnderVo userUnderObj) throws Exception {
		if (StringUtil.isEmpty(userUnderObj.getUnderAccounts())) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + ":下属用户帐号underAccounts必填");
		}
		if (StringUtil.isEmpty(userUnderObj.getAccount())) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + ":用户帐号account必填");
		}
		if (StringUtil.isEmpty(userUnderObj.getOrgCode())) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + ":组织编码orgCode必填");
		}
		User u = userService.getByAccount(userUnderObj.getAccount());
		if (BeanUtils.isEmpty(u)) {
			throw new RuntimeException("根据输入的account没有找到对应的用户！");
		}
		Org o = this.getByCode(userUnderObj.getOrgCode());
		if (BeanUtils.isEmpty(o)) {
			throw new RuntimeException("根据输入的orgCode没有找到组织！");
		}

		if (BeanUtils.isEmpty(orgUserService.getListByOrgIdUserId(o.getId(), u.getId()))) {
			return new CommonResult<String>(false, "用户【" + u.getFullname() + "】与组织【" + o.getName() + "】不存在关系", "");
		}

		// 添加下属
		String[] underAccounts = userUnderObj.getUnderAccounts().split(",");
		for (String a : underAccounts) {
			User under = userService.getByAccount(a);
			if (BeanUtils.isEmpty(under)) {
				throw new RuntimeException("根据帐号【" + a + "】没有找到对应的用户！");
			}
			if (BeanUtils.isEmpty(orgUserService.getListByOrgIdUserId(o.getId(), under.getId()))) {
				return new CommonResult<String>(false, "用户【" + under.getFullname() + "】与组织【" + o.getName() + "】不存在关系",
						"");
			}
			if (userUnderObj.getAccount().equals(a)) {
				throw new RuntimeException("用户【" + a + "】不能将自己添加为自己的下属！");
			}

			Map<String, Object> m = new HashMap<String, Object>();
			m.put("userId", under.getId());
			m.put("orgId", o.getId());
			m.put("underUserId", u.getId());
			List<UserUnder> list = userUnderService.getUserUnder(m);// 判断是否设置互为上下级
			if (BeanUtils.isNotEmpty(list)) {
				throw new RuntimeException(
						"用户【" + under.getAccount() + "】在组织【" + o.getCode() + "】下是用户【" + u.getAccount() + "】的上级");
			}

			Map<String, Object> m1 = new HashMap<String, Object>();
			m1.put("noUserId", u.getId());
			m1.put("orgId", o.getId());
			m1.put("underUserId", under.getId());
			List<UserUnder> list1 = userUnderService.getUserUnder(m1);// 获取该组织下，不是当前上级用户的数据
			if (BeanUtils.isNotEmpty(list1)) {// 同一组织下，用户只能有一个上级
				User supperUser = userService.get(list1.get(0).getUserId());
				throw new RuntimeException(
						"用户【" + a + "】在当前组织中已有上级" + "【" + supperUser.getFullname() + "】，在当前组织中不能再设置其他上级。");
			} else {
				Map<String, Object> m2 = new HashMap<String, Object>();
				m2.put("userId", u.getId());
				m2.put("orgId", o.getId());
				m2.put("underUserId", under.getId());
				List<UserUnder> list2 = userUnderService.getUserUnder(m2);// 获取该组织下，是当前上级用户的数据
				if (BeanUtils.isNotEmpty(list2)) {//
					continue;
				} else {
					UserUnder userUnder = new UserUnder();
					userUnder.setId(UniqueIdUtil.getSuid());
					userUnder.setUserId(u.getId());
					userUnder.setUnderUserId(under.getId());
					userUnder.setUnderUserName(under.getFullname());
					userUnder.setOrgId(o.getId());
					userUnderService.create(userUnder);
				}
			}
		}
		return new CommonResult<String>(true, "添加下属成功！", "");
	}

	@Override
	@Transactional
	public CommonResult<String> delUserUnders(String account, String orgCode) throws Exception {
		if (StringUtil.isEmpty(account)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + ":用户帐号account必填");
		}
		if (StringUtil.isEmpty(orgCode)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + ":组织编码orgCode必填");
		}
		User u = userService.getByAccount(account);
		if (BeanUtils.isEmpty(u)) {
			throw new RuntimeException("根据输入的account没有找到对应的用户！");
		}
		Org o = this.getByCode(orgCode);
		if (BeanUtils.isEmpty(o)) {
			throw new RuntimeException("根据输入的orgCode没有找到组织！");
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", u.getId());
		params.put("orgId", o.getId());
		List<UserUnder> l = userUnderService.getUserUnder(params);
		if (BeanUtils.isEmpty(l)) {
			return new CommonResult<String>(false, "用户【" + u.getFullname() + "】在组织【" + o.getName() + "】下没有下级", "");
		}
		userUnderService.delByUserIdAndOrgId(u.getId(), o.getId());
		return new CommonResult<String>(true, "删除成功！", "");
	}

	@Override
	public List<UserVo> getUserUnders(String account, String orgCode) throws Exception {
		if (StringUtil.isEmpty(account)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + ":用户帐号account必填");
		}
		if (StringUtil.isEmpty(orgCode)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + ":组织编码orgCode必填");
		}
		User u = userService.getByAccount(account);
		if (BeanUtils.isEmpty(u)) {
			throw new RuntimeException("根据输入的account没有找到对应的用户！");
		}
		Org o = this.getByCode(orgCode);
		if (BeanUtils.isEmpty(o)) {
			throw new RuntimeException("根据输入的orgCode没有找到组织！");
		}
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("userId", u.getId());
		m.put("orgId", o.getId());
		List<UserUnder> list = userUnderService.getUserUnder(m);
		List<User> userList = new ArrayList<User>();
		for (UserUnder under : list) {
			User user = userService.get(under.getUnderUserId());
			userList.add(user);
		}
		return OrgUtil.convertToUserVoList(userList);
	}

	@Override
	@Transactional
	public CommonResult<String> saveOrgAuth(OrgAuthVo orgAuthVo) throws Exception {
		if (StringUtil.isEmpty(orgAuthVo.getAccount())) {
			throw new RequiredException(HotentHttpStatus.REUIRED.description() + "：用户帐号必填！");
		}
		User u = userService.getByAccount(orgAuthVo.getAccount());
		if (BeanUtils.isEmpty(u)) {
			throw new RuntimeException("没有找到对应的用户！");
		}
		if (StringUtil.isEmpty(orgAuthVo.getOrgCode())) {
			throw new RequiredException(HotentHttpStatus.REUIRED.description() + "：组织代码必填！");
		}
		Org o = this.getByCode(orgAuthVo.getOrgCode());
		if (BeanUtils.isEmpty(o)) {
			throw new RuntimeException("没有找到对应的组织！");
		}
		if (StringUtil.isEmpty(orgAuthVo.getDemCode())) {
			throw new RequiredException(HotentHttpStatus.REUIRED.description() + "：维度编码必填！");
		}
		Demension d = demensionService.getByCode(orgAuthVo.getDemCode());
		if (BeanUtils.isEmpty(d)) {
			throw new RuntimeException("没有找到对应的组织维度！");
		}
		if (!o.getDemId().equals(d.getId())) {
			throw new RuntimeException("输入的组织所对应的维度与输入的维度不一致！");
		}
		if (StringUtil.isEmpty(orgAuthVo.getId())) {
			OrgAuth a = orgAuthService.getByOrgIdAndUserId(o.getId(), u.getId());
			if (BeanUtils.isNotEmpty(a)) {
				throw new RuntimeException("用户在该组织已经是分级管理员！");
			}
		} else {
			List<OrgAuth> list = orgAuthService.getListByOrgIdAndUserId(o.getId(), u.getId());
			if (list != null && list.size() > 1) {
				throw new RuntimeException("用户在该组织已经是分级管理员！");
			}
		}

		OrgAuth auth = new OrgAuth();
		if (StringUtil.isEmpty(orgAuthVo.getId())) {
			auth.setId(UniqueIdUtil.getSuid());
			auth.setOrgId(o.getId());
			auth.setUserId(u.getId());
			auth.setOrgPerms(orgAuthVo.getOrgPerms());
			auth.setUserPerms(orgAuthVo.getUserPerms());
			auth.setPosPerms(orgAuthVo.getPosPerms());
			auth.setOrgauthPerms(orgAuthVo.getOrgauthPerms());
			auth.setLayoutPerms(orgAuthVo.getLayoutPerms());
			auth.setDemId(d.getId());
			auth.setRolePerms(orgAuthVo.getRolePerms());
			auth.setRoleConfig(orgAuthVo.getRoleConfig());
			orgAuthService.create(auth);
			return new CommonResult<String>(true, "添加分级管理成功！", "");
		} else {
			auth.setId(orgAuthVo.getId());
			auth.setOrgId(o.getId());
			auth.setUserId(u.getId());
			auth.setOrgPerms(orgAuthVo.getOrgPerms());
			auth.setUserPerms(orgAuthVo.getUserPerms());
			auth.setPosPerms(orgAuthVo.getPosPerms());
			auth.setOrgauthPerms(orgAuthVo.getOrgauthPerms());
			auth.setLayoutPerms(orgAuthVo.getLayoutPerms());
			auth.setDemId(d.getId());
			auth.setRolePerms(orgAuthVo.getRolePerms());
			auth.setRoleConfig(orgAuthVo.getRoleConfig());
			orgAuthService.update(auth);
			return new CommonResult<String>(true, "更新分级管理成功！", "");
		}

	}

	@Override
	@Transactional
	public CommonResult<String> deleteOrgAuth(String ids) throws Exception {
		if (StringUtil.isEmpty(ids)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + ":分级组织管理id必填");
		}
		String[] idArr = ids.split(",");
		for (String id : idArr) {
			if (BeanUtils.isEmpty(orgAuthService.get(id))) {
				throw new RuntimeException("根据输入的分级组织管理id没有找到对应数据！");
			}
			orgAuthService.remove(id);
		}
		return new CommonResult<String>(true, "删除成功！", "");
	}

	@Override
	public Page<OrgAuth> getOrgAuthList(String account, String orgCode, String demCode) throws Exception {
		if (StringUtil.isEmpty(account)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + ":用户帐号account必填");
		}
		User u = userService.getByAccount(account);
		if (BeanUtils.isEmpty(u)) {
			throw new RuntimeException("根据输入的用户帐号没有找到对应的用户！");
		}
		Org o = null;
		if (StringUtil.isNotEmpty(orgCode)) {
			o = this.getByCode(orgCode);
		}
		if (StringUtil.isNotEmpty(orgCode) && BeanUtils.isEmpty(o)) {
			throw new RuntimeException("根据输入的组织代码没有找到对应的组织！");
		}
		Demension de = null;
		if (StringUtil.isNotEmpty(demCode)) {
			de = demensionService.getByCode(demCode);
		}
		if (StringUtil.isNotEmpty(demCode) && BeanUtils.isEmpty(de)) {
			throw new RuntimeException("根据输入的维度编码没有找到对应的维度！");
		}
		QueryFilter filter = QueryFilter.build();
		filter.addParams("userId", u.getId());
		if (BeanUtils.isNotEmpty(o)) {
			filter.addParams("orgId", o.getId());
		}
		if (BeanUtils.isNotEmpty(de)) {
			filter.addParams("demId", de.getId());
		}
		Page<OrgAuth> list = (Page<OrgAuth>) orgAuthService.getAllOrgAuth(filter);
		return list;
	}

	@Override
	public OrgAuth getOrgAuth(String id) throws Exception {
		if (StringUtil.isEmpty(id)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + ":分级组织管理id必填");
		}
		if (BeanUtils.isEmpty(orgAuthService.get(id))) {
			throw new RuntimeException("根据输入的id数据没有找到对应的信息");
		}
		OrgAuth orgAuth = orgAuthService.get(id);
		User user = userService.get(orgAuth.getUserId());
		orgAuth.setUserName(user.getFullname());
		orgAuth.setUserAccount(user.getAccount());
		return orgAuth;
	}

	@Override
	public List<Org> getUserOrgs(String account, String demCode, Boolean isMain) throws Exception {
		if (StringUtil.isEmpty(account)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + ":用户帐号account必填");
		}
		User u = userService.getByAccount(account);
		if (BeanUtils.isEmpty(u)) {
			throw new RuntimeException("根据输入的用户帐号没有找到对应的用户！");
		}
		Demension de = null;
		if (StringUtil.isNotEmpty(demCode)) {
			de = demensionService.getByCode(demCode);
		}
		if (StringUtil.isNotEmpty(demCode) && BeanUtils.isEmpty(de)) {
			throw new RuntimeException("根据输入的维度编码没有找到对应的维度！");
		}
		List<Org> list = null;
		String demId = null;
		if (BeanUtils.isNotEmpty(de)) {
			demId = de.getId();
		}
		if (BeanUtils.isEmpty(isMain)) {
			list = this.getUserOrg(u.getId(), demId, null);
		} else {
			list = this.getUserOrg(u.getId(), demId, isMain);
		}
		return list;
	}

	@Override
	public List<UserVo> getUsersByOrgCodes(String orgCodes, Boolean isMain) throws Exception {
		if (StringUtil.isEmpty(orgCodes)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "组织代码orgCodes必填！");
		}
		List<User> list = new ArrayList<User>();
		String[] orgCodeArr = orgCodes.split(",");
		for (String orgCode : orgCodeArr) {
			Org o = this.getByCode(orgCode);
			if (BeanUtils.isEmpty(o)) {
				throw new RuntimeException("根据组织代码【" + orgCode + "】没有找到对应的组织信息！");
			}
			List<User> l = userService.getOrgUsers(o.getId(), isMain);
			if (BeanUtils.isNotEmpty(l)) {
				list.addAll(l);
			}
		}
		return OrgUtil.convertToUserVoList(list);
	}

	@Override
	public List<User> getUsersByOrgIds(Collection<String> orgIds, boolean isMain) {
		if (BeanUtils.isEmpty(orgIds)) {
			return new ArrayList<>();
		}
		return baseMapper.getUsersByOrgIds(orgIds, isMain);
	}

	@Override
	public List<OrgPost> getPostsByOrgCodes(String orgCodes, Boolean isMain) throws Exception {
		if (StringUtil.isEmpty(orgCodes)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "组织代码orgCodes必填！");
		}
		List<OrgPost> list = new ArrayList<OrgPost>();
		String[] orgCodeArr = orgCodes.split(",");
		for (String orgCode : orgCodeArr) {
			Org o = this.getByCode(orgCode);
			if (BeanUtils.isEmpty(o)) {
				throw new RuntimeException("根据组织代码【" + orgCode + "】没有找到对应的组织信息！");
			}
			List<OrgPost> l = orgPostService.getRelCharge(o.getId(), isMain);
			if (BeanUtils.isNotEmpty(l)) {
				list.addAll(l);
			}
		}
		return list;
	}

	@Override
	public List<Org> getByLevel(String level, String demCode) throws Exception {
		if (StringUtil.isEmpty(level)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "组织级别level必填！");
		}
		Demension d = null;
		if (StringUtil.isNotEmpty(demCode)) {
			d = demensionService.getByCode(demCode);
		}
		if (StringUtil.isNotEmpty(demCode) && BeanUtils.isEmpty(d)) {
			throw new RuntimeException("根据输入的输入的维度编码demCode没有找到对应的维度！");
		}
		QueryFilter filter = QueryFilter.build();
		//filter.setClazz(Org.class);
		filter.addParams("grade_", level);
		if (BeanUtils.isNotEmpty(d)) {
			filter.addParams("dem_id_", d.getId());
		}
		return this.query(filter).getRows();
	}

	@Override
	@Transactional
	public CommonResult<String> saveUserPost(String accounts, String postCode) throws Exception {
		if (StringUtil.isEmpty(accounts)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "用户帐号accounts必填！");
		}
		if (StringUtil.isEmpty(postCode)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "岗位代码postCode必填！");
		}
		String[] postCodeArr = postCode.split(",");
		String[] accountArr = accounts.split(",");
		for(String str : postCodeArr) {
			OrgPost post = orgPostService.getByCode(str);
			if (BeanUtils.isEmpty(post)) {
				throw new RuntimeException("根据输入岗位代码没有找到对应的岗位信息！");
			}
			Org org = this.get(post.getOrgId());
			if(postCode.indexOf(",") < 0) {
				if (org.getExceedLimitNum() == 1 && org.getLimitNum() != 0) {
					Map<String, Object> map = new HashMap<>();
					map.put("orgCode", org.getCode());
					map.put("group", "true");
					List<Map<String, Object>> list = orgUserService.getUserNumByOrgCode(map);
					if (org.getLimitNum() < list.size() + accountArr.length) {
						return new CommonResult<String>(false, "人数超出组织上限，不予添加", null);
					}
				}
			}
			for (String account : accountArr) {
				User u = userService.getByAccount(account);
				if (BeanUtils.isEmpty(u)) {
					throw new RuntimeException("根据输入的用户帐号【" + account + "】没有找到对应的用户");
				}
				OrgUser ou = orgUserService.getOrgUser(post.getOrgId(), u.getId(), post.getId());
				if (BeanUtils.isNotEmpty(ou)) {
					continue;
				}
				ou = orgUserService.getOrgUser(post.getOrgId(), u.getId(), "");
				if (BeanUtils.isNotEmpty(ou)) {
					ou.setDemId(org.getDemId());
					ou.setRelId(post.getId());
					userService.removeUserGroupsCache(u.getId());
				} else {
					ou = new OrgUser();
					ou.setId(UniqueIdUtil.getSuid());
					ou.setUserId(u.getId());
					ou.setIsCharge(0);
					ou.setIsMaster(0);
					ou.setIsRelActive(1);
					ou.setOrgId(post.getOrgId());
					ou.setDemId(org.getDemId());
					ou.setRelId(post.getId());
					userService.removeUserGroupsCache(u.getId());
				}
				List<OrgUser> l = orgUserService.getOrgUserMaster(u.getId(), org.getDemId());
				//当前维度无主组织，则将该岗位所属组织设置为主组织
				if (BeanUtils.isEmpty(l)) {
					ou.setIsMaster(1);
				}
				orgUserService.saveOrUpdate(ou);
			}
		}
		return new CommonResult<String>(true, "添加成功", "");
	}

	@Override
	@Transactional
	public CommonResult<String> saveUserPosts(String account, String postCodes) throws Exception {

		if (StringUtil.isEmpty(account)) {
			throw new BaseException(HotentHttpStatus.REUIRED.description() + "用户帐号accounts必填！");
		}
		if (StringUtil.isEmpty(postCodes)) {
			throw new BaseException(HotentHttpStatus.REUIRED.description() + "岗位代码postCode必填！");
		}
		String[] postCodesArr = postCodes.split(",");

		for (String postCode : postCodesArr) {
			OrgPost post = orgPostService.getByCode(postCode);
			if (BeanUtils.isEmpty(post)) {
				throw new BaseException("根据输入岗位代码没有找到对应的岗位信息！");
			}
			Org org = this.get(post.getOrgId());
			if (org.getExceedLimitNum() == 1 && org.getLimitNum() != 0) {
				Map<String, Object> map = new HashMap<>();
				map.put("orgCode", org.getCode());
				map.put("group", "true");
				List<Map<String, Object>> list = orgUserService.getUserNumByOrgCode(map);
				if (org.getLimitNum() <= list.size()) {
					return new CommonResult<String>(false, org.getName()+"人数超出上限，不予添加！请重新选择", null);
				}
			}
			User u = userService.getByAccount(account);
			if (BeanUtils.isEmpty(u)) {
				throw new BaseException("根据输入的用户帐号【" + account + "】没有找到对应的用户");
			}
			OrgUser ou = orgUserService.getOrgUser(post.getOrgId(), u.getId(), post.getId());
			if (BeanUtils.isNotEmpty(ou)) {
				throw new BaseException("当前用户已在【"+post.getName()+"】的岗位上！");
			}

			QueryWrapper<OrgUser> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("ORG_ID_",post.getOrgId());
			queryWrapper.eq("USER_ID_",u.getId());
			List<Map<String, Object>> list = orgUserService.listMaps(queryWrapper);
			for (int i = 0; i < list.size(); i++) {
				if(!BeanUtils.isEmpty(MapUtil.getIgnoreCase(list.get(i), "relId"))){
					delOrgUser(MapUtil.getIgnoreCase(list.get(i), "relId").toString());
					break;
				}
			}

			ou = orgUserService.getOrgUser(post.getOrgId(), u.getId(), "");
			if (BeanUtils.isNotEmpty(ou)) {
				ou.setDemId(org.getDemId());
				ou.setRelId(post.getId());
				userService.removeUserGroupsCache(u.getId());
			} else {
				ou = new OrgUser();
				ou.setId(UniqueIdUtil.getSuid());
				ou.setUserId(u.getId());
				ou.setIsCharge(0);
				ou.setIsMaster(0);
				ou.setIsRelActive(1);
				ou.setOrgId(post.getOrgId());
				ou.setDemId(org.getDemId());
				ou.setRelId(post.getId());
				userService.removeUserGroupsCache(u.getId());
			}
			List<OrgUser> l = orgUserService.getOrgUserMaster(u.getId(), org.getDemId());
			//当前维度无主组织，则将该岗位所属组织设置为主组织
			if (BeanUtils.isEmpty(l)) {
				ou.setIsMaster(1);
			}
			orgUserService.saveOrUpdate(ou);
			userService.removeUserGroupsCache(u.getId());
		}
		return new CommonResult<String>(true, "添加成功", "");

	}

	@Override
	@Transactional
	public CommonResult<String> delUserPost(String accounts, String postCode) throws Exception {
		if (StringUtil.isEmpty(accounts)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "用户帐号accounts必填！");
		}
		if (StringUtil.isEmpty(postCode)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "岗位代码postCode必填！");
		}
		OrgPost post = orgPostService.getByCode(postCode);
		if (BeanUtils.isEmpty(post)) {
			throw new RuntimeException("根据输入岗位代码没有找到对应的岗位信息！");
		}
		String[] accountArr = accounts.split(",");
		for (String account : accountArr) {
			User u = userService.getByAccount(account);
			if (BeanUtils.isEmpty(u)) {
				throw new RuntimeException("根据输入的用户帐号【" + account + "】没有找到对应的用户");
			}
			OrgUser ou = orgUserService.getOrgUser(post.getOrgId(), u.getId(), post.getId());
			if (BeanUtils.isEmpty(ou)) {
				// continue;
				throw new RuntimeException("用户【" + account + "】不在岗位【" + post.getCode() + "】下");
			}
			orgUserService.remove(ou.getId());
			userService.removeUserGroupsCache(u.getId());
		}
		return new CommonResult<String>(true, "删除成功", "");
	}

	@Override
	@Transactional
	public CommonResult<String> saveOrgPost(OrgPostVo orgPostVo) throws Exception {
		if (StringUtil.isEmpty(orgPostVo.getCode())) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "岗位代码code必填！");
		}
		if (orgPostVo.getCode().contains(",")) {
			throw new RuntimeException("添加岗位失败，岗位编码不允许含英文逗号‘,’");
		}
		if (StringUtil.isEmpty(orgPostVo.getName())) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "岗位名称name必填！");
		}
		if (StringUtil.isEmpty(orgPostVo.getJobCode())) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "职务代码jobCode必填！");
		}
		if (StringUtil.isEmpty(orgPostVo.getOrgCode())) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "组织代码orgCode必填！");
		}
		Org o = this.getByCode(orgPostVo.getOrgCode());
		if (BeanUtils.isEmpty(o)) {
			throw new RuntimeException("根据输入的组织代码没有找到对应的组织信息！");
		}
		OrgJob job = orgJobService.getByCode(orgPostVo.getJobCode());
		if (BeanUtils.isEmpty(job)) {
			throw new RuntimeException("根据输入的职务编码没有找到对应的职务信息！");
		}
		if (orgPostService.getCountByCode(orgPostVo.getCode())>0) {
			throw new RuntimeException("岗位编码【" + orgPostVo.getCode() + "】已经存在系统中！");
		}

		OrgPost rel = new OrgPost();
		rel.setId(UniqueIdUtil.getSuid());
		rel.setName(orgPostVo.getName());
		rel.setCode(orgPostVo.getCode());
		rel.setRelDefId(job.getId());
		rel.setOrgId(o.getId());
		rel.setIsCharge(orgPostVo.getIsCharge());
		if (orgPostVo.getIsCharge() == 1) {
			List<OrgPost> l = orgPostService.getRelCharge(o.getId(), true);
			if (BeanUtils.isNotEmpty(l)) {
				OrgPost p = l.get(0);
				p.setIsCharge(0);
				orgPostService.update(p);
			}
		}

		orgPostService.create(rel);
		return new CommonResult<String>(true, "添加岗位成功！", "");
	}

	@Override
	@Transactional
	public CommonResult<String> deleteOrgPost(String postCodes) throws Exception {
		if (StringUtil.isEmpty(postCodes)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "岗位编码postCodes必填！");
		}
		String[] codeArr = postCodes.split(",");
		for (String code : codeArr) {
			OrgPost rel = orgPostService.getByCode(code);
			if (BeanUtils.isEmpty(rel)) {
				throw new RuntimeException("根据输入的岗位编码【" + code + "】没有找到对应的岗位信息！");
			}

			//判断岗位组是否存在人员
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("orgId", rel.getOrgId());
			map.put("relId", rel.getId());

			List<OrgUser> orgUsers = orgUserService.getByParms(map);
			if(BeanUtils.isNotEmpty(orgUsers)) {
				throw new RuntimeException("岗位【" + rel.getName() + "】下还存在分配用户，请删除用户在进行操作！");
			}
			// if (OrgUtil.checkUserGruopIsUserRel("pos", rel.getId())) {
			// throw new RuntimeException("编码为【"+code+"】的岗位为汇报节点不能删除！");
			// }
			String[] ids = { rel.getId() };
			orgPostService.removeByIds(ids);
		}
		return new CommonResult<String>(true, "删除岗位成功", "");
	}

	@Override
	@Transactional
	public CommonResult<String> setPostMaster(String postCode, Boolean isMain) throws Exception {
		if (StringUtil.isEmpty(postCode)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "岗位编码postCode必填！");
		}
		if (BeanUtils.isEmpty(isMain)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "是否责任岗位isMain必填！");
		}
		OrgPost post = orgPostService.getByCode(postCode);
		if (BeanUtils.isEmpty(post)) {
			throw new RuntimeException("根据输入的岗位编码没有找到对应的岗位！");
		}
		if (isMain) {// 若为设置责任岗位，那么先将该组织中的责任岗位取消再设置
			orgPostService.cancelRelCharge(post.getOrgId());
		}
		orgPostService.setRelCharge(post.getId(), isMain);
		return new CommonResult<String>(true, "设置成功！", "");
	}

	@Override
	@Transactional
	public CommonResult<String> setUserPostDueTime(PostDueVo postDueVo) throws Exception {
		if (StringUtil.isEmpty(postDueVo.getCode())) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "岗位编码code必填！");
		}
		if (StringUtil.isEmpty(postDueVo.getAccount())) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "用户帐号account必填！");
		}
		if (BeanUtils.isEmpty(postDueVo.getEndDate()) && BeanUtils.isEmpty(postDueVo.getStartDate())) {
			throw new RuntimeException("开始时间和结束时间至少填写一个！");
		}
		OrgPost post = orgPostService.getByCode(postDueVo.getCode());
		if (BeanUtils.isEmpty(post)) {
			throw new RuntimeException("根据输入的岗位编码没有找到对应的岗位信息！");
		}
		User u = userService.getByAccount(postDueVo.getAccount());
		if (BeanUtils.isEmpty(u)) {
			throw new RuntimeException("根据输入的用户帐号没有找到对应的用户信息！");
		}
		OrgUser orgUser = orgUserService.getOrgUser(post.getOrgId(), u.getId(), post.getId());
		if (BeanUtils.isEmpty(orgUser)) {
			throw new RuntimeException("用户与该岗位没关系，不能设置！");
		}
		if (StringUtil.isNotEmpty(postDueVo.getStartDate()) && StringUtil.isNotEmpty(postDueVo.getEndDate())) {
			LocalDateTime startDate = DateFormatUtil.parse(postDueVo.getStartDate());
			LocalDateTime endDate = DateFormatUtil.parse(postDueVo.getEndDate());
			if (DateUtil.getTime(startDate, endDate) < 0) {
				throw new RuntimeException("开始时间不能大于结束时间！");
			}
		}
		if (StringUtil.isNotEmpty(postDueVo.getStartDate())) {
			orgUser.setStartDate(DateFormatUtil.parse(postDueVo.getStartDate()));
		} else {
			orgUser.setStartDate(null);
		}
		if (StringUtil.isNotEmpty(postDueVo.getEndDate())) {
			orgUser.setEndDate(DateFormatUtil.parse(postDueVo.getEndDate()));
		} else {
			orgUser.setEndDate(null);
		}
		orgUserService.update(orgUser);
		return new CommonResult<String>(true, "设置成功！", "");
	}

	@Override
	@Transactional
	public CommonResult<String> validOrgUser() throws Exception {
		orgUserService.syncValidOrgUser();
		return new CommonResult<String>(true, "校验成功！", "");
	}

	@Override
	@Transactional
	public CommonResult<String> addOrgRole(OrgRoleVo orgRoleVo) throws Exception {
		if (StringUtil.isEmpty(orgRoleVo.getOrgCode())) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "组织编码orgCode必填！");
		}
		Org org = this.getByCode(orgRoleVo.getOrgCode());
		if (BeanUtils.isEmpty(org)) {
			throw new RuntimeException("根据输入的组织编码，没有找到对应的组织信息！");
		}
		if (StringUtil.isEmpty(orgRoleVo.getRoleCodes())) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "角色编码roleCodes必填！");
		}
		String[] roleCodes = orgRoleVo.getRoleCodes().split(",");
		for (String rCode : roleCodes) {
			Role r = roleService.getByAlias(rCode);

			if (BeanUtils.isEmpty(r)) {
				r = roleService.get(rCode);
				if (BeanUtils.isEmpty(r))
					throw new RuntimeException("根据输入的角色编码，没有找到对应的角色信息！");
			}
			if (orgRoleVo.getIsInherit() > 0) {
				orgRoleService.addOrgRole(org.getId(), r, 1);
			} else {
				orgRoleService.addOrgRole(org.getId(), r, 0);
			}
		}

		return new CommonResult<String>(true, "保存成功", "");
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveRoleOrg(RoleOrgVo vo) {
		Assert.notNull(vo.getRoleId(), "角色ID不能为空");
		Assert.notEmpty(vo.getOrgIds(), "组织id不能为空");
		List<OrgRole> orgRoles = new ArrayList<>();
		Role role = roleService.getById(vo.getRoleId());
		if (BeanUtils.isEmpty(role)) {
			throw new BaseException(String.format("根据角色ID【%s】,找不到对应角色", vo.getRoleId()));
		}
		CacheManager cacheManager = AppUtil.getBean(CacheManager.class);
		Collection<ICache> caches = cacheManager.getCache(CacheKeyConst.EIP_UC_ORG_ROLE);
		for (String orgId : vo.getOrgIds()) {
			Org org = this.getById(orgId);
			if (BeanUtils.isEmpty(org)) {
				throw new BaseException(String.format("根据组织ID【%s】，找不到对应组织", orgId));
			}
			OrgRole or = new OrgRole();
			or.setIsInherit(0);
			or.setOrgId(orgId);
			or.setRoleId(vo.getRoleId());
			orgRoles.add(or);
			for (ICache cach : caches) {
				cach.evict(orgId);
			}
			this.removeUserMenuByOrgId(orgId);
		}
		QueryWrapper<OrgRole> deleteQueryWrapper = new QueryWrapper<>();
		deleteQueryWrapper.eq("ROLE_ID_", vo.getRoleId()).in("ORG_ID_", vo.getOrgIds());
		orgRoleManager.remove(deleteQueryWrapper);
		orgRoleManager.saveBatch(orgRoles);
	}

	@Override
	@Transactional
	public void delOrgRoleByCode(String orgCode, String roleCodes) throws Exception {
		if (StringUtil.isEmpty(orgCode)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "组织编码orgCode必填！");
		}
		Org org = this.getByCode(orgCode);
		if (BeanUtils.isEmpty(org)) {
			throw new RuntimeException("根据输入的组织编码，没有找到对应的组织信息！");
		}
		if (StringUtil.isEmpty(roleCodes)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "角色编码roleCodes必填！");
		}
		String[] roleCodeArr = roleCodes.split(",");
		for (String rCode : roleCodeArr) {
			Role r = roleService.getByAlias(rCode);
			if (BeanUtils.isEmpty(r)) {
				throw new RuntimeException("根据输入的角色编码，没有找到对应的角色信息！");
			}
			orgRoleService.delByOrgIdAndRoleId(org.getId(), r.getId());
		}
	}

	@Override
	@Transactional
	public CommonResult<String> delOrgRoleById(String ids) throws Exception {
		if (StringUtil.isEmpty(ids)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "组织角色ID必填！");
		}
		String[] roleId = ids.split(",");
		for (String id : roleId) {
			orgRoleService.remove(id);
		}
		return new CommonResult<String>(true, "删除成功", "");
	}

	@Override
	@Transactional
	public void delAllOrgRole(String orgCode) throws Exception {
		if (StringUtil.isEmpty(orgCode)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "组织编码orgCode必填！");
		}
		Org org = this.getByCode(orgCode);
		if (BeanUtils.isEmpty(org)) {
			throw new RuntimeException("根据输入的组织编码，没有找到对应的组织信息！");
		}
		orgRoleService.delByOrgIdAndRoleId(org.getId(), null);
	}

	@Override
	public List<Role> getOrgRoleByCode(String orgCode) throws Exception {
		if (StringUtil.isEmpty(orgCode)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "组织编码orgCode必填！");
		}
		Org org = this.getByCode(orgCode);
		if (BeanUtils.isEmpty(org)) {
			throw new RuntimeException("根据输入的组织编码，没有找到对应的组织信息！");
		}
		return getRolesByOrgId(org.getId());
	}

	public List<Role> getRolesByOrgId(String orgId) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("orgId", orgId);
		List<Role> roleList = roleService.getOrgRoleList(map);// 获取自身所拥有角色
		// 根据组织id获取。
		if (BeanUtils.isNotEmpty(roleList))
			return roleList;
		// 沿着路径往上查找。
		roleList = new ArrayList<Role>();
		String path = getPathByOrgId(orgId);
		if (StringUtil.isEmpty(path))
			return roleList;
		String[] aryPath = path.split("[.]");
		// 从后往前找。
		for (int i = aryPath.length - 1; i >= 0; i--) {
			String tmpOrgId = aryPath[i];
			Map<String, Object> m = new HashMap<String, Object>();
			m.put("orgId", tmpOrgId);
			m.put("isInherit", 1);
			roleList = roleService.getOrgRoleList(m);// 获取父组织可继承的角色
			// 如果找到了则停止循环。
			if (BeanUtils.isNotEmpty(roleList)) {
				break;
			}
		}
		return roleList;
	}

	/**
	 * 根据组织ID获取组织路径。
	 *
	 * @param orgId
	 *            组织ID。
	 * @return
	 */
	private String getPathByOrgId(String orgId) {
		Org sysOrg = this.get(orgId);
		if (sysOrg == null)
			return "";
		String path = sysOrg.getPath();
		if (StringUtil.isEmpty(path))
			return "";
		// 去掉当前Id。
		path = path.replace("." + orgId + ".", "");
		// 去掉维度Id。
		int pos = path.indexOf(".");
		path = path.substring(pos + 1);
		return path;
	}

	@Override
	@Transactional
	public CommonResult<String> updateOrgPost(OrgPostVo postVo) throws Exception {
		if(StringUtils.isEmpty(postVo.getCode())){
			return new CommonResult<String>(false, "岗位编码必填", "");
		}
		if(StringUtils.isEmpty(postVo.getName())){
			return new CommonResult<String>(false, "岗位名称必填", "");
		}
		OrgPost p = orgPostService.getByCode(postVo.getCode());
		if(BeanUtils.isEmpty(p)){
			return new CommonResult<String>(false, "根据输入的编码没有找到对应的岗位", "");
		}
		if (StringUtil.isNotEmpty(postVo.getOrgCode())){
			Org o = this.getByCode(postVo.getOrgCode());
			//岗位所属组织发生了变化，
			if (!p.getOrgId().equals(o.getId())) {
				p.setOrgId(o.getId());
				//判断新组织是否有限编
				if (o.getExceedLimitNum() ==1 && o.getLimitNum()!=0 ){
					Map<String, Object> map = new HashMap<>();
					map.put("orgCode", o.getCode());
					map.put("group", "true");
					//获取新组织已有人数
					List<Map<String, Object>> list = orgUserService.getUserNumByOrgCode(map);
					if (o.getLimitNum() <= list.size() ){
						return new CommonResult<String>(false,"岗位组织所属人数超出上限，修改失败",null);
					}else {
						Set<String> userIds= new HashSet<>();
						for (Map<String, Object> l : list) {
							userIds.add((String)l.get("userId"));
						}
						//查询当前岗位下的人数
						QueryFilter queryFilter = QueryFilter.build().withPage(new PageBean(1,PageBean.WITHOUT_PAGE));
						queryFilter.addFilter("pos_id_", p.getId(), QueryOP.EQUAL);
						IPage<HashMap<String, Object>> userByGroup = orgUserService.getUserByGroup(queryFilter);
						//List<Map<String, Object>> userByGroup = orgUserService.getUserByGroup(queryFilter);
						Set<String> addUserIds= new HashSet<>();
						if (BeanUtils.isNotEmpty(userByGroup)) {
							for (Map<String, Object> orgUser : userByGroup.getRecords()) {
								if (!userIds.contains(orgUser.get("userId"))) {
									addUserIds.add((String)orgUser.get("userId"));
								}
							}
						}
						if (o.getLimitNum() <= (list.size()+addUserIds.size())) {
							return new CommonResult<String>(false,"岗位所属组织人数超出上限，修改失败",null);
						}
					}
				}
				orgUserService.updateUserOrgByPostId(p.getId(), p.getOrgId());
			}
		}

		if(postVo.getIsCharge() == 1){
			p.setIsCharge(1);
			this.setPostMaster(p.getCode(), true);
		}

		p.setName(postVo.getName());
		if(StringUtil.isNotEmpty(postVo.getJobCode())){
			OrgJob byCode = orgJobService.getByCode(postVo.getJobCode());
			p.setRelDefId(byCode.getId());
		}
		orgPostService.update(p);
		return new CommonResult<String>(true, "更新成功", "");
	}

	@Override
	@Transactional
	public CommonResult<String> setUnderUsers(String orgId, String account, String underAccounts) throws Exception {
		User u = userService.getByAccount(account);
		Org o = this.get(orgId);
		// 添加下属
		String[] underAccountArr = underAccounts.split(",");
		for (String a : underAccountArr) {
			User under = userService.getByAccount(a);
			if (BeanUtils.isEmpty(under)) {
				throw new BaseException("根据帐号【" + a + "】没有找到对应的用户！");
			}
			if (account.equals(a)) {
				throw new BaseException("用户【" + under.getFullname() + "】不能将自己添加为自己的下属！");
			}

			Map<String, Object> m = new HashMap<String, Object>();
			m.put("userId", under.getId());
			m.put("orgId", o.getId());
			m.put("underUserId", u.getId());
			List<UserUnder> list = userUnderService.getUserUnder(m);// 判断是否设置互为上下级
			if (BeanUtils.isNotEmpty(list)) {
				throw new BaseException(
						"用户【" + under.getFullname() + "】在组织【" + o.getCode() + "】下是用户【" + u.getFullname() + "】的上级");
			}

			Map<String, Object> m1 = new HashMap<String, Object>();
			m1.put("noUserId", u.getId());
			m1.put("orgId", o.getId());
			m1.put("underUserId", under.getId());
			List<UserUnder> list1 = userUnderService.getUserUnder(m1);// 获取该组织下，不是当前上级用户的数据
			if (BeanUtils.isNotEmpty(list1)) {// 同一组织下，用户只能有一个上级
				User supperUser = userService.get(list1.get(0).getUserId());
				throw new BaseException("用户【" + under.getFullname() + "】在当前组织中已有上级" + "【" + supperUser.getFullname()
						+ "】，在当前组织中不能再设置其他上级。");
			} else {
				Map<String, Object> m2 = new HashMap<String, Object>();
				m2.put("userId", u.getId());
				m2.put("orgId", o.getId());
				m2.put("underUserId", under.getId());
				List<UserUnder> list2 = userUnderService.getUserUnder(m2);// 获取该组织下，是当前上级用户的数据
				if (BeanUtils.isNotEmpty(list2)) {//
					continue;
				} else {
					UserUnder userUnder = new UserUnder();
					userUnder.setId(UniqueIdUtil.getSuid());
					userUnder.setUserId(u.getId());
					userUnder.setUnderUserId(under.getId());
					userUnder.setUnderUserName(under.getFullname());
					userUnder.setOrgId(o.getId());
					userUnderService.create(userUnder);
				}
			}
			if (BeanUtils.isEmpty(orgUserService.getListByOrgIdUserId(o.getId(), under.getId()))) {// 若添加的下属还不属于该组织人员，那么将用户添为该组织人员
				OrgUser ou = new OrgUser();
				ou.setId(UniqueIdUtil.getSuid());
				ou.setUserId(under.getId());
				ou.setOrgId(orgId);
			}
		}
		return new CommonResult<String>(true, "添加下属成功", "");
	}

	@Override
	@Transactional
	public CommonResult<String> addUsersForOrg(String orgCode, String accounts) throws Exception {
		String[] accountArr = accounts.split(",");
		Org o = this.getByCode(orgCode);
		for (String a : accountArr) {
			User u = userService.getByAccount(a);
			if (BeanUtils.isEmpty(u)) {
				return new CommonResult<String>(false, "帐号【" + a + "】不存在", "");
			}
			List<OrgUser> l = orgUserService.getListByOrgIdUserId(o.getId(), u.getId());
			if (BeanUtils.isNotEmpty(l)) {
				//return new CommonResult<String>(false, u.getFullname()+"已在该组织下，请勿重复添加");
				continue;
			}

			OrgUser ou = new OrgUser();
			ou.setId(UniqueIdUtil.getSuid());
			List<OrgUser> orgUsers = orgUserService.getOrgUserMaster(u.getId(), o.getDemId());
			//已有主组织，但是当前组织是指定的主组织。则将原来的主组织取消
			if (BeanUtils.isEmpty(orgUsers)) {
				ou.setIsMaster(1);
			}else {
				ou.setIsMaster(0);
			}
			ou.setIsCharge(0);

			ou.setOrgId(o.getId());
			ou.setDemId(o.getDemId());
			ou.setUserId(u.getId());
			ou.setVersion(1);
			ou.setIsRelActive(1);
			orgUserService.create(ou);
			userService.removeUserGroupsCache(u.getId());
		}
		return new CommonResult<String>(true, "加入成功", "");
	}

	@Override
	public List<Org> getOrgByTime(OrgExportObject exportObject) throws Exception {
		QueryFilter queryFilter = OrgUtil.getDataByTimeFilter(exportObject.getBtime(), exportObject.getEtime());
		List<Demension> list = new ArrayList<Demension>();
		if (StringUtil.isNotEmpty(exportObject.getDemCodes())) {
			QueryFilter filter = QueryFilter.build().withPage(new PageBean(1, PageBean.WITHOUT_PAGE));
			filter.addFilter("CODE_", exportObject.getDemCodes(), QueryOP.IN, FieldRelation.AND);
			list = DemensionManager.queryNoPage(filter);
		}
		if (BeanUtils.isNotEmpty(list)) {
			Set<String> demIds = new HashSet<String>();
			for (Demension demension : list) {
				demIds.add(demension.getId());
			}
			queryFilter.addFilter("DEM_ID_", new ArrayList<String>(demIds), QueryOP.IN, FieldRelation.AND);
		}

		if (StringUtil.isNotEmpty(exportObject.getOrgCodes())) {
			List<String> ids = getOrgAndChildrens(exportObject.getOrgCodes());
			if (BeanUtils.isNotEmpty(ids)) {
				queryFilter.addFilter("ID_", ids, QueryOP.IN, FieldRelation.AND);
			}
		}

		return this.queryNoPage(queryFilter);
	}

	/**
	 * 获取组织的子组织
	 *
	 * @param orgCodes
	 * @return
	 */
	private List<String> getOrgAndChildrens(String orgCodes) {
		QueryFilter filter = QueryFilter.build().withPage(new PageBean(1, PageBean.WITHOUT_PAGE));
		filter.setPageBean(new PageBean(1, PageBean.WITHOUT_PAGE));
		filter.addFilter("CODE_", orgCodes, QueryOP.IN, FieldRelation.AND);
		List<Org> porgs = this.queryNoPage(filter);
		if (BeanUtils.isNotEmpty(porgs)) {
			QueryFilter filter2 = QueryFilter.build().withPage(new PageBean(1, PageBean.WITHOUT_PAGE));
			filter2.setPageBean(new PageBean(1, PageBean.WITHOUT_PAGE));
			for (Org org : porgs) {
				filter2.addFilter("PATH_", org.getPath(), QueryOP.RIGHT_LIKE, FieldRelation.OR);
			}
			List<Org> childrens = this.queryNoPage(filter2);
			if (BeanUtils.isNotEmpty(childrens)) {
				Set<String> ids = new HashSet<String>();
				for (Org org : childrens) {
					ids.add(org.getId());
				}
				List<String> list = new ArrayList<String>();
				list.addAll(ids);
				return list;
			}

		}
		return new ArrayList<String>();
	}

	/**
	 * 获取同步数据时，如果传了组织相关的参数，则添加过滤条件
	 *
	 * @param queryFilter
	 * @param exportObject
	 * @throws Exception
	 */
	@Transactional
	private void addOrgFilter(QueryFilter queryFilter, OrgExportObject exportObject) throws Exception {
		if (StringUtil.isNotEmpty(exportObject.getDemCodes()) || StringUtil.isNotEmpty(exportObject.getOrgCodes())) {
			List<Org> orgs = getOrgByTime(exportObject);
			if (BeanUtils.isNotEmpty(orgs)) {
				List<String> orgIds = new ArrayList<String>();
				for (Org org : orgs) {
					orgIds.add(org.getId());
				}
				queryFilter.addFilter("ORG_ID_", orgIds, QueryOP.IN, FieldRelation.AND);
			}
		}
	}

	@Override
	public List<OrgParams> getOrgParamByTime(OrgExportObject exportObject) throws Exception {
		QueryFilter queryFilter = OrgUtil.getDataByTimeFilter(exportObject.getBtime(), exportObject.getEtime());
		return orgParamsService.queryNoPage(queryFilter);
	}

	@Override
	public List<OrgPost> getOrgPostByTime(OrgExportObject exportObject) throws Exception {
		QueryFilter queryFilter = OrgUtil.getDataByTimeFilter(exportObject.getBtime(), exportObject.getEtime());
		return orgPostService.queryNoPage(queryFilter);
	}

	@Override
	public List<OrgRole> getOrgRoleByTime(OrgExportObject exportObject) throws Exception {
		QueryFilter queryFilter = OrgUtil.getDataByTimeFilter(exportObject.getBtime(), exportObject.getEtime());
		addOrgFilter(queryFilter, exportObject);
		return orgRoleManager.queryNoPage(queryFilter);
	}

	@Override
	public List<OrgUser> getOrgUserByTime(OrgExportObject exportObject) throws Exception {
		QueryFilter queryFilter = OrgUtil.getDataByTimeFilter(exportObject.getBtime(), exportObject.getEtime());
		addOrgFilter(queryFilter, exportObject);
		return orgUserService.queryNoPage(queryFilter);
	}

	@Override
	public List<UserUnder> getUserUnderByTime(OrgExportObject exportObject) throws Exception {
		QueryFilter queryFilter = OrgUtil.getDataByTimeFilter(exportObject.getBtime(), exportObject.getEtime());
		addOrgFilter(queryFilter, exportObject);
		return userUnderManager.queryNoPage(queryFilter);
	}

	@Override
	public List<Org> getOrgsByAccount(String account) throws Exception {
		if (StringUtil.isEmpty(account)) {
			throw new RuntimeException(HotentHttpStatus.REUIRED.description() + ":用户帐号account必填");
		}
		List<Org> list = baseMapper.getOrgsByAccount(account);
		for (Org org : list) {
			Demension dem = demensionService.get(org.getDemId());
			if (BeanUtils.isNotEmpty(dem)) {
				org.setDemName(dem.getDemName());
			}
		}
		OrgUtil.removeDuplicate(list, "id");
		return list;
	}

	@Override
	@Transactional
	public Integer removePostPhysical() {
		return orgPostDao.removePhysical();
	}

	@Override
	@Transactional
	public Integer removeOrgUserPhysical() {
		return orgUserService.removePhysical();
	}

	@Override
	public CommonResult<Boolean> isCodeExist(String code) throws Exception {
		Org org = baseMapper.getByCode(code);
		boolean isExist = BeanUtils.isNotEmpty(org);
		return new CommonResult<Boolean>(isExist, isExist ? "该组织编码已存在！" : "", isExist);
	}

	@Override
	public CommonResult<Boolean> isPostCodeExist(String code) throws Exception {
		OrgPost post = orgPostDao.getByCode(code);
		boolean isExist = BeanUtils.isNotEmpty(post);
		return new CommonResult<Boolean>(isExist, isExist ? "该岗位编码已存在！" : "", isExist);
	}

	@Override
	@Transactional
	public CommonResult<String> updateOrgPos(String orgId, String parentId) throws Exception {
		if (StringUtil.isEmpty(orgId) || StringUtil.isEmpty(parentId)) {
			throw new RequiredException("移动节点或目标节点id不能为空！");
		}
		Org org = this.get(orgId);
		if (BeanUtils.isEmpty(org)) {
			throw new RequiredException("根据移动节点id【" + orgId + "】未找到对应组织！");
		}
		org.setParentId(parentId);
		if ("0".equals(parentId)) {
			parentId = org.getDemId();
		}
		Org parentOrg = this.get(parentId);
		if (BeanUtils.isEmpty(parentOrg)) {
			org.setPath(parentId + "." + orgId + ".");
			org.setPathName("/" + org.getName());
		} else {
			org.setPath(parentOrg.getPath() + orgId + ".");
			org.setPathName(parentOrg.getPathName() + "/" + org.getName());
		}
		this.update(org);
		updateChildrenOrg(org);
		return new CommonResult<String>(true, "更新组织成功！", "");
	}

	/**
	 * 递归更新子组织的path和pathName
	 *
	 * @param parentOrg
	 * @throws SQLException
	 */
	@Transactional
	private void updateChildrenOrg(Org parentOrg) throws SQLException {
		List<Org> childrens = this.getByParentId(parentOrg.getId());
		for (Org org : childrens) {
			org.setPath(parentOrg.getPath() + org.getId() + ".");
			org.setPathName(parentOrg.getPathName() + "/" + org.getName());
			this.update(org);
			updateChildrenOrg(org);
		}
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public String exportData(String orgCode, boolean isChildre) throws Exception {
		if (StringUtil.isEmpty(orgCode)) {
			throw new RequiredException("组织编码【orgCode】不能为空！");
		}
		Org org = baseMapper.getByCode(orgCode);
		if (BeanUtils.isEmpty(org)) {
			throw new RequiredException("根据组织编码【" + orgCode + "】找不到对应组织！");
		}
		QueryFilter queryFilter = QueryFilter.build();
		queryFilter.getPageBean().setPageSize(PageBean.WITHOUT_PAGE);
		if (isChildre) {
			queryFilter.getParams().put("whereSql", " org.path_ like '" + org.getPath() + "%'");
		} else {
			queryFilter.getParams().put("orgId", org.getId());
		}
		String orgName = org.getName();
		String times = DateUtil.getCurrentTime("yyyymmddhhmmss");
		List list = orgUserService.getOrgUserData(queryFilter);
		String path = (FileUtil.getIoTmpdir() + "/attachFiles/tempZip/" + orgName + "/" + times).replace("/",
				File.separator);
		String excelPath = path + File.separator;
		String excelName = "组织【" + orgName + "】相关数据";
		exportExcel(list, orgName, excelName, excelPath);
		String filePath = excelPath + excelName;
		return filePath;
	}

	private <E> void exportExcel(List<E> list, String sheetName, String excelName, String excelPath) throws Exception {
		Map<String, String> exportMaps = new LinkedHashMap<String, String>();
		exportMaps.put("fullName", "用户姓名");
		exportMaps.put("account", "用户账号");
		exportMaps.put("userNumber", "工号");
		exportMaps.put("userId", "用户ID");
		exportMaps.put("status", "用户状态");
		exportMaps.put("mobile", "手机号码");
		exportMaps.put("email", "邮箱");
		exportMaps.put("orgName", "组织名称");
		exportMaps.put("orgCode", "组织编码");
		exportMaps.put("orgId", "组织ID");
		exportMaps.put("orgPath", "组织路径");
		exportMaps.put("orgPathName", "路径名称");
		exportMaps.put("isMaster", "主岗位");
		exportMaps.put("isCharge", "负责人");
		exportMaps.put("relName", "岗位名称");
		exportMaps.put("postCode", "岗位编码");
		exportMaps.put("relId", "岗位ID");
		exportMaps.put("isRelActive", "岗位是否有效");
		HSSFWorkbook book = ExcelUtil.exportExcel(sheetName, 16, exportMaps, list);
		ExcelUtil.saveExcel(book, excelName, excelPath);
	}

	@Override
	public List<Map<String, String>> getPathNames(List<String> userIds) {
		return baseMapper.getPathNames(userIds);
	}

	@Override
	public Map<String, Set<String>> getChildrenIds(Map<String, String> ids) {
		Map<String, Set<String>> resultMap = new HashMap<String, Set<String>>();
		if (BeanUtils.isNotEmpty(ids)) {
			for (String key : ids.keySet()) {
				String idStr = ids.get(key);
				if (StringUtil.isEmpty(idStr)) {
					continue;
				}
				String[] idArray = idStr.split(",");
				QueryFilter filter1 = QueryFilter.build().withPage(new PageBean(1, PageBean.WITHOUT_PAGE));
				filter1.addFilter("ID_", idArray, QueryOP.IN);
				List<Org> orgs = this.queryNoPage(filter1);
				if (BeanUtils.isNotEmpty(orgs)) {
					Map<String, String> pathMap = new HashMap<String, String>();
					for (int i = 0; i < orgs.size(); i++) {
						pathMap.put(String.valueOf(i + 1), orgs.get(i).getPath());
					}
					List<String> childrenIds = baseMapper.getChildrenIds(pathMap);
					resultMap.put(key, new HashSet<>(childrenIds));
				}
			}
		}
		return resultMap;
	}

	@Override
	public Org getOrgMaster(String account) {
		List<Org> orglist = baseMapper.getOrgMaster(account);
		if (BeanUtils.isNotEmpty(orglist)) {
			return orglist.get(0);
		} else {
			return null;
		}
	}

	/**
	 * 根据组织ids（多个）获取组织信息
	 * @param orgIds
	 */
	@Override
	public List<Org> getOrgByIds(List<String> orgIds) throws Exception {
		List<Org> orglist = baseMapper.getByIds(orgIds);
		return orglist;
	}

	@Override
	public List<Map<String, Object>> getOrgByIdsAndCurOrgId(List<String> orgIds, String orgPath) {
		List<Map<String, Object>> orglist = baseMapper.getOrgByIdsAndCurOrgId(orgIds, orgPath);
		return orglist;
	}

	@Override
	@Transactional
	public CommonResult<String> addOrgFromExterUni(Org orgVo) {
		if (BeanUtils.isEmpty(orgVo.getName())) {
			throw new RuntimeException("添加组织失败，组织名称【name】不能为空！");
		}
		if (BeanUtils.isEmpty(orgVo.getCode())) {
			throw new RuntimeException("添加组织失败，组织编码【code】不能为空！");
		}
		if (orgVo.getCode().contains(",")) {
			throw new RuntimeException("组织编码中不能包含英文逗号‘,’");
		}
		if (BeanUtils.isEmpty(orgVo.getDemId())) {
			Demension defaultDem =  demensionService.getDefaultDemension();
			if(BeanUtils.isEmpty(defaultDem)) {
				throw new RuntimeException("添加组织["+orgVo.getName()+"]失败，本系统无默认维度");
			}else {
				orgVo.setDemId(defaultDem.getId());
			}
		}else {
			Demension dem = demensionService.get(orgVo.getDemId());
			if (BeanUtils.isEmpty(dem)) {
				throw new RuntimeException("添加组织["+orgVo.getName()+"]失败，根据输入的demId[" + orgVo.getDemId() + "]没有找到对应的维度信息！");
			}
		}

		Org o = this.getByCode(orgVo.getCode());
		if (BeanUtils.isNotEmpty(o)) {
			throw new RuntimeException("添加组织["+orgVo.getName()+"]失败，组织编码[" + orgVo.getCode() + "]已存在！");
		}
		Org pOrg = null;
		if (!"0".equals(orgVo.getParentId()) && BeanUtils.isNotEmpty(orgVo.getParentId())) {
			pOrg = this.get(orgVo.getParentId());
			if (BeanUtils.isEmpty(pOrg)) {
				throw new RuntimeException("添加组织["+orgVo.getName()+"]失败，根据输入的parentId[" + orgVo.getParentId() + "]没有找到对应的组织信息！");
			}
			if (BeanUtils.isEmpty(pOrg) && !pOrg.getDemId().equals(orgVo.getDemId())) {
				throw new RuntimeException("添加组织["+orgVo.getName()+"]失败，根据输入demId与所输入的父组织所对应的维度id不一致！");
			}
		}
		o = new Org();
		o.setId(orgVo.getId());
		o.setCode(orgVo.getCode());
		o.setName(orgVo.getName());
		o.setDemId(orgVo.getDemId());
		o.setOrderNo(orgVo.getOrderNo());
		if (StringUtils.isEmpty(orgVo.getParentId())) {
			o.setParentId("0");
		} else {
			o.setParentId(orgVo.getParentId());
		}
		if (BeanUtils.isEmpty(pOrg)) {
			o.setPathName("/" + orgVo.getName());
			o.setPath(orgVo.getDemId() + "." + o.getId() + ".");
		} else {
			o.setPath(pOrg.getPath() + o.getId() + ".");
			o.setPathName(pOrg.getPathName() + "/" + orgVo.getName());
		}
		this.create(o);
		return new CommonResult<String>(true, "添加组织成功！", "");
	}

	@Override
	public List<Org> getOrgsByparentId(String parentId) {
		return baseMapper.getByParentId(parentId);
	}

	@Override
	@Transactional
	public Integer removePhysical() {
		return baseMapper.removePhysical();
	}

	@Override
	public Org get(Serializable id) {
		return baseMapper.get(id);
	}

	@Override
	public List<String> getSubOrgByIds(Set<String> parentIds) {
		//递归获取所有下级组织
		List<String> list = getSubOrgIds(parentIds);
		if(CollectionUtils.isNotEmpty(list)){
			List<String> listSub = getSubOrgByIds(new HashSet<>(list));
			if(CollectionUtils.isNotEmpty(list)){
				list.addAll(listSub);
			}
		}
		return list;
	}
	private List<String> getSubOrgIds(Set<String> parentIds){
		if(parentIds.isEmpty()) {
			return new ArrayList<>();
		}
		return baseMapper.getSubOrgByIds(parentIds);
	}

	@Override
	public List<Map<String, Object>> getOrgIdMapByUserId(String userId) {
		return baseMapper.getOrgIdMapByUserId(userId);
	}

	@Override
	public CommonResult<Org> getFillOrg(String demId,String grade) {
		String userId = ContextUtil.getCurrentUserId();
		Org curOrg = this.getMainGroup(userId, demId);
		Org gradeOrg = null;
		if(BeanUtils.isNotEmpty(curOrg)){
			if(grade.equals(curOrg.getGrade())){
				gradeOrg = curOrg;
			}else{
				gradeOrg = getPOrgByGread(curOrg.getParentId(),grade);
			}
		}else{
			return new CommonResult<>(false, "获取当前用户所属主组织失败！");
		}
		if(BeanUtils.isEmpty(gradeOrg)){
			return new CommonResult<>(false, "未获取到当前用户填制单位！");
		}
		return new CommonResult<>(true, "获取成功！",gradeOrg);
	}

	private Org getPOrgByGread(String orgId,String grade){
		Org org = this.get(orgId);
		if(BeanUtils.isNotEmpty(org) && !grade.equals(org.getGrade())){
			return getPOrgByGread(org.getParentId(), grade);
		}
		return org;
	}

	@Override
	public Map<String, Org> getParentMainOrg(String userId) {
		Map<String, Org> map=new HashMap<>();
		Org org=getMainGroup(userId,"");
		if(BeanUtils.isNotEmpty(org)){
			String path=org.getPath();
			List<String> ids=Arrays.asList(path .split("\\.")).stream().map(s -> (s.trim())).collect(Collectors.toList());;
			List<Org> list = baseMapper.selectList(new QueryWrapper<Org>().in("ID_",ids));
			if(BeanUtils.isNotEmpty(list)){
				list.forEach(item->{
					String grade = item.getGrade() == null ? Strings.EMPTY : item.getGrade();
					map.put(grade,item);
				});
			}
		}
		return map;
	}

	@Override
	public OrgParams getParamById(String orgId, String alias) {
		return  orgParamsService.getByOrgIdAndAlias(orgId, alias);
	}

	@Override
	public boolean isOrgHasParamKey(String orgId, String alias) {
		OrgParams byOrgIdAndAlias = orgParamsDao.getByOrgIdAndAlias(orgId, alias);
		if(BeanUtils.isEmpty(byOrgIdAndAlias)){
			return false;
		}else{
			return true;
		}
	}

	@Override
	public boolean hasOrgParamKey(String grade,String userId, String alias) throws Exception {
		Map<String, Org> map = this.getParentMainOrg(userId);
		if(map.containsKey(grade)){
			OrgParams p = orgParamsService.getByOrgIdAndAlias(map.get(grade).getId(), alias);
			if (BeanUtils.isNotEmpty(p)) {
				return  true;
			}
		}
		return false;
	}

	@Override
	public List<Org> getOrgListByCodes(List<String> list) {
		return baseMapper.getOrgListByCodes(list);
	}

	@Override
	public List<Org> getByPathNames(List<String> pathNames) {
		return baseMapper.getPathNameList(pathNames);
	}

	@Override
	public boolean insertBatch(List<Org> list) {
		return this.saveBatch(list);
	}

	/**
	 * 通过用户ID获取所有父组织
	 * */
	@Override
	public List<Org> getParantMainOrgAll(String userId) throws IOException {
		String orgStr = orgUserService.getCacheByKeyOrgPost(userId);
		Org org = null;
		if (StringUtil.isNotEmpty(orgStr)){
			Map<String, Object> stringObjectMap = JsonUtil.toMap(orgStr);
			Map<String,Object> postMap = (Map<String,Object>)stringObjectMap.get("postCharge");
			if (BeanUtils.isNotEmpty(postMap)){
				org = this.getByCode(postMap.get("orgcode").toString());
			}
		}else{
			org= getMainGroup(userId,"");
		}
		if(BeanUtils.isNotEmpty(org)){
			String path = org.getPath();
			List<String> ids=Arrays.asList(path .split("\\.")).stream().map(s -> (s.trim())).collect(Collectors.toList());;
			List<Org> list = baseMapper.selectList(new QueryWrapper<Org>().in("ID_", ids));
			return list;
		}else{
			return new ArrayList<>();
		}
	}

	@Override
	public List<User> getChargesByOrgId(String orgId, Boolean isMain, Boolean demCode) throws Exception {
		List<User> users = new ArrayList<User>();
		Org org = this.get(orgId);
		if(BeanUtils.isEmpty(org)){
			org = this.getByCode(orgId);
			if(BeanUtils.isNotEmpty(org)){
				orgId = org.getId();
			}
		}
		List<OrgPost> mainPost = postService.getRelCharge(orgId, true);
		if(BeanUtils.isNotEmpty(mainPost)){
			users = userService.getListByPostId(mainPost.get(0).getId());
		}else{
			List<OrgUser> orgUsers = orgUserManager.getChargesByOrgId(orgId, isMain);
			if(BeanUtils.isNotEmpty(orgUsers)){
				Set<String> userIds = new HashSet<String>();
				for (OrgUser orgUser : orgUsers) {
					if(!userIds.contains(orgUser.getUserId())){
						User user = userService.get(orgUser.getUserId());
						if(BeanUtils.isNotEmpty(user)){
							userIds.add(orgUser.getUserId());
							users.add(user);
						}
					}
				}
			}
		}
		return users;
	}

	@Override
	public List<OrgTree> getOrgTreeByParentAndDem(Map<String, String> params) throws Exception {
		QueryFilter filter = QueryFilter.build();
		String demId = "";
		if(BeanUtils.isNotEmpty(params.get("demId"))){
			demId = params.get("demId").toString();
			filter.addParams("demId", demId);
		}
		String parentId = "0";
		if(BeanUtils.isNotEmpty(params.get("parentId"))){
			filter.addParams("parentId", " ('" +params.get("parentId").toString()+"') ");
		}else{
			parentId = AuthFilterUtil.getOrgAuthParentId(demId);
			filter.addParams("parentId", parentId);
		}

		String authSql = AuthFilterUtil.getOrgAuthSql(demId);
		if(StringUtil.isNotEmpty(authSql)){
			filter.addParams("authSql", authSql);
		}
		List<Org> list = null;
		if(BeanUtils.isNotEmpty(params.get("deep"))){
			parentId = BeanUtils.isNotEmpty(params.get("parentId"))?params.get("parentId"):"0";
			filter.getParams().remove("parentId");
			Org parent = this.get(parentId);
			//filter.addFilter("PATH_", parent.getPath(), QueryOP.RIGHT_LIKE, FieldRelation.AND);
			filter.addParams("path",parent.getPath() + "%");
			list = this.getByParentAndDem(filter);
			list.removeIf(org->{
				return org.getId().equals(parent.getId());
			});
		}else if (BeanUtils.isNotEmpty(params.get("orgId"))){
			parentId = BeanUtils.isNotEmpty(params.get("parentId"))?params.get("parentId"):"0";
			filter.getParams().remove("parentId");
			filter.addParams("id",params.get("orgId"));
			list = this.getByParentAndDem(filter);
			list.forEach(org->{
				org.setParentId("0");
			});
		}else{
			list = this.getByParentAndDem(filter);
		}

		//处理有父子关系的权限组织根目录
		if(StringUtil.isNotEmpty(authSql)){
			OrgUtil.dealRepeatAuthRoot(list);
		}

		List<OrgTree> groupTreeList = new ArrayList<OrgTree>();

		for (Org group : list) {
			OrgTree groupTree = new OrgTree(group);
			if(BeanUtils.isNotEmpty(params.get("isShowPost"))&& StringUtil.isNotEmpty(params.get("isShowPost").toString())&&params.get("isShowPost").toString().equals("true")){
				if(!groupTree.isIsParent()){
					List<OrgPost> postList = postService.getListByOrgId(groupTree.getId());
					if(postList.size() > 0){
						groupTree.setIsParent(1);
					}
				}
			}
			groupTreeList.add(groupTree);
		}
		if(BeanUtils.isNotEmpty(params.get("demId")) && StringUtil.isNotEmpty(params.get("demId").toString()) && BeanUtils.isEmpty(params.get("parentId"))){
			OrgTree root = new OrgTree();
			Demension d = demService.get(params.get("demId").toString());
			if(BeanUtils.isNotEmpty(d)){
				root.setId("0");
				if(BeanUtils.isNotEmpty(groupTreeList)){
					root.setIsParent(1);
				}else{
					root.setIsParent(0);
				}
				root.setDemId(d.getId());
				root.setName(d.getDemName());
				root.setParentId("0");
			}
			groupTreeList.add(root);
		}else if(BeanUtils.isNotEmpty(params.get("isOrgAuth"))&& StringUtil.isNotEmpty(params.get("isOrgAuth").toString())&&params.get("isOrgAuth").toString().equals("true")){
			OrgTree root = new OrgTree();
			Org org = this.get(params.get("parentId").toString());
			if(BeanUtils.isNotEmpty(org)){
				root = new OrgTree(org);
				if(org.isIsParent()){
					root.setAuthRoot(true);
				}
			}
			groupTreeList.add(root);
		}

		//以组织id为parentId获取岗位数据，显示在树下
		if(BeanUtils.isNotEmpty(params.get("isShowPost"))&& StringUtil.isNotEmpty(params.get("isShowPost").toString())&&params.get("isShowPost").toString().equals("true")){
			if(BeanUtils.isNotEmpty(params.get("parentId"))){
				List<OrgPost> postList = postService.getListByOrgId(params.get("parentId").toString());
				for (OrgPost orgPost : postList) {
					OrgTree postTree = new OrgTree(orgPost);
					postTree.setDemId(params.get("demId").toString());
					//设置岗位类别，默认false
					postTree.setPost(true);
					groupTreeList.add(postTree);
				}
			}
		}
		return groupTreeList;
	}

	@Override
	public List<OrgTree> getByParentAndDemToTree(Map<String, String> params) throws Exception {
		List<OrgTree> groupTreeList = new ArrayList<>();
		QueryFilter filter = QueryFilter.build();
		String demId = "";
		if(BeanUtils.isNotEmpty(params.get("demId"))){
			demId = params.get("demId");
			filter.addParams("demId", demId);
		}

		//@TODO @userqiao 注释代码，能够让其查出所有的子集 但防止其影响其余未知地方 新开个接口专为组织管理树服务
		if(BeanUtils.isNotEmpty(params.get("parentId"))){
			filter.addParams("parentId", " ('" +params.get("parentId")+"') ");
		}
		String authSql = AuthFilterUtil.getOrgAuthSql(demId);

		if(StringUtil.isNotEmpty(authSql)){
			filter.addParams("authSql", authSql);
		}
		if(BeanUtils.isNotEmpty(params.get("name"))){
			filter.addParams("name", params.get("name"));
		}
		if(BeanUtils.isNotEmpty(params.get("id"))){
			filter.addParams("id", params.get("id"));
		}
		if(BeanUtils.isNotEmpty(params.get("orgType"))){
			filter.addParams("orgType"," (" +params.get("orgType") + ")");
		}

		List<Org> list = this.getByParentAndDem(filter);
		//处理有父子关系的权限组织根目录
		if(StringUtil.isNotEmpty(authSql)){
			OrgUtil.dealRepeatAuthRoot(list);
		}

		for (Org group : list) {
			OrgExternalSetting orgExt=orgExternalSettingManager.querySettingByCorpIdReturn(group.getId());
			if(orgExt!=null&&orgExt.getDingAppKey()!=null&&orgExt.getDingAppSecret()!=null){
				group.setExtSetting("1");
			}else{
				group.setExtSetting("0");
			}
			OrgTree groupTree = new OrgTree(group);
			if(BeanUtils.isNotEmpty(params.get("isShowPost"))&& StringUtil.isNotEmpty(params.get("isShowPost"))&& "true".equals(params.get("isShowPost"))){
				if(!groupTree.isIsParent()){
					List<OrgPost> postList = postService.getListByOrgId(groupTree.getId());
					if(postList.size() > 0){
						groupTree.setIsParent(1);
					}
				}
			}
			groupTreeList.add(groupTree);
		}
		if(BeanUtils.isNotEmpty(params.get("demId")) && StringUtil.isNotEmpty(params.get("demId")) && BeanUtils.isEmpty(params.get("parentId")) && BeanUtils.isEmpty(params.get("name"))){
			OrgTree root = new OrgTree();
			Demension d = demService.get(params.get("demId"));
			if(BeanUtils.isNotEmpty(d)){
				root.setId("0");
				if(BeanUtils.isNotEmpty(groupTreeList)){
					root.setIsParent(1);
				}else{
					root.setIsParent(0);
				}
				root.setDemId(d.getId());
				root.setName(d.getDemName());
				root.setParentId("0");
			}
			groupTreeList.add(root);
		}else if(BeanUtils.isNotEmpty(params.get("isOrgAuth"))&& StringUtil.isNotEmpty(params.get("isOrgAuth"))&& "true".equals(params.get("isOrgAuth"))){
			OrgTree root = new OrgTree();
			Org org = this.get(params.get("parentId"));
			if(BeanUtils.isNotEmpty(org)){
				root = new OrgTree(org);
				if(org.isIsParent()){
					root.setAuthRoot(true);
				}
			}
			groupTreeList.add(root);
		}

		//以组织id为parentId获取岗位数据，显示在树下
		if(BeanUtils.isNotEmpty(params.get("isShowPost"))&& StringUtil.isNotEmpty(params.get("isShowPost"))&& "true".equals(params.get("isShowPost"))){
			if(BeanUtils.isNotEmpty(params.get("parentId"))){
				List<OrgPost> postList = postService.getListByOrgId(params.get("parentId"));
				for (OrgPost orgPost : postList) {
					OrgTree postTree = new OrgTree(orgPost);
					postTree.setDemId(params.get("demId"));
					//设置岗位类别，默认false
					postTree.setPost(true);
					groupTreeList.add(postTree);
				}
			}
		}
		return groupTreeList;
	}

	@Override
	public PageList<HashMap<String, Object>> getOrgUserPage(QueryFilter queryFilter) throws Exception {
		QueryFilter groupFilter = QueryFilter.build();
		List<HashMap<String,Object>> userByGroupList = orgUserService.getUserByGroupList(groupFilter);
		Page<HashMap<String,Object>> p = (Page<HashMap<String,Object>>) orgUserService.getUserByGroupPost(queryFilter);
		String orgId = "";
		List<String> userIds = new ArrayList<>();
		if(p.getTotal() > 0 && userByGroupList.size() > 0){
			for (Map<String,Object> user : p.getRecords()) {
				for (Map<String,Object> obj : userByGroupList){
					if(Objects.equals(MapUtil.getStringIgnoreKey(user, "userId", ""), MapUtil.getStringIgnoreKey(obj, "userId", ""))){
						String isMaster = MapUtil.getStringIgnoreKey(obj, "isMaster", "");
						String[] split = isMaster.split(",");
						int count = 0;
						Pattern pt = Pattern.compile("1");
						Matcher m = pt.matcher(isMaster);
						while (m.find()) {
							count++;
						}
						if(split.length > 1 && count > 1 || isMaster.contains("1") && !"1".equals(MapUtil.getStringIgnoreKey(user, "isMaster", ""))){
							user.put("otherPost",3);
						}else if(split.length == 1){
							user.put("otherPost",1);
						}else{
							user.put("otherPost",2);
						}
						if(StringUtil.isNotEmpty((String)user.get("relName"))){
							user.put("relName", MapUtil.getStringIgnoreKey(user, "relName", "").split(","));
						}
					}
				}
				userIds.add(MapUtil.getStringIgnoreKey(user,"userId",""));
				orgId = MapUtil.getStringIgnoreKey(user,"orgId","");
			}
			//处理组织用户关系id
			if(BeanUtils.isNotEmpty(userIds)){
				QueryFilter<OrgUser> orgUserQueryFilter = QueryFilter.<OrgUser>build()
						.withQuery(new QueryField("user_id_", userIds, QueryOP.IN))
						.withQuery(new QueryField("org_id_", orgId))
						.withSorter(new FieldSort("is_master_",Direction.DESC));
				List<OrgUser> orgUsers = orgUserService.queryNoPage(orgUserQueryFilter);
				if(BeanUtils.isNotEmpty(orgUsers)){
					Map<String,String> userOrgMap = new HashMap<>();
					for (OrgUser orgUser : orgUsers) {
						if(!userOrgMap.containsKey(orgUser.getUserId())){
							userOrgMap.put(orgUser.getUserId(),orgUser.getId());
						}
					}

					for (Map<String,Object> user : p.getRecords()) {
						String userId = MapUtil.getStringIgnoreKey(user, "userId", "");
						if(BeanUtils.isNotEmpty(userOrgMap.get(userId))){
							user.put("orgUserId",userOrgMap.get(userId));
						}
					}
				}
			}

		}
		return new PageList<>(p);
	}

	@Override
	public Boolean isSupOrgByCurrMain(String userId, String demId, Integer level) throws Exception {
		List<OrgUser> orgUsers = orgUserService.getOrgUserMaster(userId,demId);
		if(BeanUtils.isNotEmpty(orgUsers)){
			OrgUser orgUser = orgUsers.get(0);
			String levelGroupId = orgUser.getOrgId();
			Org org = this.get(levelGroupId);
			while(level>0) {
				org = this.get(org.getParentId());
				if(BeanUtils.isNotEmpty(org)){
					levelGroupId = org.getId();
					--level;
				}else{
					return false;
				}
			}
			Org currentOrg = this.getMainGroup(userId, demId);
			if(BeanUtils.isNotEmpty(currentOrg)){
				String groupId = currentOrg.getId();
				if(levelGroupId.equals(groupId)){
					return false;
				}
				if(StringUtil.isNotZeroEmpty(currentOrg.getParentId())){
					return true;
				}
			}
		}
		return false;
	}

	@Override
	public PageList<Org> getOrgLimitByCodes(String codes) {

		QueryFilter queryFilter = QueryFilter.build().withPage(new PageBean(1, PageBean.WITHOUT_PAGE));
		queryFilter.addFilter("code", codes, QueryOP.IN,FieldRelation.AND,"group_1");
		PageList<Org> query = query(queryFilter);
		if (BeanUtils.isNotEmpty(query) && BeanUtils.isNotEmpty(query.getRows())) {
			for (Org org : query.getRows()) {
				Map<String, Object> map = new HashMap<>();
				map.put("orgCode", org.getCode());
				map.put("group", "true");
				List<Map<String, Object>> list = orgUserDao.getUserNumByOrgCode(map);
				org.setNowNum(list.size());
			}
		}
		return query;
	}

	@Override
	public void exportUsers(String orgCode, Boolean isChildre) throws Exception{
		HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
		isChildre = BeanUtils.isEmpty(isChildre)?true:isChildre;
		String path = exportData(orgCode, isChildre);
		if(StringUtil.isNotEmpty(path)){
			String excelPath = path+".xls";
			File file = new File(excelPath);
			if(!file.exists()){
				throw new RuntimeException("生成Excel文件失败！");
			}
			String excelName = file.getName();
			// 导出
			HttpUtil.downLoadFile(response, excelPath, excelName);
			// 删除导出的文件
			FileUtil.deleteFile(file.getParentFile().getPath());
		}else{
			throw new RuntimeException("导出组织用户信息失败！");
		}
	}

	@Override
	public List<User> getCustomLevelCharge(String userId, String level, boolean isMainCharge) throws Exception{
		List<Org> userOrg = getUserOrg(userId, "", true);
		List<User> chargesByOrg = new ArrayList<User>();
		if( BeanUtils.isEmpty(userOrg) ) {
			return chargesByOrg;
		}
		Org org = userOrg.get(0);
		while(!"0".equals(org.getParentId())) {
			String orgId = org.getParentId();
			org = get(orgId);
			if(level.equals(org.getGrade())) {
				chargesByOrg = userService.getChargesByOrg(org.getCode(), isMainCharge);
				break;
			}
		}
		return chargesByOrg;
	}

	@Override
	public Set<GroupIdentity> getCustomLevelPost(String userId, String level, String postCode) throws Exception{
		List<Org> userOrg = getUserOrg(userId, "", true);
		Set<GroupIdentity> chargesByOrg = new HashSet<GroupIdentity>();
		if( BeanUtils.isEmpty(userOrg) ) {
			return chargesByOrg;
		}
		Org org = userOrg.get(0);
		while(!"0".equals(org.getParentId())) {
			String orgId = org.getParentId();
			org = get(orgId);
			if(level.equals(org.getGrade())) {
				chargesByOrg = userService.getByPostCodeAndOrgCode(postCode, org.getCode());
				break;
			}
		}
		return chargesByOrg;
	}

	@Override
	public Set<GroupIdentity> getCustomLevelJob(String userId, String level, String jobCode) throws Exception{
		List<Org> userOrg = getUserOrg(userId, "", true);
		Set<GroupIdentity> chargesByOrg = new HashSet<GroupIdentity>();
		if( BeanUtils.isEmpty(userOrg) ) {
			return chargesByOrg;
		}
		Org org = userOrg.get(0);
		while(!"0".equals(org.getParentId())) {
			String orgId = org.getParentId();
			org = get(orgId);
			if(level.equals(org.getGrade())) {
				chargesByOrg =  userService.getByJobCodeAndOrgCode(jobCode,org.getCode());
				break;
			}
		}
		return chargesByOrg;
	}

	@Override
	public List<Map<String, Object>> getUserOrgNowNumByOrgIds(String orgIds) {
		List<Map<String, Object>> mapList = new ArrayList<>();
		String[] value = orgIds.split(",");
		for(String orgId :value){
			Map<String, Object> map = new HashMap<>();
			Map<String, Object> numMap = new HashMap<>();
			map.put("orgId", orgId);
			map.put("group", "true");
			List<Map<String, Object>> list = orgUserDao.getUserNumByOrgId(map);
			numMap.put("orgId", orgId);
			numMap.put("num", list.size());
			mapList.add(numMap);
		}
		return mapList;
	}

	@Override
	@Transactional
	public CommonResult<String> operatingUserOrgPost(Map<String,Object> mapObj) throws Exception {
		List<String> accounts = (List<String>) mapObj.get("accounts");//要转移或复制的用户
		String type = mapObj.get("type").toString();//1、转移，2、复制
		String msg = "组织岗位转移成功";
		for (String account : accounts) {
			//只有组织的情况
			if (BeanUtils.isNotEmpty(mapObj.get("orgCodes"))) {
				List<String> orgCodes = (List<String>) mapObj.get("orgCodes");//要转移或复制的组织
				for (String code : orgCodes) {
					OrgUserVo orgUserVo = new OrgUserVo();
					orgUserVo.setAccount(account);
					orgUserVo.setOrgCode(code);
					User u = userService.getByAccount(orgUserVo.getAccount());
					if (BeanUtils.isEmpty(u)) {
						throw new RuntimeException("没有找到对应的用户");
					}
					Org o = this.getByCode(orgUserVo.getOrgCode());
					if (BeanUtils.isEmpty(u)) {
						throw new RuntimeException("没有找到对应的用户");
					}
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("userId", u.getId());
					map.put("orgId", o.getId());
					List<OrgUser> list = orgUserService.getByParms(map);
					//用户不存在该组织则把用户添加到该组织
					if (BeanUtils.isEmpty(list)) {
						OrgUser orgUser = new OrgUser();
						orgUser.setId(UniqueIdUtil.getSuid());
						orgUser.setUserId(u.getId());
						orgUser.setOrgId(o.getId());
						orgUser.setIsRelActive(1);
						if (BeanUtils.isEmpty(orgUserVo.getIsCharge())) {
							orgUser.setIsCharge(0);
						} else {
							orgUser.setIsCharge(orgUserVo.getIsCharge());
						}
						if (BeanUtils.isEmpty(orgUserVo.getIsMaster())) {
							orgUser.setIsMaster(0);
						} else {
							orgUser.setIsMaster(orgUserVo.getIsMaster());
							if (orgUserVo.getIsMaster() == 1) {
								List<OrgUser> l = orgUserService.getOrgUserMaster(u.getId(), o.getDemId());
								if (BeanUtils.isNotEmpty(l)) {
									OrgUser ou = l.get(0);
									ou.setIsMaster(0);
									orgUserService.update(ou);
								}
							}
						}
						orgUserService.create(orgUser);
					}
				}
			}
			//有组织或岗位的情况
			if (BeanUtils.isNotEmpty(mapObj.get("postCodes"))) {
				List<String> postCodes = (List<String>) mapObj.get("postCodes");//要转移或复制的岗位
				for (String postCode : postCodes) {
					OrgPost post = orgPostService.getByCode(postCode);
					if (BeanUtils.isEmpty(post)) {
						throw new RuntimeException("根据输入岗位代码没有找到对应的岗位信息！");
					}
					Org org = this.get(post.getOrgId());
					if (org.getExceedLimitNum() == 1 && org.getLimitNum() != 0) {
						Map<String, Object> map = new HashMap<>();
						map.put("orgCode", org.getCode());
						map.put("group", "true");
						List<Map<String, Object>> list = orgUserService.getUserNumByOrgCode(map);
						if (org.getLimitNum() <= list.size()) {
							return new CommonResult<String>(false, "人数超出组织上限，不予添加", null);
						}
					}
					User u = userService.getByAccount(account);
					if (BeanUtils.isEmpty(u)) {
						throw new RuntimeException("根据输入的用户帐号【" + account + "】没有找到对应的用户");
					}
					OrgUser ou = orgUserService.getOrgUser(post.getOrgId(), u.getId(), post.getId());
					QueryWrapper<OrgUser> queryWrapper = new QueryWrapper<>();
					queryWrapper.eq("ORG_ID_", post.getOrgId());
					queryWrapper.eq("USER_ID_", u.getId());
					List<Map<String, Object>> list = orgUserService.listMaps(queryWrapper);
					//用户不存在该岗位则把用户添加到该岗位
					if (BeanUtils.isEmpty(ou)) {
						for (int i = 0; i < list.size(); i++) {
							if (ObjectUtils.isEmpty(list.get(i).get("relId"))) {
								if (BeanUtils.isNotEmpty(list.get(i).get("ID_"))) {
									delOrgUser(list.get(i).get("ID_").toString());
								} else {
									delOrgUser(list.get(i).get("id_").toString());
								}
								break;
							}
						}
						ou = new OrgUser();
						ou.setId(UniqueIdUtil.getSuid());
						ou.setUserId(u.getId());
						ou.setIsCharge(0);
						ou.setIsMaster(0);
						ou.setIsRelActive(1);
						ou.setOrgId(post.getOrgId());
						ou.setRelId(post.getId());
						orgUserService.create(ou);
					}
				}
			}
		}
		if("2".equals(type)) {
			msg = "组织岗位复制成功";
		}else {
			List<String> orgUserIds = (List<String>)mapObj.get("orgUserIds");//原用户的组织岗位Id
			StringBuilder str = new StringBuilder();
			for (String id : orgUserIds) {// 将用户在该组织下的所有相关下属删除
				OrgUser obj = orgUserService.get(id);
				if (BeanUtils.isNotEmpty(obj)) {
					userUnderService.delByUserIdAndOrgId(obj.getUserId(), obj.getOrgId());
				}
			}
			orgUserService.removeByIds(orgUserIds);
		}
		return new CommonResult<String>(true, msg, "");
	}

	@Override
	public void removeUserMenuByOrgId(String orgId){
		try {
			List<User> userListByOrgId = userManager.getUserListByOrgId(orgId);
			if(CollectionUtils.isNotEmpty(userListByOrgId)){
				for (User user : userListByOrgId) {
					roleManager.delUserMenuCacheByUserId(user.getUserId());
				}
			}
		} catch (Exception e) {
			throw new com.hotent.uc.exception.BaseException(e.getMessage());
		}
	}

	@Override
	public CommonResult<String> delOrgUserByUserIds(String ids) throws Exception {
		if (StringUtil.isEmpty(ids)) {
			throw new RuntimeException("id值不能为空！");
		}
		String[] userIds = ids.split(",");
		List<String> removeIds = new ArrayList<>();
		Boolean isDele = false;
		StringBuilder str = new StringBuilder();
		for (String orgId : userIds) {
			OrgUser orgUser = orgUserService.get(orgId);
			if(orgUser == null){
				continue;
			}
			QueryFilter<OrgUser> build = QueryFilter.build();
			build.addQueryField(new QueryField("USER_ID_",orgUser.getUserId()));
			build.addQueryField(new QueryField("ORG_ID_",orgUser.getOrgId()));
			List<OrgUser> orgUsers = orgUserService.queryNoPage(build);
			for (OrgUser user : orgUsers) {
				if (BeanUtils.isNotEmpty(user)) {
					//清除用户主组织缓存
					orgUserService.removeUserMainOrgCache(user.getUserId());
					userService.removeUserGroupsCache(user.getUserId());
					orgUserService.removeUserMainOrgCache("", user.getUserId());
					userUnderService.delByUserIdAndOrgId(user.getUserId(), user.getOrgId());
					isDele = true;
					removeIds.add(user.getId());
				} else {
					str.append(user.getUserId());
					str.append("，");
				}
			}
		}
		String msg = StringUtil.isEmpty(str.toString()) ? "用户取消加入成功！" : "部分用户取消加入成功，id为：" + str.toString() + "的数据不存在！";
		String[] removeArr = new String[removeIds.size()];
		for (int i = 0; i < removeArr.length; i++) {
			removeArr[i] = removeIds.get(i);
		}
		orgUserService.removeByIds(removeArr);
		return new CommonResult<String>(isDele, msg, "");
	}

	/**
	 * 通过ids查询对应的组织
	 */
	@Override
	public List<Org> getOrgListByIds(List<String> list, String demId) {
		return baseMapper.getOrgListByIds(list, demId);
	}

	/**
	 * 通过判断同级组织是否 包含 相同名称
	 * @param orgId 组织id
	 * @param parentId 父组织id
	 * @param newName 组织新名称
	 * @param orgType 组织类型
	 */
	@Override
	public boolean queryExistsNameBySameLevel(String orgId, String parentId, String newName, String orgType) throws Exception {
		return baseMapper.queryExistsNameBySameLevel(orgId, parentId, newName, orgType);
	}

	@Override
	public CommonResult<String> importOrg(MultipartHttpServletRequest request) throws Exception {
		MultipartFile file = request.getFile("file");

		String token = JwtUtil.getToken(request);
		Claims claims = jwtTokenHandler.parseToken(token);
		String tenantId = (String) claims.get("tenantId"); //获取维度
		String demId="";
		QueryWrapper<Demension> lambdaQueryWrapper=new QueryWrapper<>();
		lambdaQueryWrapper.eq("TENANT_ID_",tenantId);
		lambdaQueryWrapper.eq("IS_DEFAULT_","1");
		Demension demension=demensionManager.getBaseMapper().selectOne(lambdaQueryWrapper);
		Boolean isRepeat = importOrgFile(file,demension);
		if(!isRepeat){
			return new CommonResult<>(true,"confirmUpload");
		}
		return new CommonResult<>(true,"导入成功");
	}

	@Override
	public CommonResult<String> importDepart(MultipartHttpServletRequest request) throws Exception {
		MultipartFile file = request.getFile("file");

		String token = JwtUtil.getToken(request);
		Claims claims = jwtTokenHandler.parseToken(token);
		String tenantId = (String) claims.get("tenantId"); //获取维度
		String demId="";
		QueryWrapper<Demension> lambdaQueryWrapper=new QueryWrapper<>();
		lambdaQueryWrapper.eq("TENANT_ID_",tenantId);
		lambdaQueryWrapper.eq("IS_DEFAULT_","1");
		Demension demension=demensionManager.getBaseMapper().selectOne(lambdaQueryWrapper);
		Boolean isRepeat = importDepartFile(file,demension);
		if(!isRepeat){
			return new CommonResult<>(true,"confirmUpload");
		}
		return new CommonResult<>(true,"导入成功");
	}

	@Override
	public void export(HttpServletResponse response, String ids) throws Exception {
		QueryFilter filter = QueryFilter.build().withPage(new PageBean(1, PageBean.WITHOUT_PAGE));
		filter.addFilter("id", ids.split(","), QueryOP.IN);
		PageList<Org> orgs = query(filter);
		List<Map<String,Object>> list = new ArrayList<>();
		if(BeanUtils.isNotEmpty(orgs.getRows())){
			for (Org role : orgs.getRows()) {
				list.add(JsonUtil.toMap(JsonUtil.toJson(role)));
			}
		}
		Map<String,String> exportMap = new LinkedHashMap<>();
		exportMap.put("pathName","组织名称");
		exportMap.put("code","组织代码");
//		exportMap.put("enabled","状态");
//		exportMap.put("description","描述");
		HSSFWorkbook exportFile = ExcelUtil.exportExcel("组织列表", 22, exportMap, list);
		ExcelUtil.downloadExcel(exportFile,"组织导出",response);
	}

	@Override
	public CommonResult<?> addOrEditOrg(OrgVo org,String demId) {
		//中间表保存数据
		//消息中间件处理数据
//		Map<String,Object> objMap=new HashMap<>();
//		objMap.put("data",org);
//		objMap.put("funType","addOrEditOrg");
//		//消息中间件保存数据
//		jmsProducer.sendToQueue(objMap,"externData");
		List<Org> listReturn=null;
		try {
			QueryWrapper<Demension> lambdaQueryWrapper=new QueryWrapper<>();
			lambdaQueryWrapper.eq("ID_",demId);
			lambdaQueryWrapper.eq("IS_DEFAULT_","1");
			Demension demension=demensionManager.getBaseMapper().selectOne(lambdaQueryWrapper);
			List<OrgVo> list=new ArrayList<>();
			list.add(org);

			if(org.getOrgType().equals(Org.ORG_TYPE_ORG)){
				listReturn=addOrEditOrg(list,demension);

			}else if(org.getOrgType().equals(Org.ORG_TYPE_DEP)){
				listReturn=addOrEditDepart(list,demension);
			}
			orgExternalManager.addOrEdit(listReturn.size()>0?org.changeVoOpen(listReturn.get(0)):org ,demId);

			//此处保存成功需要推送到钉钉等外部系统

			//成功回写id到中间表
		} catch (Exception e) {
			e.printStackTrace();
		}
		return  new CommonResult<Org>(true,listReturn.size()==0?"更新成功":"新增成功",listReturn.size()>0?listReturn.get(0):null);
	}

	@Override
	public CommonResult<?> deleteOrg(OrgVo org, String demId) {
		LambdaQueryWrapper<Org> qw=new LambdaQueryWrapper<>();
		qw.eq(Org::getId,org.getId());
		Org orgEnt=this.baseMapper.selectOne(qw);
		if(orgEnt!=null){
			try {
				this.orgService.deleteOrg(orgEnt.getCode());
				orgExternalManager.deleteEnti(org);
				return new CommonResult<String>(true,"删除成功");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public CommonResult<?> getOrgStatic() {
		Map<String,Object> mapResult=new HashMap<>();
		IUser user = ContextUtil.getCurrentUser();
		try {
			if(!user.isAdmin()) {
				QueryFilter queryFilter = QueryFilter.build();
				queryFilter.addFilter("b.account_",user.getAccount(), QueryOP.EQUAL);
				IPage<OrgAuth> list =orgAuthService.getAllOrgAuth(queryFilter);
				List<OrgAuth> listOrg=list.getRecords();
				mapResult.put("org",list.getRecords().size());
				List<String> orgIdList=listOrg.stream().map(r->r.getOrgId()).collect(Collectors.toList());
				mapResult.put("dept",orgIdList.size()>0?getDeptByOrgId(orgIdList).size():"0");
				mapResult.put("user",orgIdList.size()>0?getUserByOrgId(orgIdList).size():"0");
			}else{
				List<Org> orgList=getAllOrg();
				mapResult.put("org",orgList.size());
				List<String> orgIdList=orgList.stream().map(r->r.getId()).collect(Collectors.toList());
				mapResult.put("dept",orgIdList.size()>0?getDeptByOrgId(orgIdList).size():"0");
				mapResult.put("user",orgIdList.size()>0?getUserByOrgId(orgIdList).size():"0");

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new CommonResult<>(true,"获取成功",mapResult);
	}

	@Override
	public Map<String, Object> getUserOrgAndDept(String userId) {
		boolean flag=false;
		Map<String,Object> result=new HashMap<>();
		User userCur=userService.get(userId);
		if(userCur!=null&&!flag){
			LambdaQueryWrapper<OrgUser> orgUserQw=new LambdaQueryWrapper<>();
			orgUserQw.eq(OrgUser::getUserId,userCur.getId());
			orgUserQw.orderByDesc(OrgUser::getIsMaster);
			List<OrgUser> orgUserList=orgUserDao.selectList(orgUserQw);
			for(int i=0;i<orgUserList.size();i++){
				LambdaQueryWrapper<Org> orgQw=new LambdaQueryWrapper<>();
				orgQw.eq(Org::getId,orgUserList.get(i).getOrgId());
				orgQw.eq(Org::getOrgType,Org.ORG_TYPE_DEP);
				orgQw.eq(Org::getIsDelete,"0");
				List<Org> orgList=this.baseMapper.selectList(orgQw);
				if(orgList.size()>0){
					result.put("deptName",orgList.get(0).getName());
					flag=true;
					break;
				}
			}

			for(int i=0;i<orgUserList.size();i++){
				LambdaQueryWrapper<Org> orgQw=new LambdaQueryWrapper<>();
				orgQw.eq(Org::getId,orgUserList.get(i).getOrgId());
				orgQw.notIn(Org::getOrgType,Org.ORG_TYPE_DEP);
				orgQw.eq(Org::getIsDelete,"0");
				List<Org> orgList=this.baseMapper.selectList(orgQw);
				if(orgList.size()>0){
					result.put("orgName",orgList.get(0).getName());
					break;
				}
			}
		}
		return result;
	}

	private List<Org> getAllOrg(){
		LambdaQueryWrapper<Org> orgLambdaQueryWrapper=new LambdaQueryWrapper<>();
		orgLambdaQueryWrapper.eq(Org::getIsDelete,"0");
		orgLambdaQueryWrapper.notIn(Org::getOrgType,Org.ORG_TYPE_DEP);
		List<Org> resultList=this.baseMapper.selectList(orgLambdaQueryWrapper);
		return resultList;
	}
	private List<Org> getDeptByOrgId(List<String> orgIdList){
        LambdaQueryWrapper<Org> orgLambdaQueryWrapper=new LambdaQueryWrapper<>();
		orgLambdaQueryWrapper.eq(Org::getIsDelete,"0");
		orgLambdaQueryWrapper.in(Org::getParentId,orgIdList);
		orgLambdaQueryWrapper.eq(Org::getOrgType,Org.ORG_TYPE_DEP);
		List<Org> resultList=this.baseMapper.selectList(orgLambdaQueryWrapper);
		List<Org> indexList=new ArrayList<>();
		indexList.addAll(resultList);
		findDeptList(indexList,resultList);
		return indexList;
	}

	private void findDeptList(List<Org> indexList,List<Org> list){
		for(int i=0;i<list.size();i++){
			String id=list.get(i).getId();
			LambdaQueryWrapper<Org> orgLambdaQueryWrapper=new LambdaQueryWrapper<>();
			orgLambdaQueryWrapper.eq(Org::getIsDelete,"0");
			orgLambdaQueryWrapper.eq(Org::getParentId,id);
			orgLambdaQueryWrapper.in(Org::getOrgType,Org.ORG_TYPE_DEP);
			List<Org> resultList=this.baseMapper.selectList(orgLambdaQueryWrapper);
			indexList.addAll(resultList);
			if(resultList.size()>0){
				findDeptList(indexList,resultList);
			}

		}
	}

	private List<OrgUser> getUserByOrgId(List<String> orgIdList){
		List<OrgUser> resultList=new ArrayList<>();
		LambdaQueryWrapper<OrgUser> orgLambdaQueryWrapper=new LambdaQueryWrapper<>();
		orgLambdaQueryWrapper.eq(OrgUser::getIsDelete,"0");
		orgLambdaQueryWrapper.in(OrgUser::getOrgId,orgIdList);
		resultList=orgUserDao.selectList(orgLambdaQueryWrapper);
		List<OrgUser> distinctUser = resultList.stream()
				.collect(Collectors.collectingAndThen(
						Collectors.toMap(OrgUser::getUserId, r -> r, (p1, p2) -> p1),
						map -> new ArrayList<>(map.values())
				));
		return distinctUser;
	}

	@Transactional
	public List<Org> addOrEditDepart(List<OrgVo> list,Demension demension){
		String preCode = "";
		preCode = demension.getDemCode();
		List<Org> orgList = new ArrayList<Org>();
		if(BeanUtils.isNotEmpty(list)){
			List<Org> databaseOrgList = new ArrayList<Org>();
			Map<String,String> orgMap = new HashMap<String,String>();
			Map<String,List<Org>> pathOrgMap = new HashMap<String, List<Org>>();
			List<String> orgPaths = new ArrayList<String>();
			for (OrgVo orgVo : list) {
				if(StringUtil.isNotEmpty(orgVo.getName())) {
					orgPaths.add(orgVo.getName());
				}
			}
			if(BeanUtils.isNotEmpty(orgPaths)) {
				BeanUtils.removeDuplicate(orgPaths);
				databaseOrgList = orgService.getByPathNames(orgPaths);
				if(BeanUtils.isNotEmpty(databaseOrgList)) {
					for (Org iorg : databaseOrgList) {
						String pname = iorg.getPathName();
						List<Org> porgs = null;
						if(pathOrgMap.containsKey(pname)) {
							porgs = pathOrgMap.get(pname);
						}else {
							porgs = new ArrayList<Org>();
						}
						porgs.add(iorg);
						pathOrgMap.put(pname, porgs);
					}
				}
			}
			//获取所有组织
			List<Org> databaseOrgs = orgService.getAll();
			Map<String,Org> orgCodeMap = new HashMap<String, Org>();
			if(BeanUtils.isNotEmpty(databaseOrgs)) {
				for (Org org : databaseOrgs) {
					if(!"1".equals(org.getIsDelete())) {
						orgCodeMap.put(org.getCode(), org);

						String pname = org.getPathName();
						List<Org> porgs = null;
						boolean exist = false;
						if(pathOrgMap.containsKey(pname)) {
							porgs = pathOrgMap.get(pname);
							for (Org org2 : databaseOrgs) {
								if(org2.getPathName()!=null){
									if(org2.getPathName().equals(pname)) {
										exist = true;
										break;
									}
								}

							}
						}else {
							porgs = new ArrayList<Org>();
						}
						if(!exist) {
							porgs.add(org);
							pathOrgMap.put(pname, porgs);
						}
					}
				}
			}

			for(OrgVo orgVo:list){
				Org currentOrg = null;//当前行所指向的组织
				int subIndex = 1;
				String orgInfo = orgVo.getName();
				//判断数据库中是否存在
				List<Org> porgs = pathOrgMap.get(orgInfo);
				if(BeanUtils.isNotEmpty(porgs)) {
					for (Org porg : porgs) {
						//从同纬度下取
						if(demension.getId().equals(porg.getDemId())) {
							currentOrg = porg;
							break;
						}
					}
				}
				if(!orgInfo.startsWith("/")){
					subIndex = 0;
				}
				if(currentOrg == null) {
					String[] orgNameArr = orgInfo.substring(subIndex, orgInfo.length()).split("/");
					Map<String,String> pathNameMap = new HashMap<String,String>();
					for(int j = 0;j<=orgNameArr.length-1;j++){
						if(j == 0){
							pathNameMap.put("父级路径", "");
							pathNameMap.put("子级路径", "/"+orgNameArr[j]);
						}else{
							pathNameMap.put("父级路径", pathNameMap.get("子级路径"));
							pathNameMap.put("子级路径", pathNameMap.get("子级路径")+"/"+orgNameArr[j]);
						}
						List<Org> selectOrgList = pathOrgMap.get(pathNameMap.get("子级路径"));
						Org nowOrg = null;
						if(BeanUtils.isNotEmpty(selectOrgList)){
							for (Org org : selectOrgList) {
								if(demension.getId().equals(org.getDemId())){
									nowOrg = org;
									break;
								}
							}
						}
						if(BeanUtils.isEmpty(nowOrg) && StringUtil.isNotEmpty(orgNameArr[j])){//为空，考虑新增组织
							if(j==0){
								Org org = new Org();
								org.setId(UniqueIdUtil.getSuid());
								org.setName(orgNameArr[j]);
								org.setDemId(demension.getId());
								org.setParentId("0");
//								Org parentOrg1 = getById(org.getParentId());
//								if(parentOrg1!=null) {
//									if(Org.ORG_TYPE_DEP.equals(parentOrg1.getOrgType())) {
//										org.setSuperiorOrgId(parentOrg1.getSuperiorOrgId());
//										org.setSuperiorDepId(org.getParentId());
//									} else {
//										org.setSuperiorOrgId(org.getParentId());
//									}
//								}
								org.setPathName(pathNameMap.get("子级路径"));
								org.setOrgType(Org.ORG_TYPE_DEP);//部门
								org.setPath(demension.getId()+"."+org.getId()+".");
								String code = preCode+"_"+PinyinUtil.getPinYinHeadChar(orgNameArr[j]).replace("-", "_");
								if(orgCodeMap.containsKey(code) && org.getPathName().equals(orgCodeMap.get(code).getPathName())) {
									currentOrg = orgCodeMap.get(code);
								}else {
									code = code + "_" + org.getId().substring(org.getId().length()-3);
									if(orgMap.containsKey(code) && pathNameMap.get("子级路径").equals(orgMap.get(code))) {
										code = code + "_" + org.getId().substring(org.getId().length()-3);
									}
									org.setCode(code);
									orgMap.put(code, org.getPathName());
									currentOrg = dealOrg(org,orgList,preCode,orgMap,orgCodeMap);
								}
							}else{
								currentOrg = dealOrgUnderBydepart(pathNameMap.get("父级路径"),pathNameMap.get("子级路径"),orgList,demension.getId(),preCode,orgMap,pathOrgMap,orgCodeMap);
							}
						}else{
							currentOrg = nowOrg;
						}
					}
				}

			}

			Map<String,List<Org>> codeOrgMaps = new HashMap<String, List<Org>>();
			if(BeanUtils.isNotEmpty(orgList)) {
				for (Org o : orgList) {
					String code = o.getCode();
					if(orgCodeMap.containsKey(code)) {
						System.out.println(code);
					}

					List<Org> porgs = null;
					if(codeOrgMaps.containsKey(code)) {
						porgs = pathOrgMap.get(code);
					}else {
						porgs = new ArrayList<Org>();
					}
					porgs.add(o);
					pathOrgMap.put(code, porgs);
				}
			}
			//批量新增组织
			if(BeanUtils.isNotEmpty(orgList)) {
				orgList.stream().forEach(item->{
					Org parentOrg = getById(item.getParentId());
					if(parentOrg!=null) {
						if(Org.ORG_TYPE_DEP.equals(parentOrg.getOrgType())) {
							item.setSuperiorOrgId(parentOrg.getSuperiorOrgId());
							item.setSuperiorDepId(item.getParentId());
						} else {
							item.setSuperiorOrgId(item.getParentId());
						}
					}
					orgService.saveOrUpdate(item);
				});

			}
		}
		return orgList;
	}
	@Transactional
	public List<Org> addOrEditOrg(List<OrgVo> list,Demension demension){
		String preCode = "";
		preCode = demension.getDemCode();
		List<Org> orgList = new ArrayList<Org>();
		if(BeanUtils.isNotEmpty(list)){
			List<Org> databaseOrgList = new ArrayList<Org>();
			Map<String,String> orgMap = new HashMap<String,String>();
			Map<String,List<Org>> pathOrgMap = new HashMap<String, List<Org>>();
			List<String> orgPaths = new ArrayList<String>();
			for (OrgVo orgVo : list) {
				if(StringUtil.isNotEmpty(orgVo.getName())) {
					orgPaths.add(orgVo.getName());
				}
			}
			if(BeanUtils.isNotEmpty(orgPaths)) {
				BeanUtils.removeDuplicate(orgPaths);
				databaseOrgList = orgService.getByPathNames(orgPaths);
				if(BeanUtils.isNotEmpty(databaseOrgList)) {
					for (Org iorg : databaseOrgList) {
						String pname = iorg.getPathName();
						List<Org> porgs = null;
						if(pathOrgMap.containsKey(pname)) {
							porgs = pathOrgMap.get(pname);
						}else {
							porgs = new ArrayList<Org>();
						}
						porgs.add(iorg);
						pathOrgMap.put(pname, porgs);
					}
				}
			}
			//获取所有组织
			List<Org> databaseOrgs = orgService.getAll();
			Map<String,Org> orgCodeMap = new HashMap<String, Org>();
			if(BeanUtils.isNotEmpty(databaseOrgs)) {
				for (Org org : databaseOrgs) {
					if(!"1".equals(org.getIsDelete())) {
						orgCodeMap.put(org.getCode(), org);

						String pname = org.getPathName();
						List<Org> porgs = null;
						boolean exist = false;
						if(pathOrgMap.containsKey(pname)) {
							porgs = pathOrgMap.get(pname);
							for (Org org2 : databaseOrgs) {
								if(org2.getPathName()!=null){
									if(org2.getPathName().equals(pname)) {
										exist = true;
										break;
									}
								}

							}
						}else {
							porgs = new ArrayList<Org>();
						}
						if(!exist) {
							porgs.add(org);
							pathOrgMap.put(pname, porgs);
						}
					}
				}
			}

			for(OrgVo orgVo:list){
				Org currentOrg = null;//当前行所指向的组织
				int subIndex = 1;
				String orgInfo = orgVo.getName();
				//判断数据库中是否存在
				List<Org> porgs = pathOrgMap.get(orgInfo);
				if(BeanUtils.isNotEmpty(porgs)) {
					for (Org porg : porgs) {
						//从同纬度下取
						if(demension.getId().equals(porg.getDemId())) {
							currentOrg = porg;
							break;
						}
					}
				}
				if(!orgInfo.startsWith("/")){
					subIndex = 0;
				}
				if(currentOrg == null) {
					String[] orgNameArr = orgInfo.substring(subIndex, orgInfo.length()).split("/");
					Map<String,String> pathNameMap = new HashMap<String,String>();
					for(int j = 0;j<=orgNameArr.length-1;j++){
						if(j == 0){
							pathNameMap.put("父级路径", "");
							pathNameMap.put("子级路径", "/"+orgNameArr[j]);
						}else{
							pathNameMap.put("父级路径", pathNameMap.get("子级路径"));
							pathNameMap.put("子级路径", pathNameMap.get("子级路径")+"/"+orgNameArr[j]);
						}
						List<Org> selectOrgList = pathOrgMap.get(pathNameMap.get("子级路径"));
						Org nowOrg = null;
						if(BeanUtils.isNotEmpty(selectOrgList)){
							for (Org org : selectOrgList) {
								if(demension.getId().equals(org.getDemId())){
									nowOrg = org;
									break;
								}
							}
						}
						if(BeanUtils.isEmpty(nowOrg) && StringUtil.isNotEmpty(orgNameArr[j])){//为空，考虑新增组织
							if(j==0){
								Org org = new Org();
								org.setId(UniqueIdUtil.getSuid());
								org.setName(orgNameArr[j]);
								org.setDemId(demension.getId());
								org.setParentId("0");
								org.setPathName(pathNameMap.get("子级路径"));
								org.setPath(demension.getId()+"."+org.getId()+".");
								org.setOrderNo(orgVo.getOrderNo());
								String code = preCode+"_"+PinyinUtil.getPinYinHeadChar(orgNameArr[j]).replace("-", "_");
								if(orgCodeMap.containsKey(code) && org.getPathName().equals(orgCodeMap.get(code).getPathName())) {
									currentOrg = orgCodeMap.get(code);
								}else {
									code = code + "_" + org.getId().substring(org.getId().length()-3);
									if(orgMap.containsKey(code) && pathNameMap.get("子级路径").equals(orgMap.get(code))) {
										code = code + "_" + org.getId().substring(org.getId().length()-3);
									}
									org.setCode(code);
									orgMap.put(code, org.getPathName());
									currentOrg = dealOrg(org,orgList,preCode,orgMap,orgCodeMap);
								}
							}else{
								currentOrg = dealOrgUnder(pathNameMap.get("父级路径"),pathNameMap.get("子级路径"),orgList,demension.getId(),preCode,orgMap,pathOrgMap,orgCodeMap);
							}
						}else{
							currentOrg = nowOrg;
						}
					}
				}

			}

			Map<String,List<Org>> codeOrgMaps = new HashMap<String, List<Org>>();
			if(BeanUtils.isNotEmpty(orgList)) {
				for (Org o : orgList) {
					String code = o.getCode();
					if(orgCodeMap.containsKey(code)) {
						System.out.println(code);
					}

					List<Org> porgs = null;
					if(codeOrgMaps.containsKey(code)) {
						porgs = pathOrgMap.get(code);
					}else {
						porgs = new ArrayList<Org>();
					}
					porgs.add(o);
					pathOrgMap.put(code, porgs);
				}
			}

			//批量新增组织
			if(BeanUtils.isNotEmpty(orgList)) {
				orgService.insertBatch(orgList);

				orgList.stream().forEach(item->{
					Org parentOrg = getById(item.getParentId());
					if(parentOrg!=null) {
						if(Org.ORG_TYPE_DEP.equals(parentOrg.getOrgType())) {
							item.setSuperiorOrgId(parentOrg.getSuperiorOrgId());
							item.setSuperiorDepId(item.getParentId());
						} else {
							item.setSuperiorOrgId(item.getParentId());
						}
					}
				});

			}
		}
		return orgList;
	}

	@Transactional
	public Boolean importOrgFile(MultipartFile file,Demension demension){
		List<OrgVo> list = ExcelUtil.readExcel(OrgVo.class,file);
		String preCode = "";
		preCode = demension.getDemCode();
		if(BeanUtils.isNotEmpty(list)){
			List<Org> databaseOrgList = new ArrayList<Org>();
			Map<String,String> orgMap = new HashMap<String,String>();
			Map<String,List<Org>> pathOrgMap = new HashMap<String, List<Org>>();
			List<Org> orgList = new ArrayList<Org>();
			List<String> orgPaths = new ArrayList<String>();
			for (OrgVo orgVo : list) {
				if(StringUtil.isNotEmpty(orgVo.getName())) {
					orgPaths.add(orgVo.getName());
				}
			}
			if(BeanUtils.isNotEmpty(orgPaths)) {
				BeanUtils.removeDuplicate(orgPaths);
				databaseOrgList = orgService.getByPathNames(orgPaths);
				if(BeanUtils.isNotEmpty(databaseOrgList)) {
					for (Org iorg : databaseOrgList) {
						String pname = iorg.getPathName();
						List<Org> porgs = null;
						if(pathOrgMap.containsKey(pname)) {
							porgs = pathOrgMap.get(pname);
						}else {
							porgs = new ArrayList<Org>();
						}
						porgs.add(iorg);
						pathOrgMap.put(pname, porgs);
					}
				}
			}
			//获取所有组织
			List<Org> databaseOrgs = orgService.getAll();
			Map<String,Org> orgCodeMap = new HashMap<String, Org>();
			if(BeanUtils.isNotEmpty(databaseOrgs)) {
				for (Org org : databaseOrgs) {
					if(!"1".equals(org.getIsDelete())) {
						orgCodeMap.put(org.getCode(), org);

						String pname = org.getPathName();
						List<Org> porgs = null;
						boolean exist = false;
						if(pathOrgMap.containsKey(pname)) {
							porgs = pathOrgMap.get(pname);
							for (Org org2 : databaseOrgs) {
								if(org2.getPathName()!=null){
									if(org2.getPathName().equals(pname)) {
										exist = true;
										break;
									}
								}

							}
						}else {
							porgs = new ArrayList<Org>();
						}
						if(!exist) {
							porgs.add(org);
							pathOrgMap.put(pname, porgs);
						}
					}
				}
			}

			for(OrgVo orgVo:list){
				Org currentOrg = null;//当前行所指向的组织
				int subIndex = 1;
				String orgInfo = orgVo.getName();
				//判断数据库中是否存在
				List<Org> porgs = pathOrgMap.get(orgInfo);
				if(BeanUtils.isNotEmpty(porgs)) {
					for (Org porg : porgs) {
						//从同纬度下取
						if(demension.getId().equals(porg.getDemId())) {
							currentOrg = porg;
							break;
						}
					}
				}
				if(!orgInfo.startsWith("/")){
					subIndex = 0;
				}
				if(currentOrg == null) {
					String[] orgNameArr = orgInfo.substring(subIndex, orgInfo.length()).split("/");
					Map<String,String> pathNameMap = new HashMap<String,String>();
					for(int j = 0;j<=orgNameArr.length-1;j++){
						if(j == 0){
							pathNameMap.put("父级路径", "");
							pathNameMap.put("子级路径", "/"+orgNameArr[j]);
						}else{
							pathNameMap.put("父级路径", pathNameMap.get("子级路径"));
							pathNameMap.put("子级路径", pathNameMap.get("子级路径")+"/"+orgNameArr[j]);
						}
						List<Org> selectOrgList = pathOrgMap.get(pathNameMap.get("子级路径"));
						Org nowOrg = null;
						if(BeanUtils.isNotEmpty(selectOrgList)){
							for (Org org : selectOrgList) {
								if(demension.getId().equals(org.getDemId())){
									nowOrg = org;
									break;
								}
							}
						}
						if(BeanUtils.isEmpty(nowOrg) && StringUtil.isNotEmpty(orgNameArr[j])){//为空，考虑新增组织
							if(j==0){
								Org org = new Org();
								org.setId(UniqueIdUtil.getSuid());
								org.setName(orgNameArr[j]);
								org.setDemId(demension.getId());
								org.setParentId("0");
								org.setPathName(pathNameMap.get("子级路径"));
								org.setPath(demension.getId()+"."+org.getId()+".");
								String code = preCode+"_"+PinyinUtil.getPinYinHeadChar(orgNameArr[j]).replace("-", "_");
								if(orgCodeMap.containsKey(code) && org.getPathName().equals(orgCodeMap.get(code).getPathName())) {
									currentOrg = orgCodeMap.get(code);
								}else {
									code = code + "_" + org.getId().substring(org.getId().length()-3);
									if(orgMap.containsKey(code) && pathNameMap.get("子级路径").equals(orgMap.get(code))) {
										code = code + "_" + org.getId().substring(org.getId().length()-3);
									}
									org.setCode(code);
									orgMap.put(code, org.getPathName());
									currentOrg = dealOrg(org,orgList,preCode,orgMap,orgCodeMap);
								}
							}else{
								currentOrg = dealOrgUnder(pathNameMap.get("父级路径"),pathNameMap.get("子级路径"),orgList,demension.getId(),preCode,orgMap,pathOrgMap,orgCodeMap);
							}
						}else{
							currentOrg = nowOrg;
						}
					}
				}

			}

			Map<String,List<Org>> codeOrgMaps = new HashMap<String, List<Org>>();
			if(BeanUtils.isNotEmpty(orgList)) {
				for (Org o : orgList) {
					String code = o.getCode();
					if(orgCodeMap.containsKey(code)) {
						System.out.println(code);
					}

					List<Org> porgs = null;
					if(codeOrgMaps.containsKey(code)) {
						porgs = pathOrgMap.get(code);
					}else {
						porgs = new ArrayList<Org>();
					}
					porgs.add(o);
					pathOrgMap.put(code, porgs);
				}
			}

			//批量新增组织
			if(BeanUtils.isNotEmpty(orgList)) {
				orgList.stream().forEach(item->{
					Org parentOrg = getById(item.getParentId());
					if(parentOrg!=null) {
						if(Org.ORG_TYPE_DEP.equals(parentOrg.getOrgType())) {
							item.setSuperiorOrgId(parentOrg.getSuperiorOrgId());
							item.setSuperiorDepId(item.getParentId());
						} else {
							item.setSuperiorOrgId(item.getParentId());
						}
					}
				});



				orgService.insertBatch(orgList);
			}
		}
		return true;
	}

	@Transactional
	public Boolean importDepartFile(MultipartFile file,Demension demension){
		List<OrgVo> list = ExcelUtil.readExcel(OrgVo.class,file);
		String preCode = "";
		preCode = demension.getDemCode();
		if(BeanUtils.isNotEmpty(list)){
			List<Org> databaseOrgList = new ArrayList<Org>();
			Map<String,String> orgMap = new HashMap<String,String>();
			Map<String,List<Org>> pathOrgMap = new HashMap<String, List<Org>>();
			List<Org> orgList = new ArrayList<Org>();
			List<String> orgPaths = new ArrayList<String>();
			for (OrgVo orgVo : list) {
				if(StringUtil.isNotEmpty(orgVo.getName())) {
					orgPaths.add(orgVo.getName());
				}
			}
			if(BeanUtils.isNotEmpty(orgPaths)) {
				BeanUtils.removeDuplicate(orgPaths);
				databaseOrgList = orgService.getByPathNames(orgPaths);
				if(BeanUtils.isNotEmpty(databaseOrgList)) {
					for (Org iorg : databaseOrgList) {
						String pname = iorg.getPathName();
						List<Org> porgs = null;
						if(pathOrgMap.containsKey(pname)) {
							porgs = pathOrgMap.get(pname);
						}else {
							porgs = new ArrayList<Org>();
						}
						porgs.add(iorg);
						pathOrgMap.put(pname, porgs);
					}
				}
			}
			//获取所有组织
			List<Org> databaseOrgs = orgService.getAll();
			Map<String,Org> orgCodeMap = new HashMap<String, Org>();
			if(BeanUtils.isNotEmpty(databaseOrgs)) {
				for (Org org : databaseOrgs) {
					if(!"1".equals(org.getIsDelete())) {
						orgCodeMap.put(org.getCode(), org);

						String pname = org.getPathName();
						List<Org> porgs = null;
						boolean exist = false;
						if(pathOrgMap.containsKey(pname)) {
							porgs = pathOrgMap.get(pname);
							for (Org org2 : databaseOrgs) {
								if(org2.getPathName()!=null){
									if(org2.getPathName().equals(pname)) {
										exist = true;
										break;
									}
								}

							}
						}else {
							porgs = new ArrayList<Org>();
						}
						if(!exist) {
							porgs.add(org);
							pathOrgMap.put(pname, porgs);
						}
					}
				}
			}

			for(OrgVo orgVo:list){
				Org currentOrg = null;//当前行所指向的组织
				int subIndex = 1;
				String orgInfo = orgVo.getName();
				//判断数据库中是否存在
				List<Org> porgs = pathOrgMap.get(orgInfo);
				if(BeanUtils.isNotEmpty(porgs)) {
					for (Org porg : porgs) {
						//从同纬度下取
						if(demension.getId().equals(porg.getDemId())) {
							currentOrg = porg;
							break;
						}
					}
				}
				if(!orgInfo.startsWith("/")){
					subIndex = 0;
				}
				if(currentOrg == null) {
					String[] orgNameArr = orgInfo.substring(subIndex, orgInfo.length()).split("/");
					Map<String,String> pathNameMap = new HashMap<String,String>();
					for(int j = 0;j<=orgNameArr.length-1;j++){
						if(j == 0){
							pathNameMap.put("父级路径", "");
							pathNameMap.put("子级路径", "/"+orgNameArr[j]);
						}else{
							pathNameMap.put("父级路径", pathNameMap.get("子级路径"));
							pathNameMap.put("子级路径", pathNameMap.get("子级路径")+"/"+orgNameArr[j]);
						}
						List<Org> selectOrgList = pathOrgMap.get(pathNameMap.get("子级路径"));
						Org nowOrg = null;
						if(BeanUtils.isNotEmpty(selectOrgList)){
							for (Org org : selectOrgList) {
								if(demension.getId().equals(org.getDemId())){
									nowOrg = org;
									break;
								}
							}
						}
						if(BeanUtils.isEmpty(nowOrg) && StringUtil.isNotEmpty(orgNameArr[j])){//为空，考虑新增组织
							if(j==0){
								Org org = new Org();
								org.setId(UniqueIdUtil.getSuid());
								org.setName(orgNameArr[j]);
								org.setDemId(demension.getId());
								org.setParentId("0");
//								Org parentOrg1 = getById(org.getParentId());
//								if(parentOrg1!=null) {
//									if(Org.ORG_TYPE_DEP.equals(parentOrg1.getOrgType())) {
//										org.setSuperiorOrgId(parentOrg1.getSuperiorOrgId());
//										org.setSuperiorDepId(org.getParentId());
//									} else {
//										org.setSuperiorOrgId(org.getParentId());
//									}
//								}
								org.setPathName(pathNameMap.get("子级路径"));
								org.setOrgType(Org.ORG_TYPE_DEP);//部门
								org.setPath(demension.getId()+"."+org.getId()+".");
								String code = preCode+"_"+PinyinUtil.getPinYinHeadChar(orgNameArr[j]).replace("-", "_");
								if(orgCodeMap.containsKey(code) && org.getPathName().equals(orgCodeMap.get(code).getPathName())) {
									currentOrg = orgCodeMap.get(code);
								}else {
									code = code + "_" + org.getId().substring(org.getId().length()-3);
									if(orgMap.containsKey(code) && pathNameMap.get("子级路径").equals(orgMap.get(code))) {
										code = code + "_" + org.getId().substring(org.getId().length()-3);
									}
									org.setCode(code);
									orgMap.put(code, org.getPathName());
									currentOrg = dealOrg(org,orgList,preCode,orgMap,orgCodeMap);
								}
							}else{
								currentOrg = dealOrgUnderBydepart(pathNameMap.get("父级路径"),pathNameMap.get("子级路径"),orgList,demension.getId(),preCode,orgMap,pathOrgMap,orgCodeMap);
							}
						}else{
							currentOrg = nowOrg;
						}
					}
				}

			}

			Map<String,List<Org>> codeOrgMaps = new HashMap<String, List<Org>>();
			if(BeanUtils.isNotEmpty(orgList)) {
				for (Org o : orgList) {
					String code = o.getCode();
					if(orgCodeMap.containsKey(code)) {
						System.out.println(code);
					}

					List<Org> porgs = null;
					if(codeOrgMaps.containsKey(code)) {
						porgs = pathOrgMap.get(code);
					}else {
						porgs = new ArrayList<Org>();
					}
					porgs.add(o);
					pathOrgMap.put(code, porgs);
				}
			}

			//批量新增组织
			if(BeanUtils.isNotEmpty(orgList)) {
				orgList.stream().forEach(item->{
					Org parentOrg = getById(item.getParentId());
					if(parentOrg!=null) {
						if(Org.ORG_TYPE_DEP.equals(parentOrg.getOrgType())) {
							item.setSuperiorOrgId(parentOrg.getSuperiorOrgId());
							item.setSuperiorDepId(item.getParentId());
						} else {
							item.setSuperiorOrgId(item.getParentId());
						}
					}
					orgService.saveOrUpdate(item);
				});

			}
		}
		return true;
	}
	/**
	 * 处理组织的上下级关系
	 * @param supperPathName  父级路径名
	 * @param underPathName  子级路径名
	 * @param demId 对应维度id
	 * @param orgList
	 * @return
	 */
	public Org dealOrgUnderBydepart(String supperPathName,String underPathName,List<Org> orgList,String demId,String preCode,Map<String,String> orgMap,Map<String,List<Org>> pathOrgMap,Map<String,Org> orgCodeMap){
		String underName = underPathName.substring(underPathName.lastIndexOf("/")+1, underPathName.length());
		List<Org> chirList = pathOrgMap.get(underPathName);
		if(BeanUtils.isNotEmpty(chirList)){//子组织不为空
			for (Org org : chirList) {
				if(demId.equals(org.getDemId())){
					return org;
				}
			}
		}
		//子组织为空的情况
		List<Org> pList = pathOrgMap.get(supperPathName);
		List<Org> parentList = new ArrayList<Org>();
		if(BeanUtils.isNotEmpty(pList)) {
			for (Org org : pList) {
				if(demId.equals(org.getDemId())){
					parentList.add(org);
				}
			}
		}
		Org chird = new Org();
		if(BeanUtils.isEmpty(parentList)){//父组织为空，直接从orgList中寻找父级组织
			for(int i=0;i<orgList.size();i++){
				if(orgList.get(i).getPathName().equals(supperPathName)){
					chird.setId(UniqueIdUtil.getSuid());
					chird.setParentId(orgList.get(i).getId());
					chird.setDemId(demId);
//					Org parentOrg1 = getById(chird.getParentId());
//					if(parentOrg1!=null) {
//						if(Org.ORG_TYPE_DEP.equals(parentOrg1.getOrgType())) {
//							chird.setSuperiorOrgId(parentOrg1.getSuperiorOrgId());
//							chird.setSuperiorDepId(chird.getParentId());
//						} else {
//							chird.setSuperiorOrgId(chird.getParentId());
//						}
//					}
					chird.setName(underName);
					chird.setPathName(underPathName);
					chird.setOrgType(Org.ORG_TYPE_DEP);
					chird.setPath(orgList.get(i).getPath()+chird.getId()+".");
					String code = preCode+"_"+PinyinUtil.getPinYinHeadChar(underName);
					if(orgMap.containsKey(code) && !chird.getPathName().equals(orgMap.get(code))) {
						code = code + "_" + chird.getId().substring(chird.getId().length()-3);
					}
					chird.setCode(code);
					//chird.setOrgType("实体");
				}
			}
		}else{//父组织不为空，从数据库中拿父组织
			chird.setId(UniqueIdUtil.getSuid());
			chird.setParentId(parentList.get(0).getId());
			chird.setDemId(demId);
			chird.setName(underName);
			chird.setPathName(underPathName);
			chird.setOrgType(Org.ORG_TYPE_DEP);

//			Org parentOrg1 = getById(chird.getParentId());
//			if(parentOrg1!=null) {
//				if(Org.ORG_TYPE_DEP.equals(parentOrg1.getOrgType())) {
//					chird.setSuperiorOrgId(parentOrg1.getSuperiorOrgId());
//					chird.setSuperiorDepId(chird.getParentId());
//				} else {
//					chird.setSuperiorOrgId(chird.getParentId());
//				}
//			}
			chird.setPath(parentList.get(0).getPath()+chird.getId()+".");
			String code = preCode+"_"+PinyinUtil.getPinYinHeadChar(underName);
			if(orgMap.containsKey(code) && !chird.getPathName().equals(orgMap.get(code))) {
				code = code + "_" + chird.getId().substring(chird.getId().length()-3);
			}
			chird.setCode(code);
			//chird.setOrgType("实体");
		}

		return dealOrg(chird,orgList,preCode,orgMap,orgCodeMap);
	}
	/**
	 * 处理组织的上下级关系
	 * @param supperPathName  父级路径名
	 * @param underPathName  子级路径名
	 * @param demId 对应维度id
	 * @param orgList
	 * @return
	 */
	public Org dealOrgUnder(String supperPathName,String underPathName,List<Org> orgList,String demId,String preCode,Map<String,String> orgMap,Map<String,List<Org>> pathOrgMap,Map<String,Org> orgCodeMap){
		String underName = underPathName.substring(underPathName.lastIndexOf("/")+1, underPathName.length());
		List<Org> chirList = pathOrgMap.get(underPathName);
		if(BeanUtils.isNotEmpty(chirList)){//子组织不为空
			for (Org org : chirList) {
				if(demId.equals(org.getDemId())){
					return org;
				}
			}
		}
		//子组织为空的情况
		List<Org> pList = pathOrgMap.get(supperPathName);
		List<Org> parentList = new ArrayList<Org>();
		if(BeanUtils.isNotEmpty(pList)) {
			for (Org org : pList) {
				if(demId.equals(org.getDemId())){
					parentList.add(org);
				}
			}
		}
		Org chird = new Org();
		if(BeanUtils.isEmpty(parentList)){//父组织为空，直接从orgList中寻找父级组织
			for(int i=0;i<orgList.size();i++){
				if(orgList.get(i).getPathName().equals(supperPathName)){
					chird.setId(UniqueIdUtil.getSuid());
					chird.setParentId(orgList.get(i).getId());
					chird.setDemId(demId);
					chird.setName(underName);
					chird.setPathName(underPathName);
					chird.setPath(orgList.get(i).getPath()+chird.getId()+".");
					String code = preCode+"_"+PinyinUtil.getPinYinHeadChar(underName);
					if(orgMap.containsKey(code) && !chird.getPathName().equals(orgMap.get(code))) {
						code = code + "_" + chird.getId().substring(chird.getId().length()-3);
					}
					chird.setCode(code);
					//chird.setOrgType("实体");
				}
			}
		}else{//父组织不为空，从数据库中拿父组织
			chird.setId(UniqueIdUtil.getSuid());
			chird.setParentId(parentList.get(0).getId());
			chird.setDemId(demId);
			chird.setName(underName);
			chird.setPathName(underPathName);
			chird.setPath(parentList.get(0).getPath()+chird.getId()+".");
			String code = preCode+"_"+PinyinUtil.getPinYinHeadChar(underName);
			if(orgMap.containsKey(code) && !chird.getPathName().equals(orgMap.get(code))) {
				code = code + "_" + chird.getId().substring(chird.getId().length()-3);
			}
			chird.setCode(code);
			//chird.setOrgType("实体");
		}

		return dealOrg(chird,orgList,preCode,orgMap,orgCodeMap);
	}
	/**
	 * 添加需要新增的组织
	 * @param org
	 * @param orgList
	 * @return
	 */
	public Org dealOrg(Org org,List<Org> orgList,String preCode,Map<String,String> orgMap,Map<String,Org> orgCodeMap){
		Org rtn = null;

		if(org.getOrderNo()==null){
			org.setOrderNo(99L); // 导入的排序号默认设置为99
		}
		if(BeanUtils.isEmpty(orgList)){
			if(orgMap.containsKey(org.getCode()) && !org.getPathName().equals(orgMap.get(org.getCode()))){
				org.setCode(org.getCode()+"_"+org.getId().substring(org.getId().length()-3));
			}
			orgList.add(org);
			orgMap.put(org.getCode(), org.getPathName());
			rtn = org;
		}else{
			Boolean flag = true;
			for(int i=0;i<orgList.size();i++){
				if(orgList.get(i).getPathName().equals(org.getPathName()) ){
					flag = false;
					rtn = orgList.get(i);
				}
				if(orgList.get(i).getName().equals(org.getName()) &&  orgList.get(i) != org){//新增数据中，组织同名的情况
					org.setCode(preCode+"_"+PinyinUtil.getPinYinHeadChar(org.getName())+org.getId().substring(org.getId().length()-3));
				}
				Org systemOrg = orgCodeMap.get(org.getCode());//判断是否与数据库中组织代码重复
				if(BeanUtils.isNotEmpty(systemOrg)){
					org.setCode(preCode+"_"+PinyinUtil.getPinYinHeadChar(org.getName())+org.getId().substring(org.getId().length()-3)+(i+1));
				}
				if(i == (orgList.size()-1) && flag ){
					if(BeanUtils.isNotEmpty(orgMap.get(org.getCode()))){
						org.setCode(org.getCode()+"_"+org.getId().substring(org.getId().length()-3));
					}
					orgList.add(org);
					orgMap.put(org.getCode(), org.getId());
					rtn = org;
				}
			}
		}
		return rtn;
	}

	private boolean validateAllRole(List<OrgVo> list){
		for (OrgVo orgVo : list) {
			if(StringUtil.isEmpty(orgVo.getName()) || StringUtil.isEmpty(orgVo.getCode())
			){
				return false;
			}
			if(!orgVo.getName().matches("^[\\s\\S]{1,30}$")
					|| !orgVo.getCode().matches("^[-0-9a-zA-Z_]{1,30}$")){
				return false;
			}
//			if(!(roleVo.getEnabled() == 0 || roleVo.getEnabled() == 1)){
//				return false;
//			}
		}
		return true;
	}

	@Override
	public List<OrgTreeVo> getTreeAllOrgByExtOrgId(String orgPath) throws Exception {
		List<OrgTreeVo> dbOrgs = new ArrayList<OrgTreeVo>();
		QueryWrapper<OrgTreeVo> queryWrapper = new QueryWrapper<OrgTreeVo>();
		queryWrapper.orderByAsc("ORDER_NO_");
		try(MultiTenantIgnoreResult setThreadLocalIgnore = MultiTenantHandler.setThreadLocalIgnore()){
			dbOrgs = baseMapper.getTreeAllOrgByExtOrgId(orgPath, queryWrapper);
		}
		catch(Exception e) {
			throw new BaseException(e.getMessage(),e);
		}
		return dbOrgs;
	}

	@Override
	public List<Map<String, Object>> getTreeCheckOrgByExtOrgId(String orgPath, String appType, String appId) throws Exception {
		List<Map<String, Object>> dbOrgs = new ArrayList<Map<String, Object>>();
		QueryWrapper<Org> queryWrapper = new QueryWrapper<Org>();
		queryWrapper.orderByAsc("ORDER_NO_");
		String tenantId = saaSConfig.isEnable()? baseContext.getCurrentTenantId(): null;
		try(MultiTenantIgnoreResult setThreadLocalIgnore = MultiTenantHandler.setThreadLocalIgnore()){
			dbOrgs = baseMapper.getTreeCheckOrgByExtOrgId(tenantId, orgPath, appType, appId, queryWrapper);
		}
		catch(Exception e) {
			throw new BaseException(e.getMessage(),e);
		}
		return dbOrgs;
	}
}
