package com.yunzhupaas.permission.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
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.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.ImmutableMap;
import com.yunzhupaas.base.ActionResult;
import com.yunzhupaas.base.UserInfo;
import com.yunzhupaas.base.entity.DictionaryDataEntity;
import com.yunzhupaas.base.service.DictionaryDataService;
import com.yunzhupaas.base.service.SuperServiceImpl;
import com.yunzhupaas.constant.YunzhupaasConst;
import com.yunzhupaas.constant.MsgCode;
import com.yunzhupaas.constant.PermissionConst;
import com.yunzhupaas.message.service.SynThirdDingTalkService;
import com.yunzhupaas.message.service.SynThirdQyService;
import com.yunzhupaas.permission.entity.OrganizeAdministratorEntity;
import com.yunzhupaas.permission.entity.OrganizeEntity;
import com.yunzhupaas.permission.entity.PositionEntity;
import com.yunzhupaas.permission.mapper.OrganizeMapper;
import com.yunzhupaas.permission.model.authorize.AuthorizeConditionEnum;
import com.yunzhupaas.permission.model.organize.OrganizeConditionModel;
import com.yunzhupaas.permission.model.organize.OrganizeModel;
import com.yunzhupaas.permission.model.organize.PaginationOrganize;
import com.yunzhupaas.permission.service.*;
import com.yunzhupaas.permission.util.PermissionUtil;
import com.yunzhupaas.util.*;
import com.yunzhupaas.util.enums.DictionaryDataEnum;
import com.yunzhupaas.util.treeutil.SumTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 组织机构
 *
 * @author 云筑产品开发平台组
 * @version V3.1.0
 * @copyright 深圳市乐程软件有限公司
 * @date 2024-09-26 上午9:18
 */
@Service
public class OrganizeServiceImpl extends SuperServiceImpl<OrganizeMapper, OrganizeEntity> implements OrganizeService {

    @Autowired
    private PositionService positionService;
    @Autowired
    private CacheKeyUtil cacheKeyUtil;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserRelationService userRelationService;
    @Autowired
    private OrganizeRelationService organizeRelationService;
    @Autowired
    private SynThirdQyService synThirdQyService;
    @Autowired
    private SynThirdDingTalkService synThirdDingTalkService;
    @Autowired
    private OrganizeAdministratorService organizeAdministratorService;
    @Autowired
    private DictionaryDataService dictionaryDataService;

    @Override
    public List<OrganizeEntity> getListAll(List<String> idAll, String keyWord) {
        // 定义变量判断是否需要使用修改时间倒序
        boolean flag = false;
        List<OrganizeEntity> list = new ArrayList<>();
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtil.isNotEmpty(keyWord)) {
            flag = true;
            queryWrapper.lambda().and(
                    t -> t.like(OrganizeEntity::getFullName, keyWord)
                            .or().like(OrganizeEntity::getEnCode, keyWord));
        }
        // 排序
        queryWrapper.lambda().orderByAsc(OrganizeEntity::getSortCode)
                .orderByDesc(OrganizeEntity::getCreatorTime);
        if (flag) {
            queryWrapper.lambda().orderByDesc(OrganizeEntity::getLastModifyTime);
        }
        if (idAll.size() > 0) {
            queryWrapper.lambda().in(OrganizeEntity::getId, idAll);
            list = this.list(queryWrapper);
        }
        return list;
    }

    @Override
    public List<OrganizeEntity> getDepsByParentId(String id) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getParentId, id);
        queryWrapper.lambda().eq(OrganizeEntity::getCategory, PermissionConst.DEPARTMENT);
        queryWrapper.lambda().orderByAsc(OrganizeEntity::getSortCode)
                .orderByDesc(OrganizeEntity::getCreatorTime);
        List<OrganizeEntity> list = this.list(queryWrapper);
        return list;
    }

    @Override
    public List<OrganizeEntity> getList(boolean filterEnabledMark) {
        return getList(null, filterEnabledMark);
    }

    @Override
    public List<OrganizeEntity> getListByEnabledMark(Boolean enable) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        if (enable) {
            queryWrapper.lambda().eq(OrganizeEntity::getEnabledMark, 1);
        }
        Map<String, OrganizeEntity> orgMaps = getBaseOrgMaps(queryWrapper, ImmutableMap.of(
                OrganizeEntity::getSortCode, true,
                OrganizeEntity::getCreatorTime, false), null, false);

        // Map<String, OrganizeEntity> entityList = new LinkedHashMap<>();
        // if (StringUtil.isNotEmpty(keyword)) {
        // getParentOrganize(orgMaps, orgMaps, entityList);
        // orgMaps.clear();
        // orgMaps = entityList;
        // }
        return new LinkedList<>(orgMaps.values());
    }

    @Override
    public OrganizeEntity getInfoByFullName(String fullName) {
        if (StringUtil.isEmpty(fullName)) {
            return null;
        }
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getFullName, fullName);
        List<OrganizeEntity> list = this.list(queryWrapper);
        return list.size() > 0 ? list.get(0) : null;
    }

    @Override
    public List<OrganizeEntity> getList(String keyword, boolean filterEnabledMark) {
        return new LinkedList<>(getOrgMaps(keyword, filterEnabledMark, null).values());
    }

    /**
     * 获取组织信息
     *
     * @return OrgId, OrgEntity
     */
    @Override
    public Map<String, OrganizeEntity> getOrgMapsAll(SFunction<OrganizeEntity, ?>... columns) {
        return getOrgMaps(null, false, null, columns);
    }

    /**
     * 获取组织信息
     *
     * @param keyword
     * @param filterEnabledMark
     * @param type
     * @return OrgId, OrgEntity
     */
    @Override
    public Map<String, OrganizeEntity> getOrgMaps(String keyword, boolean filterEnabledMark, String type,
            SFunction<OrganizeEntity, ?>... columns) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtil.isNotEmpty(keyword)) {
            queryWrapper.lambda().and(
                    t -> t.like(OrganizeEntity::getFullName, keyword)
                            .or().like(OrganizeEntity::getEnCode, keyword.toLowerCase()));
        }
        if (filterEnabledMark) {
            queryWrapper.lambda().eq(OrganizeEntity::getEnabledMark, 1);
        }
        if (StringUtil.isNotEmpty(type)) {
            queryWrapper.lambda().eq(OrganizeEntity::getCategory, type);
        }
        Map<String, OrganizeEntity> orgMaps = getBaseOrgMaps(queryWrapper, ImmutableMap.of(
                OrganizeEntity::getSortCode, true,
                OrganizeEntity::getCreatorTime, false), null, false);

        Map<String, OrganizeEntity> entityList = new LinkedHashMap<>();
        if (StringUtil.isNotEmpty(keyword)) {
            getParentOrganize(orgMaps, orgMaps, entityList);
            orgMaps.clear();
            orgMaps = entityList;
        }
        return orgMaps;
    }

    /**
     * 组织基础过滤
     *
     * @param queryWrapper
     * @param orderBy      Map<Column, isAsc>
     * @param groupBy      Column
     * @param columns      query
     * @return
     */
    public Map<String, OrganizeEntity> getBaseOrgMaps(QueryWrapper<OrganizeEntity> queryWrapper,
            Map<SFunction<OrganizeEntity, ?>, Boolean> orderBy, List<SFunction<OrganizeEntity, ?>> groupBy,
            boolean bigColumnHas, SFunction<OrganizeEntity, ?>... columns) {
        if (queryWrapper == null) {
            queryWrapper = new QueryWrapper<>();
        }
        LambdaQueryWrapper<OrganizeEntity> lambdaQueryWrapper = queryWrapper.lambda();

        List<SFunction<OrganizeEntity, ?>> columnList;
        List<SFunction<OrganizeEntity, ?>> bigColumnList = null;
        // 没有指定查询字段就返回全部字段
        if (columns == null || columns.length == 0) {
            columnList = Arrays.asList(OrganizeEntity::getId, OrganizeEntity::getParentId, OrganizeEntity::getCategory,
                    OrganizeEntity::getEnCode, OrganizeEntity::getFullName, OrganizeEntity::getManagerId,
                    OrganizeEntity::getSortCode, OrganizeEntity::getEnabledMark, OrganizeEntity::getOrganizeIdTree,
                    OrganizeEntity::getCreatorTime, OrganizeEntity::getCreatorUserId, OrganizeEntity::getLastModifyTime,
                    OrganizeEntity::getLastModifyUserId, OrganizeEntity::getDeleteMark, OrganizeEntity::getDeleteTime,
                    OrganizeEntity::getDeleteUserId, OrganizeEntity::getTenantId);
            // 把长文本字段分开查询, 默认带有排序， 数据量大的情况长文本字段参与排序速度非常慢
            if (bigColumnHas) {
                bigColumnList = Arrays.asList(
                        OrganizeEntity::getId,
                        OrganizeEntity::getDescription,
                        OrganizeEntity::getPropertyJson);
            }
        } else {
            columnList = new ArrayList<>(Arrays.asList(columns));
            // 指定字段中没有ID， 强制添加ID字段
            if (!columnList.contains((SFunction<OrganizeEntity, ?>) OrganizeEntity::getId)) {
                columnList.add(OrganizeEntity::getId);
            }
        }
        lambdaQueryWrapper.select(columnList);
        QueryWrapper<OrganizeEntity> bigColumnQuery = null;
        if (bigColumnList != null) {
            // 获取大字段不参与排序
            bigColumnQuery = queryWrapper.clone();
        }
        // 排序
        if (orderBy != null && !orderBy.isEmpty()) {
            orderBy.forEach((k, v) -> {
                lambdaQueryWrapper.orderBy(true, v, k);
            });
        }
        // 分组
        if (groupBy != null && !groupBy.isEmpty()) {
            lambdaQueryWrapper.groupBy(groupBy);
        }
        List<OrganizeEntity> list = this.list(queryWrapper);

        Map<String, OrganizeEntity> orgMaps = new LinkedHashMap<>(list.size(), 1);
        list.forEach(t -> orgMaps.put(t.getId(), t));

        if (bigColumnList != null) {
            // 获取大字段数据
            bigColumnQuery.lambda().select(bigColumnList);
            List<OrganizeEntity> listBigFields = this.list(bigColumnQuery);
            listBigFields.forEach(t -> {
                OrganizeEntity organizeEntity = orgMaps.get(t.getId());
                if (organizeEntity != null) {
                    organizeEntity.setPropertyJson(t.getPropertyJson());
                    organizeEntity.setDescription(t.getDescription());
                }
            });
        }
        return orgMaps;
    }

    /**
     * 获取父级集合
     *
     * @param list       需要遍历的集合
     * @param entityList 结果集
     */
    private void getParentOrganize(Map<String, OrganizeEntity> list, Map<String, OrganizeEntity> searchList,
            Map<String, OrganizeEntity> entityList) {
        Map<String, OrganizeEntity> list1 = new LinkedHashMap<>();
        searchList.forEach((id, entity) -> {
            entityList.put(id, entity);
            OrganizeEntity info = list.get(id);
            if (info == null) {
                info = getInfo(id);
            }
            if (Objects.nonNull(info)) {
                if (StringUtil.isNotEmpty(info.getParentId()) && !"-1".equals(info.getParentId())) {
                    OrganizeEntity organizeEntity = list.get(info.getParentId());
                    if (organizeEntity == null) {
                        organizeEntity = getInfo(info.getParentId());
                    }
                    if (organizeEntity != null) {
                        list1.put(organizeEntity.getId(), organizeEntity);
                        getParentOrganize(list, list1, entityList);
                    }
                } else if (StringUtil.isNotEmpty(info.getParentId()) && "-1".equals(info.getParentId())) {
                    entityList.put(id, info);
                }
            }
        });
    }

    @Override
    public List<OrganizeEntity> getOrgEntityList(List<String> idList, Boolean enable) {
        if (!idList.isEmpty()) {
            QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(OrganizeEntity::getId, idList);
            if (enable) {
                queryWrapper.lambda().eq(OrganizeEntity::getEnabledMark, 1);
            }
            // queryWrapper.lambda().select(OrganizeEntity::getId,
            // OrganizeEntity::getFullName);
            return this.list(queryWrapper);
        }
        return Collections.EMPTY_LIST;
    }

    @Override
    public List<OrganizeEntity> getOrgEntityList(Set<String> idList) {
        if (idList.size() > 0) {
            QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().select(OrganizeEntity::getId, OrganizeEntity::getFullName).in(OrganizeEntity::getId,
                    idList);
            List<OrganizeEntity> list = this.list(queryWrapper);
            return list;
        }
        return new ArrayList<>();
    }

    @Override
    public Map<String, Object> getOrgMap() {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().select(OrganizeEntity::getId, OrganizeEntity::getFullName);
        List<OrganizeEntity> list = this.list(queryWrapper);
        return list.stream().collect(Collectors.toMap(OrganizeEntity::getId, OrganizeEntity::getFullName));
    }

    @Override
    public Map<String, Object> getOrgEncodeAndName(String type) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().select(OrganizeEntity::getId, OrganizeEntity::getFullName, OrganizeEntity::getEnCode);
        queryWrapper.lambda().eq(OrganizeEntity::getCategory, type);
        List<OrganizeEntity> list = this.list(queryWrapper);
        return list.stream().collect(
                Collectors.toMap(o -> o.getFullName() + "/" + o.getEnCode(), OrganizeEntity::getId, (v1, v2) -> v2));
    }

    @Override
    public Map<String, Object> getOrgNameAndId(String type) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().select(OrganizeEntity::getId, OrganizeEntity::getFullName);
        if (StringUtil.isNotEmpty(type)) {
            queryWrapper.lambda().eq(OrganizeEntity::getCategory, type);
        }
        List<OrganizeEntity> list = this.list(queryWrapper);
        Map<String, Object> allOrgMap = new HashMap<>();
        for (OrganizeEntity entity : list) {
            allOrgMap.put(entity.getFullName(), entity.getId());
        }
        return allOrgMap;
    }

    @Override
    public List<OrganizeEntity> getOrgRedisList() {
        if (redisUtil.exists(cacheKeyUtil.getOrganizeList())) {
            return JsonUtil.getJsonToList(redisUtil.getString(cacheKeyUtil.getOrganizeList()).toString(),
                    OrganizeEntity.class);
        }
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getEnabledMark, 1);

        List<OrganizeEntity> list = this.list(queryWrapper);
        if (list.size() > 0) {
            redisUtil.insert(cacheKeyUtil.getOrganizeList(), JsonUtil.getObjectToString(list), 300);
        }
        return list;
    }

    @Override
    public OrganizeEntity getInfo(String id) {
        return this.getById(id);
    }

    @Override
    public OrganizeEntity getByFullName(String fullName) {
        OrganizeEntity organizeEntity = new OrganizeEntity();
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getFullName, fullName);
        queryWrapper.lambda().select(OrganizeEntity::getId);
        List<OrganizeEntity> list = this.list(queryWrapper);
        if (list.size() > 0) {
            organizeEntity = list.get(0);
        }
        return organizeEntity;
    }

    @Override
    public OrganizeEntity getByFullName(String fullName, String category, String enCode) {
        OrganizeEntity organizeEntity = new OrganizeEntity();
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getFullName, fullName);
        queryWrapper.lambda().eq(OrganizeEntity::getCategory, category);
        queryWrapper.lambda().eq(OrganizeEntity::getEnCode, enCode);
        queryWrapper.lambda().select(OrganizeEntity::getId);
        List<OrganizeEntity> list = this.list(queryWrapper);
        if (list.size() > 0) {
            organizeEntity = list.get(0);
        }
        return organizeEntity;
    }

    @Override
    public boolean isExistByFullName(OrganizeEntity entity, boolean isCheck, boolean isFilter) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getFullName, entity.getFullName());
        if (!isCheck) {
            if (isFilter) {
                queryWrapper.lambda().ne(OrganizeEntity::getId, entity.getId());
            }
            List<OrganizeEntity> entityList = this.list(queryWrapper);
            if (entityList.size() > 0) {
                for (OrganizeEntity organizeEntity : entityList) {
                    if (organizeEntity != null && organizeEntity.getParentId().equals(entity.getParentId())
                            && organizeEntity.getCategory().equals(entity.getCategory())) {
                        return true;
                    }
                }
            }
            return false;
        }
        return this.count(queryWrapper) > 0 ? true : false;
    }

    @Override
    public void getOrganizeIdTree(String organizeId, List<String> organizeParentIdList) {
        OrganizeEntity entity = getInfo(organizeId);
        if (entity != null) {
            organizeParentIdList.add(entity.getId());
            if (StringUtil.isNotEmpty(entity.getParentId())) {
                getOrganizeIdTree(entity.getParentId(), organizeParentIdList);
            }
        }
    }

    @Override
    public void getOrganizeId(String organizeId, List<OrganizeEntity> organizeList) {
        OrganizeEntity entity = getInfo(organizeId);
        if (entity != null) {
            organizeList.add(entity);
            if (StringUtil.isNotEmpty(entity.getParentId())) {
                getOrganizeId(entity.getParentId(), organizeList);
            }
        }
    }

    @Override
    public boolean isExistByEnCode(String enCode, String id) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getEnCode, enCode);
        if (!StringUtil.isEmpty(id)) {
            queryWrapper.lambda().ne(OrganizeEntity::getId, id);
        }
        return this.count(queryWrapper) > 0;
    }

    @Override
    public void create(OrganizeEntity entity) {
        if (StringUtil.isEmpty(entity.getId())) {
            entity.setId(RandomUtil.uuId());
        }

        entity.setCreatorUserId(UserProvider.getUser().getUserId());
        // 拼上当前组织id
        String organizeIdTree = StringUtil.isNotEmpty(entity.getOrganizeIdTree()) ? entity.getOrganizeIdTree() + ","
                : "";
        entity.setOrganizeIdTree(organizeIdTree + entity.getId());
        if (!UserProvider.getUser().getIsAdministrator()) {
            // 当前用户创建的组织要赋予权限
            OrganizeAdministratorEntity organizeAdministratorEntity = new OrganizeAdministratorEntity();
            organizeAdministratorEntity.setUserId(UserProvider.getUser().getUserId());
            organizeAdministratorEntity.setOrganizeId(entity.getId());
            organizeAdministratorEntity.setThisLayerAdd(1);
            organizeAdministratorEntity.setThisLayerEdit(1);
            organizeAdministratorEntity.setThisLayerDelete(1);
            organizeAdministratorEntity.setThisLayerSelect(1);
            organizeAdministratorEntity.setSubLayerAdd(0);
            organizeAdministratorEntity.setSubLayerEdit(0);
            organizeAdministratorEntity.setSubLayerDelete(0);
            organizeAdministratorEntity.setSubLayerSelect(0);
            organizeAdministratorService.create(organizeAdministratorEntity);
        }
        this.save(entity);
        redisUtil.remove(cacheKeyUtil.getOrganizeInfoList());
    }

    @Override
    public boolean update(String id, OrganizeEntity entity) {
        entity.setId(id);
        entity.setLastModifyTime(DateUtil.getNowDate());
        entity.setLastModifyUserId(UserProvider.getUser().getUserId());
        // 拼上当前组织id
        String organizeIdTree = StringUtil.isNotEmpty(entity.getOrganizeIdTree()) ? entity.getOrganizeIdTree() + ","
                : "";
        entity.setOrganizeIdTree(organizeIdTree + entity.getId());
        // 判断父级是否变化
        OrganizeEntity info = getInfo(id);
        boolean updateById = this.updateById(entity);
        if (info != null && !entity.getParentId().equals(info.getParentId())) {
            // 子集和父级都需要修改父级树
            update(entity, info.getCategory());
        }
        redisUtil.remove(cacheKeyUtil.getOrganizeInfoList());
        return updateById;
    }

    @Override
    public void update(OrganizeEntity entity, String category) {
        // 查询子级
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getParentId, entity.getId());
        if (PermissionConst.COMPANY.equals(category)) {
            queryWrapper.lambda().eq(OrganizeEntity::getCategory, PermissionConst.COMPANY);
        } else {
            queryWrapper.lambda().eq(OrganizeEntity::getCategory, PermissionConst.DEPARTMENT);
        }
        List<OrganizeEntity> list = this.list(queryWrapper);
        // 递归修改子组织的父级id字段
        for (OrganizeEntity organizeEntity : list) {
            List<String> list1 = new ArrayList<>();
            getOrganizeIdTree(organizeEntity.getId(), list1);
            // 倒叙排放
            Collections.reverse(list1);
            StringBuilder organizeIdTree = new StringBuilder();
            for (String organizeParentId : list1) {
                organizeIdTree.append("," + organizeParentId);
            }
            String organizeParentIdTree = organizeIdTree.toString();
            if (StringUtil.isNotEmpty(organizeParentIdTree)) {
                organizeParentIdTree = organizeParentIdTree.replaceFirst(",", "");
            }
            organizeEntity.setOrganizeIdTree(organizeParentIdTree);
            this.updateById(organizeEntity);
            redisUtil.remove(cacheKeyUtil.getOrganizeInfoList());
        }
    }

    @Override
    public ActionResult<String> delete(String orgId) {
        String flag = this.allowDelete(orgId);
        if (flag == null) {
            OrganizeEntity organizeEntity = this.getInfo(orgId);
            if (organizeEntity != null) {
                this.removeById(orgId);
                redisUtil.remove(cacheKeyUtil.getOrganizeInfoList());
                ThreadPoolExecutorUtil.getExecutor().execute(() -> {
                    try {
                        // 删除部门后判断是否需要同步到企业微信
                        synThirdQyService.deleteDepartmentSysToQy(false, orgId, "");
                        // 删除部门后判断是否需要同步到钉钉
                        synThirdDingTalkService.deleteDepartmentSysToDing(false, orgId, "");
                    } catch (Exception e) {
                        log.error("删除部门后同步失败到企业微信或钉钉失败，异常：" + e.getMessage());
                    }
                });
                return ActionResult.success(MsgCode.SU003.get());
            }
            return ActionResult.fail(MsgCode.FA003.get());
        } else {
            return ActionResult.fail(MsgCode.PS001.get(flag));
        }
    }

    @Override
    @DSTransactional
    public boolean first(String id) {
        boolean isOk = false;
        // 获取要上移的那条数据的信息
        OrganizeEntity upEntity = this.getById(id);
        Long upSortCode = upEntity.getSortCode() == null ? 0 : upEntity.getSortCode();
        // 查询上几条记录
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .lt(OrganizeEntity::getSortCode, upSortCode)
                .eq(OrganizeEntity::getParentId, upEntity.getParentId())
                .orderByDesc(OrganizeEntity::getSortCode);
        List<OrganizeEntity> downEntity = this.list(queryWrapper);
        if (downEntity.size() > 0) {
            // 交换两条记录的sort值
            Long temp = upEntity.getSortCode();
            upEntity.setSortCode(downEntity.get(0).getSortCode());
            downEntity.get(0).setSortCode(temp);
            this.updateById(downEntity.get(0));
            this.updateById(upEntity);
            isOk = true;
        }
        return isOk;
    }

    @Override
    @DSTransactional
    public boolean next(String id) {
        boolean isOk = false;
        // 获取要下移的那条数据的信息
        OrganizeEntity downEntity = this.getById(id);
        Long upSortCode = downEntity.getSortCode() == null ? 0 : downEntity.getSortCode();
        // 查询下几条记录
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .gt(OrganizeEntity::getSortCode, upSortCode)
                .eq(OrganizeEntity::getParentId, downEntity.getParentId())
                .orderByAsc(OrganizeEntity::getSortCode);
        List<OrganizeEntity> upEntity = this.list(queryWrapper);
        if (upEntity.size() > 0) {
            // 交换两条记录的sort值
            Long temp = downEntity.getSortCode();
            downEntity.setSortCode(upEntity.get(0).getSortCode());
            upEntity.get(0).setSortCode(temp);
            this.updateById(upEntity.get(0));
            this.updateById(downEntity);
            isOk = true;
        }
        return isOk;
    }

    @Override
    public String allowDelete(String orgId) {
        // 组织底下是否有组织
        List<OrganizeEntity> list = getListByParentId(orgId);
        if (Objects.nonNull(list) && list.size() > 0) {
            return MsgCode.PS003.get();
        }
        // 组织底下是否有岗位
        List<PositionEntity> list1 = positionService.getListByOrganizeId(Collections.singletonList(orgId), false);
        if (Objects.nonNull(list1) && list1.size() > 0) {
            return MsgCode.PS004.get();
        }
        // 组织底下是否有用户
        if (userRelationService.existByObj(PermissionConst.ORGANIZE, orgId)) {
            return MsgCode.PS005.get();
        }
        // 组织底下是否有角色
        if (organizeRelationService.existByObjTypeAndOrgId(PermissionConst.ROLE, orgId)) {
            return MsgCode.PS006.get();
        }
        return null;
    }

    @Override
    public List<OrganizeEntity> getOrganizeName(List<String> id) {
        List<OrganizeEntity> list = new ArrayList<>();
        if (id.size() > 0) {
            QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(OrganizeEntity::getId, id);
            queryWrapper.lambda().orderByAsc(OrganizeEntity::getSortCode).orderByDesc(OrganizeEntity::getCreatorTime);
            list = this.list(queryWrapper);
        }
        return list;
    }

    @Override
    public Map<String, OrganizeEntity> getOrganizeName(List<String> id, String keyword, boolean filterEnabledMark,
            String type) {
        Map<String, OrganizeEntity> list = Collections.EMPTY_MAP;
        if (id.size() > 0) {
            QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(OrganizeEntity::getId, id);
            if (StringUtil.isNotEmpty(keyword)) {
                queryWrapper.lambda().and(
                        t -> t.like(OrganizeEntity::getFullName, keyword)
                                .or().like(OrganizeEntity::getEnCode, keyword));
            }
            if (StringUtil.isNotEmpty(type)) {
                queryWrapper.lambda().eq(OrganizeEntity::getCategory, type);
            }
            if (filterEnabledMark) {
                queryWrapper.lambda().eq(OrganizeEntity::getEnabledMark, 1);
            }
            list = getBaseOrgMaps(queryWrapper, ImmutableMap.of(
                    OrganizeEntity::getSortCode, true,
                    OrganizeEntity::getCreatorTime, false), null, false);
            // Map<String, OrganizeEntity> orgList = new LinkedHashMap<>(id.size(), 1);
            // orgMaps.values().forEach(t -> {
            // if (StringUtil.isNotEmpty(t.getOrganizeIdTree())) {
            // String[] split = t.getOrganizeIdTree().split(",");
            // for (String orgId : split) {
            // if (id.contains(orgId) && !orgList.containsKey(orgId)) {
            // OrganizeEntity entity = orgMaps.get(orgId);
            // if(entity == null){
            // entity = getInfo(orgId);
            // }
            // if (entity != null) {
            // orgList.put(orgId, entity);
            // }
            // }
            // }
            // }
            // });
            // list = orgList;
        }
        return list;
    }

    @Override
    public List<OrganizeEntity> getOrganizeNameSort(List<String> id) {
        List<OrganizeEntity> list = new ArrayList<>();
        for (String orgId : id) {
            QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(OrganizeEntity::getId, orgId);
            queryWrapper.lambda().select(OrganizeEntity::getFullName);
            OrganizeEntity entity = this.getOne(queryWrapper);
            if (entity != null) {
                list.add(entity);
            }
        }
        return list;
    }

    @Override
    public List<String> getOrganize(String organizeParentId) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getParentId, organizeParentId);
        queryWrapper.lambda().select(OrganizeEntity::getId);
        List<String> list = this.list(queryWrapper).stream().map(t -> t.getId()).collect(Collectors.toList());
        return list;
    }

    @Override
    public List<String> getOrganizeByOraParentId(String organizeParentId) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getParentId, organizeParentId);
        // queryWrapper.lambda().select(OrganizeEntity::getId);
        List<OrganizeEntity> list = this.list(queryWrapper);
        return list.stream().map(t -> t.getId()).collect(Collectors.toList());
    }

    @Override
    public List<String> getUnderOrganizations(String organizeId, boolean filterEnabledMark) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        if (filterEnabledMark) {
            queryWrapper.lambda().eq(OrganizeEntity::getEnabledMark, 1);
        }
        queryWrapper.lambda().ne(OrganizeEntity::getId, organizeId);
        queryWrapper.lambda().like(OrganizeEntity::getOrganizeIdTree, organizeId);
        queryWrapper.lambda().select(OrganizeEntity::getId);
        return this.list(queryWrapper).stream().map(OrganizeEntity::getId).collect(Collectors.toList());
    }

    @Override
    public List<String> getUnderOrganizationss(String organizeId) {
        List<String> totalIds = this.getUnderOrganizations(organizeId, false);
        if (!UserProvider.getUser().getIsAdministrator()) {
            // 得到有权限的组织
            List<String> collect = organizeAdministratorService.getListByAuthorize().stream().map(OrganizeEntity::getId)
                    .collect(Collectors.toList());
            totalIds = totalIds.stream().filter(t -> collect.contains(t)).collect(Collectors.toList());
        }
        return totalIds;
    }

    @Override
    public List<OrganizeEntity> getListByFullName(String fullName) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getFullName, fullName);
        return this.list(queryWrapper);
    }

    @Override
    public List<OrganizeEntity> getListByParentId(String id) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getParentId, id);
        return this.list(queryWrapper);
    }

    @Override
    public List<OrganizeEntity> getAllOrgByUserId(String userId) {
        List<String> ids = new ArrayList<>();
        userRelationService.getAllOrgRelationByUserId(userId).forEach(r -> {
            ids.add(r.getObjectId());
        });
        return this.listByIds(ids);
    }

    @Override
    public String getFullNameByOrgIdTree(Map<String, String> idNameMaps, String orgIdTree, String regex) {
        if (idNameMaps == null || idNameMaps.isEmpty()) {
            idNameMaps = this.getInfoList();
        }
        String fullName = "";
        if (StringUtil.isNotEmpty(orgIdTree)) {
            String[] split = orgIdTree.split(",");
            StringBuilder orgName = new StringBuilder();
            String tmpName;
            for (String orgId : split) {
                if (StringUtil.isEmpty(orgIdTree)) {
                    continue;
                }
                if ((tmpName = idNameMaps.get(orgId)) != null) {
                    orgName.append(regex).append(tmpName);
                }
            }
            if (orgName.length() > 0) {
                fullName = orgName.toString().replaceFirst(regex, "");
            }
        }
        return fullName;
    }

    @Override
    public String getOrganizeIdTree(OrganizeEntity entity) {
        List<String> list = new ArrayList<>();
        this.getOrganizeIdTree(entity.getParentId(), list);
        // 倒叙排放
        Collections.reverse(list);
        StringBuilder organizeIdTree = new StringBuilder();
        for (String organizeParentId : list) {
            organizeIdTree.append("," + organizeParentId);
        }
        String organizeParentIdTree = organizeIdTree.toString();
        if (StringUtil.isNotEmpty(organizeParentIdTree)) {
            organizeParentIdTree = organizeParentIdTree.replaceFirst(",", "");
        }
        return organizeParentIdTree;
    }

    @Override
    public List<OrganizeEntity> getOrganizeByParentId(String parentId) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getParentId, parentId);
        return this.list(queryWrapper);
    }

    @Override
    public List<OrganizeEntity> getAllChild(String id) {
        QueryWrapper<OrganizeEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(OrganizeEntity::getEnabledMark, 1).like(OrganizeEntity::getOrganizeIdTree, id);
        return this.list(wrapper);
    }

    @Override
    public List<OrganizeEntity> getDepartmentAll(String organizeId) {
        OrganizeEntity organizeCompany = getOrganizeCompany(organizeId);
        if (null == organizeCompany) {
            return new ArrayList<>();
        }
        String id = organizeCompany.getId();
        List<OrganizeEntity> organizeList = new ArrayList<>();
        organizeList.add(organizeCompany);
        List<OrganizeEntity> organizeEntityList = getListByParentId(id).stream()
                .filter(t -> !PermissionConst.COMPANY.equals(t.getCategory())).collect(Collectors.toList());
        for (OrganizeEntity entity : organizeEntityList) {
            QueryWrapper<OrganizeEntity> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(OrganizeEntity::getEnabledMark, 1).like(OrganizeEntity::getOrganizeIdTree,
                    entity.getId());
            organizeList.addAll(this.list(wrapper));
        }
        return organizeList;
    }

    @Override
    public OrganizeEntity getOrganizeCompany(String organizeId) {
        OrganizeEntity entity = getInfo(organizeId);
        return (entity != null && !PermissionConst.COMPANY.equals(entity.getCategory()))
                ? getOrganizeCompany(entity.getParentId())
                : entity;
    }

    @Override
    public void getOrganizeDepartmentAll(String organizeId, List<OrganizeEntity> organizeList) {
        List<OrganizeEntity> organizeEntityList = getListByParentId(organizeId);
        for (OrganizeEntity entity : organizeEntityList) {
            if (!PermissionConst.COMPANY.equals(entity.getCategory())) {
                organizeList.add(entity);
                getOrganizeDepartmentAll(entity.getId(), organizeList);
            }
        }
    }

    @Override
    public List<String> getOrgIdTree(OrganizeEntity entity) {
        List<String> orgIds = new ArrayList<>();
        if (entity != null) {
            String organizeIdTree = entity.getOrganizeIdTree();
            if (StringUtil.isNotEmpty(organizeIdTree)) {
                String[] split = organizeIdTree.split(",");
                for (String orgId : split) {
                    orgIds.add(orgId);
                }
            }
        }
        return orgIds;
    }

    @Override
    public List<String> upWardRecursion(List<String> orgIDs, String orgID) {
        this.getOrgIDs(orgIDs, orgID);
        return orgIDs;
    }

    @Override
    public Map<String, String> getInfoList() {
        if (redisUtil.exists(cacheKeyUtil.getOrganizeInfoList())) {
            return new HashMap<>(redisUtil.getMap(cacheKeyUtil.getOrganizeInfoList()));
        } else {
            Map<String, OrganizeEntity> orgs = getOrgMaps(null, false, null, OrganizeEntity::getFullName);
            Map<String, String> infoMap = new LinkedHashMap<>(orgs.size(), 1);
            orgs.forEach((k, v) -> infoMap.put(k, v.getFullName()));
            redisUtil.insert(cacheKeyUtil.getOrganizeInfoList(), infoMap);
            return infoMap;
        }
    }

    @Override
    public List<OrganizeEntity> getListById(Boolean enable) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        if (enable) {
            queryWrapper.lambda().eq(OrganizeEntity::getEnabledMark, 1);
        }
        return this.list(queryWrapper);
    }

    @Override
    public OrganizeEntity getInfoByParentId(String parentId) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getParentId, parentId);
        return this.getOne(queryWrapper);
    }

    private void getOrgIDs(List<String> orgIDs, String orgID) {
        OrganizeEntity info = this.getInfo(orgID);
        if (info != null) {
            this.getOrgIDs(orgIDs, info.getParentId());
            orgIDs.add(info.getId());
        }
    }

    /**
     * 查询给定的条件是否有默认当前登录者的默认部门值
     *
     * @param organizeConditionModel
     * @return
     */
    @Override
    public String getDefaultCurrentValueDepartmentId(OrganizeConditionModel organizeConditionModel) {
        UserInfo userInfo = UserProvider.getUser();
        int currentFinded = 0;
        if (organizeConditionModel.getDepartIds() != null && !organizeConditionModel.getDepartIds().isEmpty()
                && organizeConditionModel.getDepartIds().contains(userInfo.getOrganizeId())) {
            currentFinded = 1;
        }
        if (currentFinded == 0 && organizeConditionModel.getDepartIds() != null
                && !organizeConditionModel.getDepartIds().isEmpty()) {
            List<String> idList = new ArrayList<>(16);
            // 获取所有组织
            if (organizeConditionModel.getDepartIds().size() > 0) {
                idList.addAll(organizeConditionModel.getDepartIds());
                organizeConditionModel.getDepartIds().forEach(t -> {
                    List<String> underOrganizations = getUnderOrganizations(t, false);
                    if (underOrganizations.size() > 0) {
                        idList.addAll(underOrganizations);
                    }
                });
            }
            Map<String, String> orgIdNameMaps = this.getInfoList();
            List<OrganizeEntity> listAll = getListAll(idList, organizeConditionModel.getKeyword());
            List<OrganizeModel> organizeList = JsonUtil.getJsonToList(listAll, OrganizeModel.class);
            List<String> collect = organizeList.stream().map(SumTree::getParentId).collect(Collectors.toList());
            List<OrganizeModel> noParentId = organizeList.stream()
                    .filter(t -> !collect.contains(t.getId()) && !"-1".equals(t.getParentId()))
                    .collect(Collectors.toList());
            noParentId.forEach(t -> {
                if (StringUtil.isNotEmpty(t.getOrganizeIdTree())) {
                    String[] split = t.getOrganizeIdTree().split(",");
                    List<String> list = Arrays.asList(split);
                    Collections.reverse(list);
                    for (int i = 1; i < list.size(); i++) {
                        String orgId = list.get(i);
                        List<OrganizeModel> collect1 = organizeList.stream().filter(tt -> orgId.equals(tt.getId()))
                                .collect(Collectors.toList());
                        if (collect1.size() > 0) {
                            String[] split1 = StringUtil.isNotEmpty(t.getOrganizeIdTree())
                                    ? t.getOrganizeIdTree().split(orgId)
                                    : new String[0];
                            if (split1.length > 0) {
                                t.setFullName(getFullNameByOrgIdTree(orgIdNameMaps, split1[1], "/"));
                            }
                            t.setParentId(orgId);
                            break;
                        }
                    }
                }
            });

            List<String> orgLIdList = organizeList.stream().map(OrganizeModel::getId).collect(Collectors.toList());
            if (orgLIdList != null && !orgLIdList.isEmpty() && orgLIdList.contains(userInfo.getOrganizeId())) {
                currentFinded = 1;
            }
        }
        return (currentFinded == 1) ? userInfo.getOrganizeId() : "";
    }

    @Override
    public Map<String, Object> getAllOrgsTreeName() {
        Map<String, Object> map = new HashMap<>();
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        List<OrganizeEntity> list = this.list(queryWrapper);
        Map<String, String> collect = list.stream()
                .collect(Collectors.toMap(OrganizeEntity::getId, OrganizeEntity::getFullName));
        for (OrganizeEntity org : list) {
            String organizeIdTree = org.getOrganizeIdTree();
            if (StringUtil.isEmpty(organizeIdTree)) {
                organizeIdTree = org.getId();
            }
            String[] split = organizeIdTree.split(",");
            StringJoiner names = new StringJoiner("/");
            for (String id : split) {
                names.add(collect.get(id));
            }
            map.put(organizeIdTree, names.toString());
        }
        return map;
    }

    @Override
    public Map<String, Object> getAllOrgsTreeName(boolean enabledMark) {
        Map<String, Object> map = new HashMap<>();
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        if (enabledMark) {
            queryWrapper.lambda().eq(OrganizeEntity::getEnabledMark, 1);
        }
        List<OrganizeEntity> list = this.list(queryWrapper);
        Map<String, String> collect = list.stream()
                .collect(Collectors.toMap(OrganizeEntity::getId, OrganizeEntity::getFullName));
        for (OrganizeEntity org : list) {
            String organizeIdTree = org.getOrganizeIdTree();
            if (StringUtil.isEmpty(organizeIdTree)) {
                organizeIdTree = org.getId();
            }
            String[] split = organizeIdTree.split(",");
            StringJoiner names = new StringJoiner("/");
            for (String id : split) {
                names.add(collect.get(id));
            }
            map.put(organizeIdTree, names.toString());
        }
        return map;
    }

    @Override
    public List<OrganizeEntity> getPageList(List<String> orgIds, PaginationOrganize pagination,
            boolean filterEnabledMark) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtil.isNotEmpty(pagination.getKeyword())) {
            queryWrapper.lambda().and(t -> t.like(OrganizeEntity::getFullName, pagination.getKeyword())
                    .or().like(OrganizeEntity::getEnCode, pagination.getKeyword()));
        }
        if (StringUtil.isNotEmpty(pagination.getType())) {
            queryWrapper.lambda().eq(OrganizeEntity::getCategory, pagination.getType());
        }
        if (!orgIds.isEmpty()) {
            queryWrapper.lambda().in(OrganizeEntity::getId, orgIds);
        }
        if (filterEnabledMark) {
            queryWrapper.lambda().eq(OrganizeEntity::getEnabledMark, 1);
        }
        queryWrapper.lambda().orderByAsc(OrganizeEntity::getSortCode);
        Page<OrganizeEntity> page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize());
        IPage<OrganizeEntity> iPage = this.page(page, queryWrapper);
        return pagination.setData(iPage.getRecords(), iPage.getTotal());
    }

    @Override
    public List<Map<String, Object>> getOrgTreeList(String category, String keyword) {
        Map<String, OrganizeEntity> list = Collections.EMPTY_MAP;
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        if (!UserProvider.getUser().getIsAdministrator()) {
            // 通过权限转树
            List<OrganizeAdministratorEntity> listss = organizeAdministratorService
                    .getOrganizeAdministratorEntity(UserProvider.getUser().getUserId());
            Set<String> orgIds = new HashSet<>(16);
            // 判断自己是哪些组织的管理员
            listss.stream().forEach(t -> {
                if (t != null) {
                    if (t.getThisLayerSelect() != null && t.getThisLayerSelect() == 1) {
                        orgIds.add(t.getOrganizeId());
                    }
                    if (t.getSubLayerSelect() != null && t.getSubLayerSelect() == 1) {
                        List<String> underOrganizations = this.getUnderOrganizations(t.getOrganizeId(), true);
                        orgIds.addAll(underOrganizations);
                    }
                }
            });
            List<String> list1 = new ArrayList<>(orgIds);
            if (list1.size() > 0) {
                queryWrapper.lambda().in(OrganizeEntity::getId, list1);
            } else {
                return new ArrayList<>();
            }
        }
        if (StringUtil.isNotEmpty(category)) {
            queryWrapper.lambda().eq(OrganizeEntity::getCategory, category);
        }
        if (StringUtil.isNotEmpty(keyword)) {
            queryWrapper.lambda().and(t -> t.like(OrganizeEntity::getFullName, keyword)
                    .or().like(OrganizeEntity::getEnCode, keyword));
        }
        queryWrapper.lambda().eq(OrganizeEntity::getEnabledMark, 1);
        list = getBaseOrgMaps(queryWrapper, ImmutableMap.of(
                OrganizeEntity::getSortCode, true,
                OrganizeEntity::getCreatorTime, false), null, true);

        List<Map<String, Object>> finalModels = new ArrayList<>();
        // 类型
        Map<String, String> typeMap = new HashMap() {
            {
                put(PermissionConst.COMPANY, "公司");
                put(PermissionConst.DEPARTMENT, "部门");
            }
        };
        // 企业性质
        List<DictionaryDataEntity> enList = dictionaryDataService
                .getByTypeCodeEnable(DictionaryDataEnum.ENTERPRISE_NATURE.getDictionaryTypeId());
        Map<String, String> enMap = enList.stream()
                .collect(Collectors.toMap(DictionaryDataEntity::getId, DictionaryDataEntity::getFullName));
        // 行业类别
        List<DictionaryDataEntity> itList = dictionaryDataService
                .getByTypeCodeEnable(DictionaryDataEnum.INDUSTRY_TYPE.getDictionaryTypeId());
        Map<String, String> itMap = itList.stream()
                .collect(Collectors.toMap(DictionaryDataEntity::getId, DictionaryDataEntity::getFullName));

        List<String> allManagerId = new ArrayList<>();
        Map<String, String> orgMapsModel = this.getInfoList();
        Map<String, OrganizeEntity> finalList = list;
        list.values().forEach(t -> {
            Map<String, Object> obj = JsonUtil.entityToMap(t);
            String propertyJson = t.getPropertyJson();
            if (StringUtil.isNotEmpty(propertyJson)) {
                Map<String, Object> propertyMap = JsonUtil.stringToMap(propertyJson);
                if (ObjectUtil.isNotEmpty(propertyMap)) {
                    if (propertyMap.get("enterpriseNature") != null) {
                        String enterpriseNature = propertyMap.get("enterpriseNature").toString();
                        propertyMap.put("enterpriseNature", enMap.get(enterpriseNature));
                    }
                    if (propertyMap.get("industry") != null) {
                        String enterpriseNature = propertyMap.get("industry").toString();
                        propertyMap.put("industry", itMap.get(enterpriseNature));
                    }
                    obj.putAll(propertyMap);
                }
            }
            String organizeIdTree = t.getOrganizeIdTree();
            if (StringUtil.isNotEmpty(organizeIdTree)) {
                List<String> split = Arrays.asList(t.getOrganizeIdTree().split(","));
                Collections.reverse(split);
                for (String orgId : split) {
                    if (!orgId.equals(t.getId())) {
                        OrganizeEntity organizeEntity = finalList.get(orgId);
                        if (organizeEntity != null) {
                            obj.put("parentId", organizeEntity.getId());
                            break;
                        }
                    }
                }
                String allName = this.getFullNameByOrgIdTree(orgMapsModel, organizeIdTree, "/");
                // 父级名称
                if (allName.contains("/")) {
                    String parentId = allName.substring(0, allName.lastIndexOf("/"));
                    obj.put("parentName", parentId);
                }
            }
            if (StringUtil.isNotEmpty(t.getCategory())) {
                obj.put("category", typeMap.get(t.getCategory()));
            }
            if (StringUtil.isNotEmpty(t.getManagerId())) {
                allManagerId.add(t.getManagerId());
            }
            finalModels.add(obj);
        });
        List<Map<String, Object>> treeObj = PermissionUtil.getTreeObj(finalModels, "parentId", "id");
        List<Map<String, Object>> realList = PermissionUtil.getListFromTree(treeObj);
        Map<String, String> userMap = userService.getUserName(allManagerId, true).stream().collect(HashMap::new,
                (k, v) -> k.put(v.getId(), v.getRealName() + "/" + v.getAccount()), HashMap::putAll);
        // 数据转换
        realList.stream().forEach(t -> {
            if (t.get("managerId") != null) {
                t.put("managerId", userMap.get(t.get("managerId").toString()));
            }
            if (t.get("parentName") != null) {
                t.put("parentId", t.get("parentName"));
            } else {
                t.put("parentId", "");
            }
            if (t.get("foundedTime") != null && StringUtil.isNotEmpty(t.get("foundedTime").toString())) {
                t.put("foundedTime", DateUtil.daFormat(Long.parseLong(t.get("foundedTime").toString())));
            }
        });
        return realList;
    }

    @Override
    public String[] myOrgArray() {
        List<Map<String, Object>> orgTreeList = this.getOrgTreeList(null, null);
        String[] organizeId = orgTreeList.stream().map(t -> {
            if (t.get("parentName") != null) {
                return t.get("parentName") + "/" + t.get("fullName");
            } else {
                return t.get("fullName");
            }
        }).toArray(String[]::new);
        return organizeId;
    }

    @Override
    public String getUserTreeOrgStr(AuthorizeConditionEnum conditionType) {
        String res = "";
        UserInfo userInfo = UserProvider.getUser();
        String orgId = userInfo.getOrganizeId();
        if (StringUtil.isNotEmpty(userInfo.getDepartmentId())) {
            orgId = userInfo.getDepartmentId();
        }
        switch (conditionType) {
            case ORGANIZE:// 当前组织
                List<String> orgIds = new ArrayList<>();
                orgIds.add(orgId);
                List<List<String>> orgAllPathList = getOrgAllPathList(orgIds);
                res = CollectionUtil.isNotEmpty(orgAllPathList) ? JsonUtil.getObjectToString(orgAllPathList.get(0))
                        : "";
                break;
            case ORGANIZEANDUNDER: // 当前组织及子组织
                List<String> underOrganizations = this.getUnderOrganizations(orgId, false);
                underOrganizations.add(orgId);
                res = getOrgAllPath(underOrganizations);
                break;
            case BRANCHMANAGEORG:// 当前分管组织
                List<String> orgManageIds = organizeAdministratorService
                        .getOrganizeUserList(YunzhupaasConst.CURRENT_ORG_SUB);
                res = getOrgAllPath(orgManageIds);
                break;
        }
        return res;
    }

    /**
     * 获取组织全路径
     *
     * @param allIdList 组织id列表。
     * @return
     */
    private String getOrgAllPath(List<String> allIdList) {
        List<List<String>> orgAllPathList = getOrgAllPathList(allIdList);
        return JsonUtil.getObjectToString(orgAllPathList);
    }

    /**
     * 获取组织全路径
     *
     * @param allIdList 组织id列表。
     * @return
     */
    private List<List<String>> getOrgAllPathList(List<String> allIdList) {
        List<List<String>> resOrg = new ArrayList<>();
        for (String itemOrg : allIdList) {
            OrganizeEntity organizeEntity = this.getInfo(itemOrg);
            if (organizeEntity != null) {
                if (StringUtil.isNotEmpty(organizeEntity.getOrganizeIdTree())) {
                    String[] split = organizeEntity.getOrganizeIdTree().split(",");
                    if (split.length > 0) {
                        resOrg.add(Arrays.asList(split));
                    }
                }
            }
        }
        return resOrg;
    }

}
