package com.junmp.jyzb.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.junmp.jyzb.api.bean.dto.OrgDto;
import com.junmp.jyzb.api.bean.query.QueryOrgReq;
import com.junmp.jyzb.api.bean.req.UpdateOrgReq;
import com.junmp.jyzb.api.exception.JYZBAppException;
import com.junmp.jyzb.api.exception.enums.PubOrgExceptionEnum;
import com.junmp.jyzb.entity.PubOrg;
import com.junmp.jyzb.mapper.PubOrgMapper;
import com.junmp.jyzb.service.PubOrgService;
import com.junmp.jyzb.utils.*;
import com.junmp.v2.common.exception.base.ServiceException;
import com.junmp.v2.common.util.BeanPlusUtil;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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


@Service
public class PubOrgServiceImpl extends ServiceImpl<PubOrgMapper, PubOrg>  implements PubOrgService{

    @Resource
    private PubOrgMapper pubOrgMapper;
    @Resource
    private RestHighLevelClient client;
    @Autowired
    private RedisUtils redisUtils;


    //例：传入abc,OrderMQReceiver ==>bc 删掉开头的字符串，不是就不删除
    public static String removePrefix(String name, String deleteName) {
        if (name.startsWith(deleteName)) {
            return name.substring(deleteName.length());
        } else {
            return name;
        }
    }



    @Override
    public List<Long> getLowerOrg(Long orgId) {
        //构建 Redis 缓存�
        String redisKey = "getLowerOrg";

        // �Redis 中获取数�
        List<PubOrg> cachedData = redisUtils.findCachedData(redisKey);
        List<PubOrg> menuList = new ArrayList<>();
        if (cachedData!=null){
            menuList = cachedData;
        }else {
            menuList = pubOrgMapper.selectAllOrg();
            redisUtils.set(redisKey, menuList);
        }

        List<Long> resultList = new ArrayList<>();  // 存储最终的菜单树结果
        Map<Long, List<Long>> childrenMap = new HashMap<>();  // 存储每个菜单项的子菜单映射

        resultList.add(orgId); //将自己加入到返回的List中

        // 构建子菜单映射表
        for (PubOrg menu : menuList) {
            Long org = menu.getOrgId();

            if (!childrenMap.containsKey(menu.getOrgParentId())) {  // 如果父菜单还不存在于映射表中
                childrenMap.put(menu.getOrgParentId(), new ArrayList<>());  // 创建一个新的子菜单列表
            }
            childrenMap.get(menu.getOrgParentId()).add(org);  // 将当前菜单项放入对应的子菜单列表中
        }

//        Long orgInfo = Long.valueOf(orgId);//获取输入的组织机构id信息
        //Long orgInfo = new BigInteger(orgId);  // 获取顶级菜单的标识符

        // 获取顶级菜单
        List<Long> topMenus = childrenMap.get(orgId);

        // 迭代构建菜单树
        if (topMenus != null) {

            for (Long topMenu : topMenus) {
                Stack<Long> stack = new Stack<>();  // 使用栈结构辅助构建菜单树
                stack.push(topMenu);  // 将当前顶级菜单项放入栈中

                while (!stack.isEmpty()) {
                    Long currentMenu = stack.pop(); // 取出队首的当前菜单项
                    //Long currentMenuId = currentMenu;  // 获取当前菜单项的标识符

                    if (childrenMap.containsKey(currentMenu)) {  // 如果当前菜单项有子菜单
                        List<Long> children = childrenMap.get(currentMenu);  // 获取子菜单列表

                        for (int i = children.size() - 1; i >= 0; i--) {
                            stack.push(children.get(i));
                        }
                    }

                    resultList.add(currentMenu);  // 将已经处理完的当前菜单项添加到结果列表中
                }
            }

        }

        return resultList;
    }


    @Override
    public Boolean setOrgParentIds() {
        //清空parent_ids字段
        pubOrgMapper.wipeParentIdsData();
        //更新parent_ids字段
        pubOrgMapper.setOrgParentIds();
        return true;
    }


    @Override
    public List<Map<String, Object>> setShortName(Map<String, Object> orgId) {

        List<PubOrg> menuList = pubOrgMapper.selectAllOrg();
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (PubOrg menu : menuList) {
            if (menu.getOrgParentId().toString().equals((orgId.get("orgId")))) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", menu.getOrgId());
                map.put("parentId", menu.getOrgParentId());
                //去掉前缀
                String name1 = menu.getOrgName(); //name1 ,获得“浙江省公安厅”
                //List<String> name2 = null;
                List<String> name2 = new ArrayList<>();
                //name3为固定字段
                List<String> name3 = new ArrayList<>();
                name3.add("公安局");
                name3.add("公安");
                name3.add("分局");

                if (menu.getOrgName().length()>3 && name2.size() <2 && (menu.getOrgName().charAt(2)=='省' ||menu.getOrgName().charAt(2)=='市')){
                    String nameHistory = menu.getOrgName().substring(0,3); //name2 ,获得“浙江省”
                    name2.add(nameHistory);
                    name2.add(" ");
                    name2.add(" ");

                }

                if (menu.getOrgName().length()>3 && (menu.getOrgName().charAt(2)=='区')){
                    name2.remove(2);
                    String nameHistory = menu.getOrgName().substring(0,3);
                    name2.add(2,nameHistory);
                }

                map.put("orgName", name1);
                List<Map<String, Object>> children = getChildMenus(menu.getOrgId(),menuList,name1,name2,name3);//name为要删掉的前缀
                if (!children.isEmpty()) {
                    map.put("children", children);
                    for (Map<String,Object> msg:children){
                        Long id = (Long) msg.get("id");
                        String orgName = msg.get("orgName").toString();
//                        pubOrgMapper.setMsg(id,orgName);
                    }
                }
                //map.put("children", getChildMenus(menu.getOrgId(),menuList,name1,name2,name3));
                resultList.add(map);


            }
        }

        return resultList;
    }

    private List<Map<String, Object>> getChildMenus(Long parentId, List<PubOrg> menuList,String deleteName1,List<String> deleteName2,List<String> deleteName3) {
        List<Map<String, Object>> childList = new ArrayList<>();
        for (PubOrg menu : menuList) {
            //if (menu.getParentId() != null && menu.getParentId().equals(parentId)) {
            if (menu.getOrgParentId().toString().equals(parentId.toString())) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", menu.getOrgId());
                map.put("parentId", menu.getOrgParentId());
                //去掉前缀
                String name1 = menu.getOrgName();
                List<String> name2 = new ArrayList<>();
                name2 = deleteName2;
                String result = removePrefix(name1, deleteName1);
                //遍历name2删掉前缀
                for (String nameMsg:name2){
                    result = removePrefix(result, nameMsg);
                    for (String name3:deleteName3){
                        result = removePrefix(result, name3);
                    }
                }
                map.put("orgName", result);
                if (result.length()>3 && (result.charAt(2)=='省' ||result.charAt(2)=='市')){
                    name2.remove(1);
                    String nameHistory = result.substring(0,3); //获得“绍兴市”
                    name2.add(1,nameHistory);
                }

                if (result.length()>3 && (result.charAt(2)=='区' ||result.charAt(2)=='县')){
                    name2.remove(2);
                    String nameHistory = result.substring(0,3);
                    name2.add(2,nameHistory);
                }

                List<Map<String, Object>> children = getChildMenus(menu.getOrgId(), menuList,name1,name2,deleteName3);
                if (!children.isEmpty()) {
                    map.put("children", children);
                }
                childList.add(map);
            }
        }
        return childList;
    }

    @Transactional
    public Boolean ChangeState(UpdateOrgReq req)
    {
        List<String> chekResult = CheckOrgList(req.getOrgIdList());
        if (chekResult.size() == 0){
            LambdaQueryWrapper<PubOrg> wp = new LambdaQueryWrapper<>();
            wp.in(ObjectUtil.isNotEmpty(req.getOrgIdList()), PubOrg::getOrgId, req.getOrgIdList());
            List<PubOrg> st = list(wp);
            st.forEach(p->
            {
                p.setDelFlag(req.getDelFlag());

            });
            //将delflag设置为user表中的字段所对应的值
            if (req.getDelFlag()==1){
                req.setDelFlag(1);
            }else {
                req.setDelFlag(2);
            }
            List<Long> collect = st.stream().map(PubOrg::getOrgId).collect(Collectors.toList());
            //将组织机构下的所有账号的状态设置成启用或者禁用
            boolean b=pubOrgMapper.setAllUserState(collect,req.getDelFlag());
           return   this.updateBatchById(st);
        }
        else
        {
            String msg="以下组织机构不存在：" +String.join(",", chekResult);
            throw new JYZBAppException(PubOrgExceptionEnum.ORG_NOT_EXIST, msg);
        }
    }



    public List<String>  CheckOrgList(List<String> req){
        LambdaQueryWrapper<PubOrg> wp = new LambdaQueryWrapper<>();
        wp.in(ObjectUtil.isNotEmpty(req), PubOrg::getOrgId, req);
        List<PubOrg> st = list(wp);

        List<String> nonexistentOrgs = new ArrayList<>();
        for (String pubOrgs : req) {
            boolean found = false;
            for (PubOrg pubOrg : st) {
                if (pubOrg.getOrgId().toString().equals( pubOrgs)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                nonexistentOrgs.add(pubOrgs);
            }
        }

        return nonexistentOrgs;

    }



    public OrgDto getOrgHierarchy(QueryOrgReq req) {

        req.setDelFlag(1);
        LambdaQueryWrapper<PubOrg> wp = this.createWrapper(req);
        List<PubOrg> list = this.list(wp);
        OrgDto orgSet=new OrgDto();
        PubOrg OrgOne= this.getById(req.getOrgId());
        BeanPlusUtil.copyProperties(OrgOne, orgSet);
        List<PubOrg> list2 = list(new LambdaQueryWrapper<PubOrg>().eq(PubOrg::getOrgParentId, orgSet.getOrgId()));
        if (list2.size()==0 || list2.isEmpty()){
            orgSet.setIsLeaf(true);
        }else {
            orgSet.setIsLeaf(false);
        }
        // Convert PubOrg list to OrgDto list
        List<OrgDto> orgs = new ArrayList<>();

        list.forEach(p -> {
            OrgDto org = new OrgDto();
            BeanPlusUtil.copyProperties(p, org);
            org.setIsLeaf(false);
            if (p.getOrgParentId().equals(orgSet.getOrgParentId())){
                List<PubOrg> list1 = list(new LambdaQueryWrapper<PubOrg>().eq(PubOrg::getOrgParentId, p.getOrgId()));
                if (list1.size()==0 || list1.isEmpty()){
                    org.setIsLeaf(true);
                }
            }
            orgs.add(org);
        });
        return  getMaximumParent(orgs,orgSet);
    }


    public OrgDto getMaximumParent(List<OrgDto> orgs, OrgDto org) {
        OrgDto dept = null;
        String parentId = org.getOrgParentId().toString();
        if(parentId.equals("0")||parentId.equals("-1")){
            dept = org;
        }else {
            List<OrgDto> parent = orgs.stream().filter(item -> item.getOrgId().toString().equals( parentId)).collect(Collectors.toList());
            //如果parent为空的话直接抛出异常（传入的组织机构不存在或者已经被删除）
            if (parent.size()==0){
                throw new ServiceException(PubOrgExceptionEnum.PUBORG_NOTEXIST_OR_DEL);
            }
            OrgDto maximumParent = getMaximumParent(orgs, parent.get(0));
            dept = maximumParent;
            parent.get(0).addChild(org);
            List<OrgDto> siblings = orgs.stream()
                    .filter(item -> !item.getOrgId().equals(org.getOrgId()) &&
                            item.getOrgParentId().toString().equals(org.getOrgParentId().toString()))
                    .sorted((o1, o2) -> {
                        String orgCode1 = o1.getOrgCode();
                        String orgCode2 = o2.getOrgCode();

                        // Check if either orgCode contains letters
                        boolean hasLetter1 = orgCode1.matches(".*[a-zA-Z].*");
                        boolean hasLetter2 = orgCode2.matches(".*[a-zA-Z].*");

                        if (hasLetter1 && hasLetter2) {
                            return orgCode1.compareTo(orgCode2); // Alphabetical order
                        } else if (hasLetter1) {
                            return 1; // o2 with letters should come first
                        } else if (hasLetter2) {
                            return -1; // o1 with letters should come first
                        } else {
                            return orgCode1.compareTo(orgCode2); // Numeric order
                        }
                    })
                    .collect(Collectors.toList());
            siblings.forEach(p->
            {
                parent.get(0).addChild(p);
            });

        }
        return dept;
    }












    public List<OrgDto> getLowOrg(QueryOrgReq req){
        if (ObjectUtil.isEmpty(req.getParentId())) {
            req.setParentId(req.getOrgId());
        }
        List<PubOrg> list=pubOrgMapper.getLowOrgs(req);
        List<OrgDto> orgs=new ArrayList<>();
        Comparator<PubOrg> orgComparator = (org1, org2) -> {
            String orgCode1 = org1.getOrgCode();
            String orgCode2 = org2.getOrgCode();

            // 判断是否包含字母
            boolean hasLetter1 = orgCode1.matches(".*[a-zA-Z]+.*");
            boolean hasLetter2 = orgCode2.matches(".*[a-zA-Z]+.*");

            // 如果其中一个包含字母，则将其放到排序的最后
            if (hasLetter1 && !hasLetter2) {
                return 1; // orgCode1包含字母，orgCode2不包含字母，orgCode1排在orgCode2后面
            } else if (!hasLetter1 && hasLetter2) {
                return -1; // orgCode1不包含字母，orgCode2包含字母，orgCode1排在orgCode2前面
            }

            // 如果两个orgCode都不含有字母，则按照每两位进行排序
            String[] orgCodeArray1 = orgCode1.split("(?<=\\G..)");
            String[] orgCodeArray2 = orgCode2.split("(?<=\\G..)");

            // 从最后一组（即最后两位）开始比较数字大小
            int index1 = orgCodeArray1.length - 1;
            int index2 = orgCodeArray2.length - 1;
            while (index1 >= 0 && index2 >= 0) {
                String codeValue1 = orgCodeArray1[index1];
                String codeValue2 = orgCodeArray2[index2];

                // 判断是否可以转换为整数，如果不能，则说明包含字母，直接返回结果
                try {
                    int intValue1 = Integer.parseInt(codeValue1, 10);
                    int intValue2 = Integer.parseInt(codeValue2, 10);
                    int compareResult = Integer.compare(intValue1, intValue2);
                    if (compareResult != 0) {
                        return compareResult;
                    }
                } catch (NumberFormatException e) {
                    // orgCode包含字母，直接返回结果
                    return codeValue1.compareTo(codeValue2);
                }

                index1--;
                index2--;
            }

            // 如果orgCode长度不同，那么较长的orgCode排在后面
            return Integer.compare(orgCodeArray1.length, orgCodeArray2.length);
        };
        Collections.sort(list, orgComparator);

        list.forEach(p->{
            OrgDto org=new OrgDto();
            BeanPlusUtil.copyProperties(p, org);
            // 判断是否有子节点
            boolean hasChildren = hasChildren(req.getDelFlag(),p.getOrgId());
            org.setIsLeaf(!hasChildren);
            orgs.add(org);
        });
        return orgs;
    }
    // 判断是否有子节点的方法
    private boolean hasChildren(Integer Del, Long parentId) {

        LambdaQueryWrapper<PubOrg> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PubOrg::getOrgParentId, parentId);
        wrapper.eq(ObjectUtil.isNotNull(Del),PubOrg::getDelFlag, Del);
        Long count = this.count(wrapper);
        return count > 0;
    }
    public List<OrgDto> getOrgList(QueryOrgReq req) {
        LambdaQueryWrapper<PubOrg> wp= this.createWrapper(req);
        List<PubOrg> list = this.list(wp);
        List<OrgDto> orgs=new ArrayList<>();
        list.forEach(p->{
            OrgDto org=new OrgDto();
            BeanPlusUtil.copyProperties(p, org);
            orgs.add(org);
        });
        return orgs;
    }


    private LambdaQueryWrapper<PubOrg> createWrapper(QueryOrgReq req) {
        LambdaQueryWrapper<PubOrg> wrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isEmpty(req)) {
            return wrapper;
        }
        wrapper.eq(ObjectUtil.isNotEmpty(req.getIsDepartment()), PubOrg::getIsDepartment, req.getIsDepartment());
        //根据业务编码查询
        wrapper.eq(ObjectUtil.isNotEmpty(req.getLevel()), PubOrg::getLevelFlag, req.getLevel());
        wrapper.eq(ObjectUtil.isNotEmpty(req.getDelFlag()), PubOrg::getDelFlag, req.getDelFlag());
        wrapper.eq(ObjectUtil.isNotEmpty(req.getParentId()), PubOrg::getOrgParentId,req.getParentId()  );
        wrapper.eq(ObjectUtil.isNotEmpty(req.getOrgCode()), PubOrg::getOrgCode, req.getOrgCode());
        wrapper.like(ObjectUtil.isNotEmpty(req.getOrgName()), PubOrg::getOrgName, req.getOrgName());
        wrapper.like(ObjectUtil.isNotEmpty(req.getDName()), PubOrg::getDName, req.getDName());

        return wrapper;
    }

    //根据组织机构id查询出组织机构是否存在
    @Override
    public PubOrg PubOrgExist(Long id) {
        PubOrg puborg = getById(id);
        if (ObjectUtil.isEmpty(puborg)) {
            //抛出组织机构不存在异常
            throw new ServiceException(PubOrgExceptionEnum.PUBORG_NOT_EXIST);
        }
        return puborg;
    }

    //根据组织机构Code查询出组织机构是否存在
    @Override
    public PubOrg PubOrgCodeExist(String orgCode) {
        PubOrg puborg = getOne(new LambdaQueryWrapper<PubOrg>().eq(PubOrg::getOrgCode,orgCode));
        if (ObjectUtil.isEmpty(puborg)) {
            //抛出组织机构不存在异常
            throw new ServiceException(PubOrgExceptionEnum.PUBORG_NOT_EXIST);
        }
        return puborg;
    }

    //通过组织机构id获取上一层的组织机构数据
    @Override
    public OrgDto getUpOrgInfo(QueryOrgReq req) {
        Long orgParentId = getById(req.getOrgId()).getOrgParentId();
        PubOrg pubOrg = getById(orgParentId);
        OrgDto orgDto = new OrgDto();
        BeanPlusUtil.copyProperties(pubOrg,orgDto);
        return orgDto;
    }

    //新增组织机构信息
    @Override
    public Long addPubOrg(UpdateOrgReq req) {
        List<PubOrg> list = list(new LambdaQueryWrapper<PubOrg>().eq(PubOrg::getOrgName, req.getOrgName()));
        if (list.size()>0){
            throw new ServiceException(PubOrgExceptionEnum.ORG_IS_EXIST);
        }
        //获取父级的组织机构信息（拿到上级组织机构的orgCode,并且将同级的其他组织机构id的code编码都查询出来）
        List<PubOrg> orgList = list(new LambdaQueryWrapper<PubOrg>()
                .eq(PubOrg::getDelFlag, 1)
                .eq(PubOrg::getOrgParentId, req.getOrgParentId()).or().eq(PubOrg::getOrgId,req.getOrgParentId())
                .orderByAsc(PubOrg::getLevelFlag));
        PubOrg parentOrg = orgList.get(0);

        Set<String> orgCodeList = orgList.stream().map(PubOrg::getOrgCode).collect(Collectors.toSet());
        //生成组织机构编码
        String orgCode = setOrgCodeByParentCode(orgCodeList, parentOrg);

        PubOrg pubOrg = new PubOrg();
        BeanPlusUtil.copyProperties(req,pubOrg);
        pubOrg.setOrgCode(orgCode);
        pubOrg.setDelFlag(1);
        pubOrg.setStatusFlag(0);
        pubOrg.setIsDepartment(0);
        pubOrg.setRemark(req.getOrgName());
        pubOrg.setCreateTime(DateTimeUtil.getCurrentDateTime());
        pubOrg.setIsMap("0");
        pubOrg.setUpdateTime(DateTimeUtil.getCurrentDateTime());
        //是否使用新系统（1是，0 否）
        pubOrg.setIsFlag(req.getFindCode().substring(0,4).equals("3302")?1:0);
        save(pubOrg);
        //添加es
//        pubOrgRepository.save(pubOrg);
        return pubOrg.getOrgId();
    }
    //生成一个新的组织机构编码
    private String setOrgCodeByParentCode(Set<String> orgCodeList,PubOrg parentOrg){
        String orgCode = "";
        Integer levelFlag = parentOrg.getLevelFlag();
        int length = parentOrg.getOrgCode().length();
        String baseSubstring = parentOrg.getOrgCode().substring(0, 2 * levelFlag);

        Random random = new Random();

        do {
            int randomTwoDigitNumber = random.nextInt(90) + 10;
            orgCode = baseSubstring + String.format("%02d", randomTwoDigitNumber);

            // Add zero padding
            int zeroPaddingLength = length - orgCode.length();
            StringBuilder zeroPadding = new StringBuilder();
            for (int i = 0; i < Math.max(0, zeroPaddingLength); i++) {
                zeroPadding.append("0");
            }
            orgCode += zeroPadding;

            // Check if orgCode already exists in orgCodeList
        } while (orgCodeList.contains(orgCode));
        return orgCode;
    }

    //修改组织机构信息
    @Override
    public boolean updatePubOrg(UpdateOrgReq req) {
//        List<PubOrg> list = list(new LambdaQueryWrapper<PubOrg>().eq(PubOrg::getOrgName, req.getOrgName()));
//        if (list.size()>0){
//            throw new ServiceException(PubOrgExceptionEnum.ORG_IS_EXIST);
//        }
        PubOrg pubOrg = new PubOrg();
        BeanPlusUtil.copyProperties(req,pubOrg);
        //添加es
//        pubOrgRepository.save(pubOrg);
        return updateById(pubOrg);
    }

    @Override
    public PubOrg getOneOrgInfo(UpdateOrgReq req) {
        PubOrg pubOrg = new PubOrg();

        if (ObjectUtil.isNotNull(req.getOrgId())){
            pubOrg = PubOrgExist(req.getOrgId());
            int isLastNode=pubOrgMapper.selectLastNode(req.getOrgId());
            pubOrg.setIsLastNode(isLastNode);
        }
        if (ObjectUtil.isNotNull(req.getOrgCode())){
            pubOrg = getOne(new LambdaQueryWrapper<PubOrg>().eq(PubOrg::getOrgCode, req.getOrgCode()));
        }
        return pubOrg;
    }

    @Override
    public Long findCodeToOrgId(PubOrg pubOrg) {
        PubOrg one = getOne(new LambdaQueryWrapper<PubOrg>()
                .isNotNull(PubOrg::getLevelFlag)
                .eq(PubOrg::getFindCode, pubOrg.getFindCode())
                .or()
                .eq(PubOrg::getOrgCode, pubOrg.getFindCode())
                .orderByAsc(PubOrg::getLevelFlag).last("limit 1"));
        return one.getOrgId();
    }

    /**
     * 构建组织机构数
     * @return
     */
    @Override
    public List<OrgDto> getTree(QueryOrgReq req) {
    PubOrg pubOrg = null;
    if (ObjectUtil.isNotNull(req.getOrgId())) {
        pubOrg = PubOrgExist(req.getOrgId());
    }
    List<PubOrg> list = list(new LambdaQueryWrapper<PubOrg>().eq(PubOrg::getDelFlag, 1)
            .and(ObjectUtil.isNotNull(req.getOrgId()), wrapper ->
                    wrapper.eq(PubOrg::getOrgId, req.getOrgId())
                            .or()
                            .like(PubOrg::getOrgParentIds, req.getOrgId())
            ));
    List<OrgDto> beanList = BeanPlusUtil.toBeanList(list, OrgDto.class);
    List<OrgDto> orgTree = buildOrgTree(pubOrg,beanList);
    return orgTree;
    }




    public List<OrgDto> buildOrgTree(PubOrg pubOrg,List<OrgDto> list) {
        if (list == null || list.isEmpty()) {
            return Collections.emptyList();
        }

        // 创建比较器

        Comparator<OrgDto> orgComparator = (org1, org2) -> {
            String orgCode1 = org1.getOrgCode();
            String orgCode2 = org2.getOrgCode();

            // 判断是否包含字母
            boolean hasLetter1 = orgCode1.matches(".*[a-zA-Z]+.*");
            boolean hasLetter2 = orgCode2.matches(".*[a-zA-Z]+.*");

            // 如果其中一个包含字母，则将其放到排序的最后
            if (hasLetter1 && !hasLetter2) {
                return 1; // orgCode1包含字母，orgCode2不包含字母，orgCode1排在orgCode2后面
            } else if (!hasLetter1 && hasLetter2) {
                return -1; // orgCode1不包含字母，orgCode2包含字母，orgCode1排在orgCode2前面
            }

            // 如果两个orgCode都不含有字母，则按照每两位进行排序
            String[] orgCodeArray1 = orgCode1.split("(?<=\\G..)");
            String[] orgCodeArray2 = orgCode2.split("(?<=\\G..)");

            // 从最后一组（即最后两位）开始比较数字大小
            int index1 = orgCodeArray1.length - 1;
            int index2 = orgCodeArray2.length - 1;
            while (index1 >= 0 && index2 >= 0) {
                String codeValue1 = orgCodeArray1[index1];
                String codeValue2 = orgCodeArray2[index2];

                // 判断是否可以转换为整数，如果不能，则说明包含字母，直接返回结果
                try {
                    int intValue1 = Integer.parseInt(codeValue1, 10);
                    int intValue2 = Integer.parseInt(codeValue2, 10);
                    int compareResult = Integer.compare(intValue1, intValue2);
                    if (compareResult != 0) {
                        return compareResult;
                    }
                } catch (NumberFormatException e) {
                    // orgCode包含字母，直接返回结果
                    return codeValue1.compareTo(codeValue2);
                }

                index1--;
                index2--;
            }

            // 如果orgCode长度不同，那么较长的orgCode排在后面
            return Integer.compare(orgCodeArray1.length, orgCodeArray2.length);
        };

        // 按parentId分组
        Map<Long, List<OrgDto>> parentIdToChildren = list.stream()
                .collect(Collectors.groupingBy(com.junmp.jyzb.api.bean.dto.OrgDto::getOrgParentId));

        // 对每个父节点下的子节点排序
        parentIdToChildren.forEach((parentId, children) ->
                children.sort(orgComparator));

        // 找出根节点(假设orgParentId为0的是根节点)
        List<OrgDto> roots=new ArrayList<>();
        if (pubOrg != null){

            roots = parentIdToChildren.getOrDefault(pubOrg.getOrgParentId(), new ArrayList<>());
        }else {

            roots = parentIdToChildren.getOrDefault(-1L, new ArrayList<>());
        }
        roots.sort(orgComparator);

        // 构建树
        for (OrgDto root : roots) {
            buildTree(root, parentIdToChildren);
        }

        return roots;
    }


    private void buildTree(OrgDto parent, Map<Long, List<OrgDto>> parentIdToChildren) {
        List<OrgDto> children = parentIdToChildren.get(parent.getOrgId());
        if (children != null) {
            for (OrgDto child : children) {
                parent.addChild(child);
                buildTree(child, parentIdToChildren);
            }
        }
    }
//    public List<OrgDto> getTree(QueryOrgReq req) {
//        PubOrg pubOrg = null;
//        if (ObjectUtil.isNotNull(req.getOrgId())) {
//            pubOrg = PubOrgExist(req.getOrgId());
//        }
//        List<PubOrg> list = list(new LambdaQueryWrapper<PubOrg>().eq(PubOrg::getDelFlag, 1));
//        List<OrgDto> beanList = BeanPlusUtil.toBeanList(list, OrgDto.class);
//        List<OrgDto> orgTree = buildOrgTree(pubOrg, beanList);
//        return orgTree;
//    }
//
//    public List<OrgDto> buildOrgTree(PubOrg pubOrg, List<OrgDto> list) {
//        if (list == null || list.isEmpty()) {
//            return Collections.emptyList();
//        }
//
//        // 创建比较器
//        Comparator<OrgDto> comparator = Comparator
//                .comparing(com.junmp.jyzb.api.bean.dto.OrgDto::getLevelFlag)
//                .thenComparing(com.junmp.jyzb.api.bean.dto.OrgDto::getOrgCode);
//
//        // 按parentId分组，处理null情况
//        Map<Long, List<OrgDto>> parentIdToChildren = list.stream()
//                .collect(Collectors.groupingBy(
//                        dto -> dto.getOrgParentId() != null ? dto.getOrgParentId() : -1L
//                ));
//
//        // 对每个父节点下的子节点排序
//        parentIdToChildren.forEach((parentId, children) ->
//                children.sort(comparator));
//
//        // 找出根节点
//        List<OrgDto> roots = new ArrayList<>();
//        if (pubOrg == null) {
//            // 获取所有根节点(parentId为null或0)
//            roots = list.stream()
//                    .filter(dto -> dto.getOrgParentId() ==-1L)
//                    .sorted(comparator)
//                    .collect(Collectors.toList());
//        } else {
//            // 以pubOrg的ID为根开始构建树
//            Long rootId = pubOrg.getOrgId();
//            List<OrgDto> rootNodes = list.stream()
//                    .filter(dto -> rootId.equals(dto.getOrgId()))
//                    .collect(Collectors.toList());
//            roots.addAll(rootNodes);
//        }
//
//        // 构建树
//        for (OrgDto root : roots) {
//            buildTree(root, parentIdToChildren);
//        }
//
//        return roots;
//    }
//
//    private void buildTree(OrgDto parent, Map<Long, List<OrgDto>> parentIdToChildren) {
//        if (parent == null) return;
//
//        Long parentId = parent.getOrgId();
//        if (parentId == null) return;
//
//        List<OrgDto> children = parentIdToChildren.get(parentId);
//        if (children != null) {
//            for (OrgDto child : children) {
//                if (child != null) {
//                    parent.addChild(child);
//                    buildTree(child, parentIdToChildren);
//                }
//            }
//        }
//    }
}










