package com.junmp.jyzb.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.junmp.jyzb.Repository.PubOrgRepository;
import com.junmp.jyzb.api.bean.dto.*;
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.OrgExceptionEnum;
import com.junmp.jyzb.api.exception.enums.PubOrgExceptionEnum;
import com.junmp.jyzb.entity.EquipmentType;
import com.junmp.jyzb.entity.PubOrg;
import com.junmp.jyzb.utils.*;
import com.junmp.v2.auth.api.context.LoginContext;
import com.junmp.v2.common.exception.base.ServiceException;
import com.junmp.v2.common.util.BeanPlusUtil;
import com.junmp.v2.sys.user.entity.SysUser;
import com.junmp.v2.sys.user.service.SysUserService;
import org.elasticsearch.action.search.ClearScrollRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchScrollRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.junmp.jyzb.mapper.PubOrgMapper;
import com.junmp.jyzb.service.PubOrgService;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


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

    @Resource
    private PubOrgMapper pubOrgMapper;
    @Resource
    private RestHighLevelClient client;
    @Resource
    private SysUserService sysUserService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private PubOrgRepository pubOrgRepository;

    private List<OrgDto> OrgDto;
    private ArrayList<String> ids;

    //例：传入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 ResponseResult setOrgParentIds() {
        //清空parent_ids字段
        pubOrgMapper.wipeParentIdsData();
        //更新parent_ids字段
        pubOrgMapper.setOrgParentIds();
        return new ResponseResult(HttpStatus.SUCCESS, ReturnMsg.PASS);
    }

    @Override
    public Object AddToEs() {
        List<PubOrg> listOrg=  this.list();
        return pubOrgRepository.saveAll(listOrg);
    }

    @Override
    public ResponseResult 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 new ResponseResult(HttpStatus.SUCCESS,"操作成功",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(OrgExceptionEnum.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);
    }

    /**
     * 搜索条件
     * @return
     * @throws IOException
     */
    public List<PubOrg> searchAll() throws IOException {
        SearchRequest request = new SearchRequest("org_pinyin");
        SearchSourceBuilder builder = new SearchSourceBuilder();

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
                .must(QueryBuilders.matchAllQuery())  // 匹配所有文档
                .filter(QueryBuilders.termQuery("delFlag", 1));  // 过滤 delFlag 为 1 的文档
        builder.query(boolQueryBuilder);
        builder.size(5000);  // 设置每页大小

        request.source(builder);
        request.scroll(TimeValue.timeValueMinutes(1L));  // 设置滚动时间

        SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);

        List<PubOrg> pubOrgList = new ArrayList<>();
        while (true) {
            for (SearchHit documentFields : searchResponse.getHits().getHits()) {
                Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
                PubOrg pubOrg = this.fromMap(sourceAsMap);
                pubOrgList.add(pubOrg);
            }

            SearchScrollRequest scrollRequest = new SearchScrollRequest(searchResponse.getScrollId());
            scrollRequest.scroll(TimeValue.timeValueMinutes(1L));
            searchResponse = client.scroll(scrollRequest, RequestOptions.DEFAULT);

            if (searchResponse.getHits().getHits().length == 0) {
                break;  // 所有结果已经检索完成
            }
        }

        // 清除滚动上下文
        ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
        clearScrollRequest.addScrollId(searchResponse.getScrollId());
        client.clearScroll(clearScrollRequest, RequestOptions.DEFAULT);

        return pubOrgList;
    }
    /**
     * 搜索条件
     * @param pageNum
     * @param pageSize
     * @param keyword
     * @return
     * @throws IOException
     */
    public List<PubOrg> searchOrg(Integer pageNum, Integer pageSize, String keyword, String currentOrg) throws IOException {
        if (pageNum < 0) pageNum = 0;

        SearchRequest request = new SearchRequest("org_pinyin");
        SearchSourceBuilder builder = new SearchSourceBuilder();

        builder.from(pageNum);
        builder.size(pageSize);

        // 添加 MatchQueryBuilder 作为 must 条件
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("dName", keyword).operator(Operator.AND);

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(matchQueryBuilder);

        // 添加过滤条件，只获取 delFlag 为 1 的数据
        boolQueryBuilder.filter(QueryBuilders.termQuery("delFlag", 1));

        // 添加过滤条件，orgParentIds 包含当前字段，或者 orgId 等于当前字段
        BoolQueryBuilder orgFilter = QueryBuilders.boolQuery();
        if (StringUtils.isNotBlank(currentOrg) )
        {
        orgFilter.should(QueryBuilders.wildcardQuery("orgParentIds", "*" + currentOrg + "*"));
        orgFilter.should(QueryBuilders.termQuery("orgId", currentOrg.toString()));
        }
        boolQueryBuilder.filter(orgFilter);

        builder.query(boolQueryBuilder);
        builder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        request.source(builder);
        SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);

        List<PubOrg> pubOrgList = new ArrayList<>();
        for (SearchHit documentFields : searchResponse.getHits().getHits()) {
            Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
            PubOrg pubOrg = this.fromMap(sourceAsMap);

            // 添加到结果列表
            pubOrgList.add(pubOrg);
        }

        return pubOrgList;
    }


    /**
     * 搜索条件
     * @param pageNum
     * @param pageSize
     * @return
     * @throws IOException
     */
    public List<PubOrg> searchAll(Integer pageNum, Integer pageSize ) throws IOException {

        if (pageNum < 0) pageNum = 0;

        SearchRequest request = new SearchRequest("org_pinyin");
        SearchSourceBuilder builder = new SearchSourceBuilder();

        builder.from(pageNum);
        builder.size(pageSize);

        // 添加过滤条件，只获取 delFlag 为 1 的数据
        builder.postFilter(QueryBuilders.termQuery("delFlag", 1));
        builder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        request.source(builder);
        SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);

        List<PubOrg> pubOrgList = new ArrayList<>();
        for (SearchHit documentFields : searchResponse.getHits().getHits()) {
            Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
            PubOrg pubOrg = this.fromMap(sourceAsMap);

            // 添加到结果列表
            pubOrgList.add(pubOrg);
        }

        return pubOrgList;
    }

    public List<OrgDto> buildTree(List<PubOrg> searchResults, List<PubOrg> allOrgs) {
        Map<Long, OrgDto> orgDtoMap = new HashMap<>();

        // 将所有组织机构转换为OrgDto并放入map中，同时计算子节点数量
        for (PubOrg org : allOrgs) {
            OrgDto orgDto = new OrgDto();
            // 这里根据你的实际字段进行映射
            orgDto.setOrgId(org.getOrgId());
            orgDto.setOrgName(org.getOrgName());
            orgDto.setOrgCode(org.getOrgCode());
            orgDto.setIsDepartment(org.getIsDepartment());
            orgDto.setOrgParentId(org.getOrgParentId());
            orgDto.setAreaName(org.getAreaName());
            orgDto.setLevelFlag(String.valueOf(org.getLevelFlag()));
            orgDto.setStatusFlag(org.getStatusFlag());
            orgDto.setDName(org.getDName());
            orgDto.setOrgParentIds(org.getOrgParentIds());

            // 计算子节点数量
            int childCount = 0;
            for (PubOrg childOrg : allOrgs) {
                if (childOrg.getOrgParentId().equals(org.getOrgId())) {
                    childCount++;
                }
            }
            orgDto.setChildCount(childCount);
            if (childCount<=0)
            {
                orgDto.setIsLeaf(true);
            }
            else
            {
                orgDto.setIsLeaf(false);
            }
            // 将OrgDto放入map中，以orgId为键
            orgDtoMap.put(org.getOrgId(), orgDto);
        }

        List<OrgDto> tree = new ArrayList<>();

        // 遍历所有搜索到的组织机构数据，构建树
        for (PubOrg searchResult : searchResults) {
            OrgDto orgDto = orgDtoMap.get(searchResult.getOrgId());

            // 如果找到对应的OrgDto
            if (orgDto != null && !tree.contains(orgDto)) {
                // 从当前节点开始，依次向上查找上级节点，直到最顶层
                Long parentId = orgDto.getOrgParentId();

                // 将当前节点及其相关节点加入树中
                while (parentId != null) {
                    OrgDto parentDto = orgDtoMap.get(parentId);

                    if (parentDto != null) {
                        // 将当前节点添加到上级节点的children中，确保不重复添加
                        if (!parentDto.getChildren().contains(orgDto)) {
                            parentDto.getChildren().add(orgDto);
                        }

                        // 如果上级节点是最顶层，将上级节点添加到树中，确保不重复添加
                        if (parentDto.getOrgParentId() == -1 && !tree.contains(parentDto)) {
                            tree.add(parentDto);
                        }

                        // 将上级节点设为当前节点，继续向上查找
                        orgDto = parentDto;
                        parentId = parentDto.getOrgParentId();
                    } else {
                        parentId = null; // 上级节点不存在，跳出循环
                    }
                }
            }
        }

        return tree;
    }






    // 从 Map 中构建 PubOrg 对象的方法
    public static PubOrg fromMap(Map<String, Object> map) {
        PubOrg pubOrg = new PubOrg();
        BeanPlusUtil.copyProperties(map, pubOrg);
//        pubOrg.setOrgName((String) map.get("orgName"));
        // 可以设置其他字段...
        return pubOrg;
    }
    ///通过ES获取数据
    @Override
    public ESOrgDto getOrgTreeByEs(QueryOrgReq req) throws IOException {


        // 先进行搜索，获取前20条数据
        List<PubOrg> searchResults = searchOrg(0, 20, req.getOrgName(), req.getCurrentOrg());
        req.setDelFlag(1);
        // 获取所有组织机构数据
        List<PubOrg> orgsAll=searchAll(0, 3000);
        List<OrgDto> treeResult= buildTree(searchResults,orgsAll);
        ESOrgDto resultDto =new ESOrgDto();
        resultDto.setOrgDto(treeResult);
        SetIds(treeResult);
        resultDto.setIds(ids);
        return resultDto;
    }

    public void SetIds(List<OrgDto> treeResult) {
        ids = new ArrayList<>();
        if (treeResult != null) {
            for (OrgDto orgDto : treeResult) {
                setIdsRecursive(orgDto);
            }
        }
    }

    private void setIdsRecursive(OrgDto orgDto) {
        if (orgDto != null) {
            // 添加当前节点的 id
            ids.add(String.valueOf(orgDto.getOrgId()));

            // 递归处理子节点
            if (orgDto.getChildren() != null) {
                for (OrgDto child : orgDto.getChildren()) {
                    setIdsRecursive(child);
                }
            }
        }
    }

    private OrgDto convertToDto(PubOrg org, List<PubOrg> allOrgs) {
        OrgDto orgDto = new OrgDto();
        // 这里根据你的实际字段进行映射
        orgDto.setOrgId(org.getOrgId());
        orgDto.setOrgName(org.getOrgName());
        orgDto.setOrgCode(org.getOrgCode());
        orgDto.setIsDepartment(org.getIsDepartment());
        orgDto.setOrgParentId(org.getOrgParentId());
        orgDto.setAreaName(org.getAreaName());
        orgDto.setLevelFlag(String.valueOf(org.getLevelFlag()));
        orgDto.setStatusFlag(org.getStatusFlag());
        orgDto.setOrgParentId(org.getOrgParentId());
        orgDto.setDName(org.getDName());

        // 其他字段的映射...

        // 查找当前节点的子节点
        List<PubOrg> children = allOrgs.stream()
                .filter(childOrg -> org.getOrgId().equals(childOrg.getOrgParentId()))
                .collect(Collectors.toList());

        // 如果子节点不为空，递归调用 convertToDto 处理子节点
        if (!children.isEmpty()) {
            List<OrgDto> childrenDto = new ArrayList<>();
            for (PubOrg child : children) {
                childrenDto.add(convertToDto(child, allOrgs));
            }
            orgDto.setChildren(childrenDto);
        }

        return orgDto;
    }



    public OrgDto getMaximumParent(List<OrgDto> orgs, OrgDto org) {
        OrgDto dept = null;
        String parentId = org.getOrgParentId().toString();
        if(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());
        }

        LambdaQueryWrapper<PubOrg> wp= this.createWrapper(req);
        List<PubOrg> list = this.list(wp);

        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;
    }

    //通过组织机构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);
        }
        PubOrg pubOrg = new PubOrg();
        BeanPlusUtil.copyProperties(req,pubOrg);
        pubOrg.setDelFlag(1);
        pubOrg.setStatusFlag(0);
        pubOrg.setIsDepartment(0);
        pubOrg.setRemark(req.getOrgName());
        pubOrg.setCreateTime(DateTimeUtil.getCurrentDateTime());
        pubOrg.setIsMap("0");
        save(pubOrg);
        //添加es
        pubOrgRepository.save(pubOrg);
        return pubOrg.getOrgId();
    }

    //修改组织机构信息
    @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());
        }
        if (ObjectUtil.isNotNull(req.getOrgCode())){
            pubOrg = getOne(new LambdaQueryWrapper<PubOrg>().eq(PubOrg::getOrgCode, req.getOrgCode()));
        }
        return pubOrg;
    }


}










