package org.jeecg.modules.system.service.impl;

import com.alibaba.fastjson.JSONObject;
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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.YouBianCodeUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.*;
import org.jeecg.modules.system.mapper.*;
import org.jeecg.modules.system.model.DepartIdModel;
import org.jeecg.modules.system.model.SysDepartTreeModel;
import org.jeecg.modules.system.service.ISysAreaService;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.util.FindsDepartsChildrenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 部门表 服务实现类
 * <p>
 * 
 * @Author Steve
 * @Since 2019-01-22
 */
@Service
public class SysDepartServiceImpl extends ServiceImpl<SysDepartMapper, SysDepart> implements ISysDepartService {

    @Autowired
    private ISysAreaService sysAreaService;
    @Resource
    private SysUserDepartMapper userDepartMapper;
	@Resource
	private SysDepartRoleMapper sysDepartRoleMapper;
	@Resource
	private SysDepartPermissionMapper departPermissionMapper;
	@Resource
	private SysDepartRolePermissionMapper departRolePermissionMapper;
	@Resource
	private SysDepartRoleUserMapper departRoleUserMapper;
	@Autowired
	private ISysUserService sysUserService;
	@Override
	public List<SysDepartTreeModel> queryMyDeptTreeList(String departIds) {
		//根据部门id获取所负责部门
		LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<>();
		String[] codeArr = this.getMyDeptParentOrgCode(departIds);
		for(int i = 0; i< Objects.requireNonNull(codeArr).length; i++){
			query.or().likeRight(SysDepart::getOrgCode,codeArr[i]);
		}
		query.eq(SysDepart::getDelFlag, CommonConstant.DEL_FLAG_0.toString());
		query.orderByAsc(SysDepart::getDepartOrder);
		//将父节点ParentId设为null
		List<SysDepart> listDepts = this.list(query);
		for (String s : codeArr) {
			for (SysDepart dept : listDepts) {
				if (dept.getOrgCode().equals(s)) {
					dept.setParentId(null);
				}
			}
		}
		// 调用wrapTreeDataToTreeList方法生成树状数据
		return FindsDepartsChildrenUtil.wrapTreeDataToTreeList(listDepts);
	}

	/**
	 * queryTreeList 对应 queryTreeList 查询所有的部门数据,以树结构形式响应给前端
	 */
	@Override
	public List<SysDepartTreeModel> queryTreeList() {
		LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<>();
		query.eq(SysDepart::getDelFlag, CommonConstant.DEL_FLAG_0.toString());
		query.orderByAsc(SysDepart::getDepartOrder);
		List<SysDepart> list = this.list(query);
		// 调用wrapTreeDataToTreeList方法生成树状数据
		return FindsDepartsChildrenUtil.wrapTreeDataToTreeList(list);
	}
	/**
	 * queryTreeList 对应 queryTreeList 查询所有的部门数据,以树结构形式响应给前端
	 */
	@Override
	public List<SysDepartTreeModel> queryTreeListTest() {
		LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<>();
		query.eq(SysDepart::getDelFlag, CommonConstant.DEL_FLAG_0.toString());
		query.orderByAsc(SysDepart::getDepartOrder);
		query.eq(SysDepart::getAreaCode, "511602000000");
		List<SysDepart> list = this.list(query);
		// 调用wrapTreeDataToTreeList方法生成树状数据
		return FindsDepartsChildrenUtil.wrapTreeDataToTreeList(list);
	}

	@Cacheable(value = CacheConstant.SYS_DEPART_IDS_CACHE)
	@Override
	public List<DepartIdModel> queryDepartIdTreeList() {
		LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<>();
		query.eq(SysDepart::getDelFlag, CommonConstant.DEL_FLAG_0.toString());
		query.orderByAsc(SysDepart::getDepartOrder);
		List<SysDepart> list = this.list(query);
		// 调用wrapTreeDataToTreeList方法生成树状数据
		return FindsDepartsChildrenUtil.wrapTreeDataToDepartIdTreeList(list);
	}

	/**
	 * saveDepartData 对应 add 保存用户在页面添加的新的部门对象数据
	 */
	@Override
	public void saveDepartData(SysDepart sysDepart, String username) {
		if (sysDepart != null && username != null) {
			if (sysDepart.getParentId() == null) {
				sysDepart.setParentId("");
			}
			//String s = UUID.randomUUID().toString().replace("-", "");
			//sysDepart.setId(s);
			// 先判断该对象有无父级ID,有则意味着不是最高级,否则意味着是最高级
			// 获取父级ID
			String parentId = sysDepart.getParentId();
			//update-begin--Author:baihailong  Date:20191209 for：部门编码规则生成器做成公用配置
			JSONObject formData = new JSONObject();
			formData.put("parentId",parentId);
			//String[] codeArray = (String[]) FillRuleUtil.executeRule(FillRuleConstant.DEPART,formData);
			//update-end--Author:baihailong  Date:20191209 for：部门编码规则生成器做成公用配置
			//sysDepart.setOrgCode(codeArray[0]);
			sysDepart.setOrgCode("1001");
			sysDepart.setCreateTime(new Date());
			sysDepart.setDelFlag(CommonConstant.DEL_FLAG_0.toString());
			this.save(sysDepart);
		}

	}
	
	/**
	 * saveDepartData 的调用方法,生成部门编码和部门类型（作废逻辑）
	 * @deprecated
	 * @return
	 */
	private String[] generateOrgCode(String parentId) {	
		//update-begin--Author:Steve  Date:20190201 for：组织机构添加数据代码调整
				LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<>();
				LambdaQueryWrapper<SysDepart> query1 = new LambdaQueryWrapper<>();
				String[] strArray = new String[2];
		        // 创建一个List集合,存储查询返回的所有SysDepart对象
		        List<SysDepart> departList = new ArrayList<>();
				// 定义新编码字符串
				String newOrgCode = "";
				// 定义旧编码字符串
				String oldOrgCode = "";
				// 定义部门类型
				String orgType = "";
				// 如果是最高级,则查询出同级的org_code, 调用工具类生成编码并返回
				if (StringUtil.isNullOrEmpty(parentId)) {
					// 线判断数据库中的表是否为空,空则直接返回初始编码
					query1.eq(SysDepart::getParentId, "").or().isNull(SysDepart::getParentId);
					query1.orderByDesc(SysDepart::getOrgCode);
					departList = this.list(query1);
					if(departList == null || departList.size() == 0) {
						strArray[0] = YouBianCodeUtil.getNextYouBianCode(null);
						strArray[1] = "1";
						return strArray;
					}else {
					SysDepart depart = departList.get(0);
					oldOrgCode = depart.getOrgCode();
					orgType = depart.getOrgType();
					newOrgCode = YouBianCodeUtil.getNextYouBianCode(oldOrgCode);
					}
				} else { // 反之则查询出所有同级的部门,获取结果后有两种情况,有同级和没有同级
					// 封装查询同级的条件
					query.eq(SysDepart::getParentId, parentId);
					// 降序排序
					query.orderByDesc(SysDepart::getOrgCode);
					// 查询出同级部门的集合
					List<SysDepart> parentList = this.list(query);
					// 查询出父级部门
					SysDepart depart = this.getById(parentId);
					// 获取父级部门的Code
					String parentCode = depart.getOrgCode();
					// 根据父级部门类型算出当前部门的类型
					orgType = String.valueOf(Integer.valueOf(depart.getOrgType()) + 1);
					// 处理同级部门为null的情况
					if (parentList == null || parentList.size() == 0) {
						// 直接生成当前的部门编码并返回
						newOrgCode = YouBianCodeUtil.getSubYouBianCode(parentCode, null);
					} else { //处理有同级部门的情况
						// 获取同级部门的编码,利用工具类
						String subCode = parentList.get(0).getOrgCode();
						// 返回生成的当前部门编码
						newOrgCode = YouBianCodeUtil.getSubYouBianCode(parentCode, subCode);
					}
				}
				// 返回最终封装了部门编码和部门类型的数组
				strArray[0] = newOrgCode;
				strArray[1] = orgType;
				return strArray;
		//update-end--Author:Steve  Date:20190201 for：组织机构添加数据代码调整
	} 

	
	/**
	 * removeDepartDataById 对应 delete方法 根据ID删除相关部门数据
	 * 
	 */
	/*
	 * @Override
	 * 
	 * @Transactional public boolean removeDepartDataById(String id) {
	 * System.out.println("要删除的ID 为=============================>>>>>"+id); boolean
	 * flag = this.removeById(id); return flag; }
	 */

	/**
	 * updateDepartDataById 对应 edit 根据部门主键来更新对应的部门数据
	 */
	@Override
	public Boolean updateDepartDataById(SysDepart sysDepart, String username) {
		if (sysDepart != null && username != null) {
			sysDepart.setUpdateTime(new Date());
			sysDepart.setUpdateBy(username);
			this.updateById(sysDepart);
			return true;
		} else {
			return false;
		}

	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteBatchWithChildren(List<String> ids) {
		List<String> idList = new ArrayList<String>();
		for(String id: ids) {
			idList.add(id);
			this.checkChildrenExists(id, idList);
		}
		this.removeByIds(idList);
		//根据部门id获取部门角色id
		List<String> roleIdList = new ArrayList<>();
		LambdaQueryWrapper<SysDepartRole> query = new LambdaQueryWrapper<>();
		query.select(SysDepartRole::getId).in(SysDepartRole::getDepartId, idList);
		List<SysDepartRole> depRoleList = sysDepartRoleMapper.selectList(query);
		for(SysDepartRole deptRole : depRoleList){
			roleIdList.add(deptRole.getId());
		}
		//根据部门id删除用户与部门关系
		userDepartMapper.delete(new LambdaQueryWrapper<SysUserDepart>().in(SysUserDepart::getDepId,idList));
		//根据部门id删除部门授权
		departPermissionMapper.delete(new LambdaQueryWrapper<SysDepartPermission>().in(SysDepartPermission::getDepartId,idList));
		//根据部门id删除部门角色
		sysDepartRoleMapper.delete(new LambdaQueryWrapper<SysDepartRole>().in(SysDepartRole::getDepartId,idList));
		if(roleIdList != null && roleIdList.size()>0){
			//根据角色id删除部门角色授权
			departRolePermissionMapper.delete(new LambdaQueryWrapper<SysDepartRolePermission>().in(SysDepartRolePermission::getRoleId,roleIdList));
			//根据角色id删除部门角色用户信息
			departRoleUserMapper.delete(new LambdaQueryWrapper<SysDepartRoleUser>().in(SysDepartRoleUser::getDroleId,roleIdList));
		}
	}

	@Override
	public List<String> getSubDepIdsByDepId(String departId) {
		return this.baseMapper.getSubDepIdsByDepId(departId);
	}

	@Override
	public List<String> getMySubDepIdsByDepId(String departIds) {
		//根据部门id获取所负责部门
		String[] codeArr = this.getMyDeptParentOrgCode(departIds);
		return this.baseMapper.getSubDepIdsByOrgCodes(codeArr);
	}

	/**
	 * <p>
	 * 根据关键字搜索相关的部门数据
	 * </p>
	 */
	@Override
	public List<SysDepartTreeModel> searhBy(String keyWord,String myDeptSearch,String departIds) {
		LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<SysDepart>();
		List<SysDepartTreeModel> newList = new ArrayList<>();
		//myDeptSearch不为空时为我的部门搜索，只搜索所负责部门
		if(!StringUtil.isNullOrEmpty(myDeptSearch)){
			//departIds 为空普通用户或没有管理部门
			if(StringUtil.isNullOrEmpty(departIds)){
				return newList;
			}
			//根据部门id获取所负责部门
			String[] codeArr = this.getMyDeptParentOrgCode(departIds);
			for(int i=0;i<codeArr.length;i++){
				query.or().likeRight(SysDepart::getOrgCode,codeArr[i]);
			}
			query.eq(SysDepart::getDelFlag, CommonConstant.DEL_FLAG_0.toString());
		}
		query.like(SysDepart::getDepartName, keyWord);
		//update-begin--Author:huangzhilin  Date:20140417 for：[bugfree号]组织机构搜索回显优化--------------------
		SysDepartTreeModel model = new SysDepartTreeModel();
		List<SysDepart> departList = this.list(query);
		if(departList.size() > 0) {
			for(SysDepart depart : departList) {
				model = new SysDepartTreeModel(depart);
				model.setChildren(null);
	    //update-end--Author:huangzhilin  Date:20140417 for：[bugfree号]组织机构搜索功回显优化----------------------
				newList.add(model);
			}
			return newList;
		}
		return null;
	}

	/**
	 * 根据部门id删除并且删除其可能存在的子级任何部门
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean delete(String id) {
		List<String> idList = new ArrayList<>();
		idList.add(id);
		this.checkChildrenExists(id, idList);
		//清空部门树内存
		//FindsDepartsChildrenUtil.clearDepartIdModel();
		boolean ok = this.removeByIds(idList);
		//根据部门id获取部门角色id
		List<String> roleIdList = new ArrayList<>();
		LambdaQueryWrapper<SysDepartRole> query = new LambdaQueryWrapper<>();
		query.select(SysDepartRole::getId).in(SysDepartRole::getDepartId, idList);
		List<SysDepartRole> depRoleList = sysDepartRoleMapper.selectList(query);
		for(SysDepartRole deptRole : depRoleList){
			roleIdList.add(deptRole.getId());
		}
		//根据部门id删除用户与部门关系
		userDepartMapper.delete(new LambdaQueryWrapper<SysUserDepart>().in(SysUserDepart::getDepId,idList));
		//根据部门id删除部门授权
		departPermissionMapper.delete(new LambdaQueryWrapper<SysDepartPermission>().in(SysDepartPermission::getDepartId,idList));
		//根据部门id删除部门角色
		sysDepartRoleMapper.delete(new LambdaQueryWrapper<SysDepartRole>().in(SysDepartRole::getDepartId,idList));
		if(roleIdList != null && roleIdList.size()>0){
			//根据角色id删除部门角色授权
			departRolePermissionMapper.delete(new LambdaQueryWrapper<SysDepartRolePermission>().in(SysDepartRolePermission::getRoleId,roleIdList));
			//根据角色id删除部门角色用户信息
			departRoleUserMapper.delete(new LambdaQueryWrapper<SysDepartRoleUser>().in(SysDepartRoleUser::getDroleId,roleIdList));
		}
		return ok;
	}
	
	/**
	 * delete 方法调用
	 * @param id
	 * @param idList
	 */
	private void checkChildrenExists(String id, List<String> idList) {	
		LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<SysDepart>();
		query.eq(SysDepart::getParentId,id);
		List<SysDepart> departList = this.list(query);
		if(departList != null && departList.size() > 0) {
			for(SysDepart depart : departList) {
				idList.add(depart.getId());
				this.checkChildrenExists(depart.getId(), idList);
			}
		}
	}

	@Override
	public List<SysDepart> queryUserDeparts(String userId) {
		return baseMapper.queryUserDeparts(userId);
	}

	@Override
	public List<SysDepart> queryDepartsByUsername(String username) {
		return baseMapper.queryDepartsByUsername(username);
	}

	/**
	 * 根据用户所负责部门ids获取父级部门编码
	 * @param departIds
	 * @return
	 */
	private String[] getMyDeptParentOrgCode(String departIds){
		//根据部门id查询所负责部门
		LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<SysDepart>();
		query.eq(SysDepart::getDelFlag, CommonConstant.DEL_FLAG_0.toString());
		query.in(SysDepart::getId, Arrays.asList(departIds.split(",")));
		query.orderByAsc(SysDepart::getOrgCode);
		List<SysDepart> list = this.list(query);
		//查找根部门
		if(list == null || list.size()==0){
			return null;
		}
		String orgCode = this.getMyDeptParentNode(list);
		String[] codeArr = orgCode.split(",");
		return codeArr;
	}

	/**
	 * 获取负责部门父节点
	 * @param list
	 * @return
	 */
	private String getMyDeptParentNode(List<SysDepart> list){
		Map<String,String> map = new HashMap<>();
		//1.先将同一公司归类
		for(SysDepart dept : list){
			String code = dept.getOrgCode().substring(0,3);
			if(map.containsKey(code)){
				String mapCode = map.get(code)+","+dept.getOrgCode();
				map.put(code,mapCode);
			}else{
				map.put(code,dept.getOrgCode());
			}
		}
		StringBuffer parentOrgCode = new StringBuffer();
		//2.获取同一公司的根节点
		for(String str : map.values()){
			String[] arrStr = str.split(",");
			parentOrgCode.append(",").append(this.getMinLengthNode(arrStr));
		}
		return parentOrgCode.substring(1);
	}

	/**
	 * 获取同一公司中部门编码长度最小的部门
	 * @param str
	 * @return
	 */
	private String getMinLengthNode(String[] str){
		int min =str[0].length();
		StringBuilder orgCode = new StringBuilder(str[0]);
		for(int i =1;i<str.length;i++){
			if(str[i].length()<=min){
				min = str[i].length();
				orgCode.append(",").append(str[i]);
			}
		}
		return orgCode.toString();
	}
    /**
     * 获取部门树信息根据关键字
     * @param keyWord
     * @return
     */
    @Override
    public List<SysDepartTreeModel> queryTreeByKeyWord(String keyWord) {
        LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<SysDepart>();
        query.eq(SysDepart::getDelFlag, CommonConstant.DEL_FLAG_0.toString());
        query.orderByAsc(SysDepart::getDepartOrder);
        List<SysDepart> list = this.list(query);
        // 调用wrapTreeDataToTreeList方法生成树状数据
        List<SysDepartTreeModel> listResult = FindsDepartsChildrenUtil.wrapTreeDataToTreeList(list);
        List<SysDepartTreeModel> treelist =new ArrayList<>();
        if(StringUtils.isNotBlank(keyWord)){
            this.getTreeByKeyWord(keyWord,listResult,treelist);
        }else{
            return listResult;
        }
        return treelist;
    }

	/**
	 * 根据parentId查询部门树
	 * @param parentId
	 * @return
	 */
	@Override
	public List<SysDepartTreeModel> queryTreeListByPid(String parentId) {
		List<SysDepart> list = this.baseMapper.queryTreeListByPid(parentId);
		List<SysDepartTreeModel> records = new ArrayList<>();
		for (int i = 0; i < list.size(); i++) {
			SysDepart depart = list.get(i);
            SysDepartTreeModel treeModel = new SysDepartTreeModel(depart);
            //TODO 异步树加载key拼接__+时间戳,以便于每次展开节点会刷新数据
			treeModel.setKey(treeModel.getKey()+"__"+System.currentTimeMillis());
            Integer count=this.baseMapper.queryCountByPid(depart.getId());
            if(count>0){
                treeModel.setIsLeaf(false);
            }else{
                treeModel.setIsLeaf(true);
            }
            records.add(treeModel);
        }
		return records;
	}
	@Override
	public SysDepart queryCompByOrgCode(String orgCode) {
		int length = YouBianCodeUtil.zhanweiLength;
		String compyOrgCode = orgCode.substring(0,length);
		return this.baseMapper.queryCompByOrgCode(compyOrgCode);
	}
	/**
	 * 根据id查询下级部门
	 * @return
	 */
	@Override
	public List<SysDepart> queryDeptByPid(String pid) {
		return this.baseMapper.queryDeptByPid(pid);
	}

	@Override
	public String[] findParentIdPath(String Id) {
		List<String> paths = new ArrayList<>();
		List<String> parentPath = findParentPath(Id, paths);
		Collections.reverse(parentPath);
		return parentPath.toArray(new String[parentPath.size()]);
	}


	@Override
	public List<String> getPidByAreaId(String areaId) {
		List<String> idByAreaId = this.baseMapper.getIdByAreaId(areaId);
		return idByAreaId;
	}

	@Override
	public List<SysDepartTreeModel> queryTreeListByAreaId(String areaId) {
		List<SysDepart> list = this.list(new QueryWrapper<SysDepart>().eq("area_id",areaId).orderByAsc("depart_order"));
		List<SysDepartTreeModel> listResult = FindsDepartsChildrenUtil.wrapTreeDataToTreeList(list);
		return listResult;
	}

	@Override
	public IPage<SysDepart> queryPage(Integer pageNo, Integer pageSize, String name, String code,String areaId) {
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		//获取用户权限信息
		Map<String, Object> userOtherInfo = sysUserService.getUserOtherInfo(loginUser);
		if (userOtherInfo == null) {
			return null;
		}
		Boolean isAreaAdmin = (Boolean) userOtherInfo.get("isAreaAdmin");
		Boolean isBasicOperation = (Boolean) userOtherInfo.get("isBasicOperation");
		Boolean isDeptAdmin = (Boolean) userOtherInfo.get("isDeptAdmin");
		Boolean isAdmin = (Boolean) userOtherInfo.get("isAdmin");
        SysDepart currentDept = (SysDepart) userOtherInfo.get("currentDept");
        SysArea currentArea = (SysArea) userOtherInfo.get("currentArea");
        QueryWrapper<SysDepart> wrapper = new QueryWrapper<>();

		if(!StringUtils.isEmpty(name)){
			wrapper.and((obj)->{
				obj.like("depart_name",name);
			});
		}
		if(!StringUtils.isEmpty(code)){
			wrapper.and((obj)->{
				obj.eq("SOCIAL_CREDIT_CODE",code);
			});
		}
		if (!isAdmin&&!isBasicOperation){
			if (isDeptAdmin&&!isAreaAdmin){
				wrapper.eq("area_id",currentArea.getId());
			}else if (isAreaAdmin) {
                //List<String> childId = sysAreaService.getChildId(currentArea.getId());
                List<String> childId = sysAreaService.quickGetChild(currentArea.getId());
                childId.add(currentArea.getId());
                wrapper.in("area_id", childId);
            }else {
				wrapper.eq("area_id",currentArea.getId());
			}
		}else {
			wrapper.eq("area_id",areaId);
		}
		Page<SysDepart> page = new Page<SysDepart>(pageNo, pageSize);
		return this.page(page,wrapper);
	}

	@Override
	public List<SysDepart> listWithTreeById(String id) {
		//1、查出所有分类
		List<SysDepart> entities = baseMapper.selectList(null);
		//2、组成父子的树形结构
		//2.1、找到所有的一级分类
		List<SysDepart> level1Menus = entities.stream().filter(SysDepart ->
				SysDepart.getParentId().equals(id)
		).map((menu)->{
			menu.setChildren(getChildrens(menu,entities));
			return menu;
		}).sorted((menu1,menu2)->{
			return (menu1.getDepartOrder()==null?0:menu1.getDepartOrder()) - (menu2.getDepartOrder()==null?0:menu2.getDepartOrder());
		}).collect(Collectors.toList());
		return level1Menus;
	}

	@Override
	public List<SysDepart> queryByAreaId(String areaId) {
        List<SysDepart> list = this.list(new QueryWrapper<SysDepart>().eq("area_id", areaId).eq("del_flag", "0"));

        return list.stream().filter(SysArea ->
                "".equals(SysArea.getParentId())
        ).map((menu) -> {
            menu.setChildren(getChildrens(menu, list));
            return menu;
        }).sorted(Comparator.comparingInt(menu -> (menu.getDepartOrder() == null ? 0 : menu.getDepartOrder()))).collect(Collectors.toList());
    }

	@Override
	public List<SysDepart> queryByAreaId(String areaId, String deptId) {
		List<SysDepart> list = this.list(new QueryWrapper<SysDepart>().eq("area_id",areaId).eq("del_flag","0").eq("id",deptId));
		return list;
	}

	@Override
	public List<SysDepart> queryTreeByAreaId(String areaId, String id) {
        List<SysDepart> list = this.list(new QueryWrapper<SysDepart>().eq("area_id", areaId).eq("del_flag", "0"));

        return list.stream().filter(SysArea ->
                SysArea.getId().equals(id)
        ).map((menu) -> {
            menu.setChildren(getChildrens(menu, list));
            return menu;
        }).sorted(Comparator.comparingInt(menu -> (menu.getDepartOrder() == null ? 0 : menu.getDepartOrder()))).collect(Collectors.toList());
    }

	@Override
	public List<SysDepart> getDeptByAreaId(String areaId) {
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		//获取用户权限信息
		Map<String, Object> userOtherInfo = sysUserService.getUserOtherInfo(loginUser);
		List<SysDepart> list = null;
		if (userOtherInfo == null) {
			return list;
		}

		Boolean isBasicOperation = (Boolean) userOtherInfo.get("isBasicOperation");
		Boolean isAreaAdmin = (Boolean) userOtherInfo.get("isAreaAdmin");
		Boolean isDeptAdmin = (Boolean) userOtherInfo.get("isDeptAdmin");
		Boolean isAdmin = (Boolean) userOtherInfo.get("isAdmin");
        SysDepart currentDept = (SysDepart) userOtherInfo.get("currentDept");
        SysArea currentArea = (SysArea) userOtherInfo.get("currentArea");

		if (!isAdmin&&!isAreaAdmin&&!isDeptAdmin&&!isBasicOperation){

			if (areaId.equals(currentArea.getId())){
				int count = this.count(new QueryWrapper<SysDepart>().eq("parent_id", currentDept.getId()));
				if (!oConvertUtils.isEmpty(currentDept.getParentId())){
					list = this.queryTreeByAreaId(areaId,currentDept.getParentId());
				}else if (count>0){
					list = this.queryTreeByAreaId(areaId,currentDept.getId());
				}else {
					list = this.queryByAreaId(areaId,currentDept.getId());
				}
			}else {
				return new ArrayList<>();
			}
		}else if (isDeptAdmin&&!isAdmin&&!isAreaAdmin&&!isBasicOperation){
			if (areaId.equals(currentArea.getId())){
				int count = this.count(new QueryWrapper<SysDepart>().eq("parent_id", currentDept.getId()));
				if (!oConvertUtils.isEmpty(currentDept.getParentId())){
					list = this.queryTreeByAreaId(areaId,currentDept.getParentId());
				}else if (count>0){
					list = this.queryTreeByAreaId(areaId,currentDept.getId());
				}else {
					list = this.queryByAreaId(areaId,currentDept.getId());
				}
			}else {
				return new ArrayList<>();
			}
		}else if (isAreaAdmin&&!isAdmin&&!isBasicOperation) {
            //List<String> childId = sysAreaService.getChildId(currentArea.getId());
            List<String> childId = sysAreaService.quickGetChild(currentArea.getId());
            childId.add(currentArea.getId());
            if (childId.contains(areaId)) {
                list = this.queryByAreaId(areaId);
            } else {
                return new ArrayList<>();
            }
        } else {
			list = this.queryByAreaId(areaId);
		}
		return list;
	}

	@Override
    public SysDepart getValidDeptById(String departs) {
        return this.baseMapper.getValidDeptById(departs);
    }

	@Override
	public List<SysDepart> getValidDeptByAreaId(String areaId) {
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		//获取用户权限信息
		Map<String, Object> userOtherInfo = sysUserService.getUserOtherInfo(loginUser);
		List<SysDepart> list = null;
		if (userOtherInfo == null) {
			return null;
		}
		Boolean isAreaAdmin = (Boolean) userOtherInfo.get("isAreaAdmin");
		Boolean isBasicOperation = (Boolean) userOtherInfo.get("isBasicOperation");
		Boolean isDeptAdmin = (Boolean) userOtherInfo.get("isDeptAdmin");
		Boolean isAdmin = (Boolean) userOtherInfo.get("isAdmin");
        SysDepart currentDept = (SysDepart) userOtherInfo.get("currentDept");
        SysArea currentArea = (SysArea) userOtherInfo.get("currentArea");

		if (!isAdmin&&!isAreaAdmin&&!isDeptAdmin&&!isBasicOperation){
			//list = this.list(new QueryWrapper<SysDepart>().eq("id", currentDept.getId()).eq("status","1"));
			int count = this.count(new QueryWrapper<SysDepart>().eq("parent_id", currentDept.getId()));
			if (!oConvertUtils.isEmpty(currentDept.getParentId())){
				list = this.queryVaildByAreaId(areaId,currentDept.getParentId());
			}else if (count>0){
				list = this.queryVaildByAreaId(areaId,currentDept.getId());
			}else {
				list = this.getValidByAreaId(areaId,currentDept.getId());
			}
		}else if (isDeptAdmin&&!isAdmin&&!isAreaAdmin&&!isBasicOperation){
			int count = this.count(new QueryWrapper<SysDepart>().eq("parent_id", currentDept.getId()));
			if (!oConvertUtils.isEmpty(currentDept.getParentId())){
				list = this.queryVaildByAreaId(areaId,currentDept.getParentId());
			}else if (count>0){
				list = this.queryVaildByAreaId(areaId,currentDept.getId());
			}else {
				list = this.getValidByAreaId(areaId,currentDept.getId());
			}
		}else {
			list = this.getVaildByAreaId(areaId);
		}
		return list;
	}

	@Override
	public SysDepart getDeptByUserId(String userId) {
		return baseMapper.getDeptByUserId(userId);
	}

	@Override
	public List<String> getUserByDept(String id) {
		return this.baseMapper.getUserByDept(id);
	}

	@Override
	public List<String> getDeptIdByAreaId(String id) {
		return this.baseMapper.getIdByAreaId(id);
	}

	@Override
	public List<SysDepart> queryDeptList(String departName) {
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		//获取用户权限信息
		Map<String, Object> userOtherInfo = sysUserService.getUserOtherInfo(loginUser);
		List<SysDepart> list;
		if (userOtherInfo == null) {
			return null;
		}
		Boolean isAreaAdmin = (Boolean) userOtherInfo.get("isAreaAdmin");
		Boolean isBasicOperation = (Boolean) userOtherInfo.get("isBasicOperation");
		Boolean isDeptAdmin = (Boolean) userOtherInfo.get("isDeptAdmin");
		Boolean isAdmin = (Boolean) userOtherInfo.get("isAdmin");
        SysDepart currentDept = (SysDepart) userOtherInfo.get("currentDept");
        SysArea currentArea = (SysArea) userOtherInfo.get("currentArea");
		if (!isAdmin&&!isBasicOperation){
			if (isAreaAdmin){
				list = baseMapper.queryDepartList(currentArea.getId(),departName);
			}else if(isDeptAdmin){
				QueryWrapper<SysDepart> queryWrapper = new QueryWrapper<>();
				queryWrapper.like("depart_simple_name",departName).eq("status","1");
				int count = this.count(new QueryWrapper<SysDepart>().eq("parent_id", currentDept.getId()));
				if (!oConvertUtils.isEmpty(currentDept.getParentId())){
					queryWrapper.and(wrapper ->wrapper.eq("id", currentDept.getParentId()).or().eq("id", currentDept.getId()));
				    list = this.list(queryWrapper);
				}else if (count>0){
					queryWrapper.and(wrapper -> wrapper.eq("parent_id", currentDept.getId()).or().eq("id", currentDept.getId()));
				    list = this.list(queryWrapper);
				}else {
					queryWrapper.and(wrapper -> wrapper.eq("id", currentDept.getId()));
					list = this.list(queryWrapper);
				}
			}else {
				list = this.list(new QueryWrapper<SysDepart>().like("depart_simple_name",departName).eq("id",currentDept.getId()).eq("status","1"));
			}
		}else {
			list = this.list(new QueryWrapper<SysDepart>().like("depart_simple_name",departName).eq("status","1"));
		}
		return list;
	}

	@Override
	public Map<String, String> queryUserDeptAreaInfo(String username) {
		return this.baseMapper.queryUserDeptAreaInfo(username);
	}

    @Override
    public List<String> queryUserAreaAuth(String username) {
        return this.baseMapper.queryUserAreaAuth(username);
    }

    private List<SysDepart> getVaildByAreaId(String areaId) {
        List<SysDepart> list = this.list(new QueryWrapper<SysDepart>().eq("area_id", areaId).eq("del_flag", "0").eq("status", "1"));
        return list.stream().filter(SysArea ->
                "".equals(SysArea.getParentId())
        ).map((menu) -> {
            menu.setChildren(getChildrens(menu, list));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getDepartOrder() == null ? 0 : menu1.getDepartOrder()) - (menu2.getDepartOrder() == null ? 0 : menu2.getDepartOrder());
        }).collect(Collectors.toList());
    }

	private List<SysDepart> getValidByAreaId(String areaId, String id) {
		return this.list(new QueryWrapper<SysDepart>().eq("area_id",areaId).eq("del_flag","0").eq("id",id).eq("status","1"));
	}

	private List<SysDepart> queryVaildByAreaId(String areaId, String id) {
        List<SysDepart> list = this.list(new QueryWrapper<SysDepart>().eq("area_id", areaId).eq("del_flag", "0").eq("status", "1"));
        return list.stream().filter(SysArea ->
                SysArea.getId().equals(id)
        ).map((menu) -> {
            menu.setChildren(getChildrens(menu, list));
            return menu;
        }).sorted(Comparator.comparingInt(menu -> (menu.getDepartOrder() == null ? 0 : menu.getDepartOrder()))).collect(Collectors.toList());
    }

	//递归查找所有菜单的子菜单
	private List<SysDepart> getChildrens(SysDepart root ,List<SysDepart> all){
		return all.stream().filter(SysDepart -> SysDepart.getParentId().equals(root.getId())).map(sysDepart -> {
			//1、找到子菜单
			sysDepart.setChildren(getChildrens(sysDepart, all));
			return sysDepart;
		}).sorted((menu1, menu2) -> {
			return (menu1.getDepartOrder() == null ? 0 : menu1.getDepartOrder()) - (menu2.getDepartOrder() == null ? 0 : menu2.getDepartOrder());
		}).collect(Collectors.toList());
	}

	private List<String> findParentPath(String Id, List<String> paths) {
		//1、收集当前节点id
		paths.add(Id);
		SysDepart byId = this.getById(Id);
//        if(!byId.getParentId().equals("")){
//            findParentPath(byId.getParentId(),paths);
//        }
		//!byId.getParentId().equals(String.valueOf(0) ||
		//!byId.getParentId().equals("")||!byId.getParentId().equals("0")
		if(!"".equals(byId.getParentId())){
			findParentPath(byId.getParentId(),paths);
		}
		return paths;
	}

	/**
     * 根据关键字筛选部门信息
     * @param keyWord
     * @return
     */
    public void getTreeByKeyWord(String keyWord,List<SysDepartTreeModel> allResult,List<SysDepartTreeModel>  newResult){
        for (SysDepartTreeModel model:allResult) {
            if (model.getDepartName().contains(keyWord)){
                newResult.add(model);
                continue;
            }else if(model.getChildren()!=null){
                getTreeByKeyWord(keyWord,model.getChildren(),newResult);
            }
        }
    }
}
