/**
 * Copyright &copy; 2021-2026 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.sys.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.SecurityUtils;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.common.constant.CommonConstants;
import com.jeeplus.common.constant.enums.OfficeTypeEnum;
import com.jeeplus.core.service.TreeService;
import com.jeeplus.sys.domain.Office;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.mapper.OfficeMapper;
import com.jeeplus.sys.service.dto.OfficeDTO;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.service.mapstruct.OfficeWrapper;
import com.jeeplus.sys.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 机构Service
 *
 * @author jeeplus
 * @version 2021-05-16
 */
@Service
@Transactional
public class OfficeService extends TreeService <OfficeMapper, Office> {

    @Autowired
    private OfficeMapper officeMapper;

    @Autowired
    private OfficeWrapper officeWrapper;

    @Autowired
    private UserService userService;

    /**
     * 获取二级节点数据信息
     * @return
     */
    public List<OfficeDTO> getSecondLevelData(){
        return officeMapper.getSecondLevelData();
    }

    /**
     * 获取列表
     *
     * @return
     */
    public List <OfficeDTO> findList(String tenantId, String parentId) {
        QueryWrapper queryWrapper = new QueryWrapper ( );
        //根据当前人的所属部门去查相关数据
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        queryWrapper.like ( StringUtils.isNotBlank ( parentId ), "a.parent_ids", "," + parentId + "," );

        queryWrapper.eq ( "a.del_flag", 0 );
        if(!"10000".equals(userDTO.getTenantDTO().getId()) && !"10002".equals(userDTO.getTenantDTO().getId())){
            queryWrapper.eq ( StringUtils.isNotBlank ( userDTO.getTenantDTO().getId() ), "a.tenant_id", userDTO.getTenantDTO().getId() );
        }
        /*if (StringUtils.isNotBlank(userDTO.getCompanyDTO().getName())){
            if (userDTO.getCompanyDTO().getName().contains("评估")) {
                queryWrapper.like ( "a.name", "%评估%" );
            }else if (userDTO.getCompanyDTO().getName().contains("会计")){
                //获取兴光会计师事务所的子集id
                List<String> ids = baseMapper.getIds(userDTO.getCompanyDTO().getId());
                ids.add(userDTO.getCompanyDTO().getId());
                queryWrapper.in ( "a.id", ids );
            }
        }*/

        queryWrapper.orderByAsc ( "a.sort" );
        return baseMapper.findList ( queryWrapper );
    }

    /**
     * 获取列表
     *
     * @return
     */
    public List <OfficeDTO> findList2(String tenantId, String parentId) {
        QueryWrapper queryWrapper = new QueryWrapper ( );
        // 查询岗位用户信息
        List<String> offId = userService.findOffId();
        queryWrapper.like ( StringUtils.isNotBlank ( parentId ), "a.parent_ids", "," + parentId + "," );
        queryWrapper.eq ( StringUtils.isNotBlank ( tenantId ), "a.tenant_id", tenantId );
        queryWrapper.eq ( "a.del_flag", 0 );
        queryWrapper.in ( "a.id", offId );
        queryWrapper.orderByAsc ( "a.sort" );
        return baseMapper.findList ( queryWrapper );
    }

    /**
     * 根据签字注师2获取列表
     *
     * @return
     */
    public List <OfficeDTO> findAccessList(String tenantId, String parentId) {
        QueryWrapper queryWrapper = new QueryWrapper ( );
        //查询签字注师2岗位用户信息
        List<String> offId = userService.findOffId();
        queryWrapper.like ( StringUtils.isNotBlank ( parentId ), "a.parent_ids", "," + parentId + "," );
        queryWrapper.eq ( StringUtils.isNotBlank ( tenantId ), "a.tenant_id", tenantId );
        queryWrapper.eq ( "a.del_flag", 0 );
        queryWrapper.in ( "a.id", offId );
        queryWrapper.orderByAsc ( "a.sort" );
        return baseMapper.findAccessList ( queryWrapper );
    }

    /**
     * 用户信息获取列表
     *
     * @return
     */
    public List <OfficeDTO> findListByUser(String tenantId, String parentId) {
        // 查询出拥有证书的用户信息所属的部门id
        List<String> ids = userService.hasUser();


        QueryWrapper queryWrapper = new QueryWrapper ( );
        queryWrapper.like ( StringUtils.isNotBlank ( parentId ), "a.parent_ids", "," + parentId + "," );
        queryWrapper.eq ( StringUtils.isNotBlank ( tenantId ), "a.tenant_id", tenantId );
        queryWrapper.eq ( "a.del_flag", 0 );
        queryWrapper.orderByAsc ( "a.sort" );
        queryWrapper.in ( "a.id", ids );
        return baseMapper.findAccessList ( queryWrapper );
    }

    public List <OfficeDTO> getAccessRootTree(List<OfficeDTO> list, String extId, String type, String showAll, String showMyOffice) {
        List<OfficeDTO> offices = Lists.newArrayList ();
        // 获取到所有parent_id为‘0’的部门数据
        List<Office> children = officeMapper.getAccessChildren(OfficeDTO.getRootId());
//        List<Office> children = super.getChildren(new Office(OfficeDTO.getRootId()));
        List<OfficeDTO> rootTrees = OfficeWrapper.INSTANCE.toDTO (children);
        for (OfficeDTO root : rootTrees) {
            if (this.isUseAble ( extId, type,root, showAll )){
                // 不是被排除节点的子节点
                List<OfficeDTO> officeList = formatListToTree (root, list, extId, type, showAll);
                offices.addAll (officeList);
            }
        }
        if (StringUtils.isNotBlank(showMyOffice)) {
            OfficeDTO officeDTO = UserUtils.getCurrentUserDTO().getOfficeDTO();
            // 排除管理员
            if (!UserUtils.getCurrentUserDTO().isAdmin()){
                if (org.apache.commons.lang.StringUtils.isNotBlank(officeDTO.getParentIds())) {
                    String[] split = officeDTO.getParentIds().split(",");
                    if (split.length > 2) {
                        Office office = officeMapper.selectById(split[2]);
                        if ("0".equals(office.getIsPublic())) {
                            // isPublic为“0”，当前用户的公司为私有，查询的部门包含自己所属公司全部部门和其他的公有部门
                            if(null != officeDTO && org.apache.commons.lang.StringUtils.isNotBlank(officeDTO.getParentIds())){
                                offices = this.getCompanyFromTree(offices);
                            }
                        }
                    } else {
                        if ("0".equals(officeDTO.getIsPublic())) {
                            // isPublic为“0”，当前用户的公司为私有，查询的部门包含自己所属公司全部部门和其他的公有部门
                            if(null != officeDTO && org.apache.commons.lang.StringUtils.isNotBlank(officeDTO.getParentIds())){
                                offices = this.getCompanyFromTree(offices);
                            }
                        }
                    }
                }
            }
        }
        return offices;
    }

    public List <OfficeDTO> getFinanceRootTree(List<OfficeDTO> list, String extId, String type, String showAll, String showMyOffice) {
        List<OfficeDTO> offices = Lists.newArrayList ();
        // 获取到所有parent_id为‘0’的部门数据
        List<Office> children = officeMapper.getFinanceChildren(OfficeDTO.getRootId());
//        List<Office> children = super.getChildren(new Office(OfficeDTO.getRootId()));
        List<OfficeDTO> rootTrees = OfficeWrapper.INSTANCE.toDTO (children);
        for (OfficeDTO root : rootTrees) {
            if (this.isUseAble ( extId, type,root, showAll )){
                // 不是被排除节点的子节点
                List<OfficeDTO> officeList = formatListToTree (root, list, extId, type, showAll);
                offices.addAll (officeList);
            }
        }
        if (StringUtils.isNotBlank(showMyOffice)) {
            OfficeDTO officeDTO = UserUtils.getCurrentUserDTO().getOfficeDTO();
            // 排除管理员
            if (!UserUtils.getCurrentUserDTO().isAdmin()){
                if (org.apache.commons.lang.StringUtils.isNotBlank(officeDTO.getParentIds())) {
                    String[] split = officeDTO.getParentIds().split(",");
                    if (split.length > 2) {
                        Office office = officeMapper.selectById(split[2]);
                        if ("0".equals(office.getIsPublic())) {
                            // isPublic为“0”，当前用户的公司为私有，查询的部门包含自己所属公司全部部门和其他的公有部门
                            if(null != officeDTO && org.apache.commons.lang.StringUtils.isNotBlank(officeDTO.getParentIds())){
                                offices = this.getCompanyFromTree(offices);
                            }
                        }
                    } else {
                        if ("0".equals(officeDTO.getIsPublic())) {
                            // isPublic为“0”，当前用户的公司为私有，查询的部门包含自己所属公司全部部门和其他的公有部门
                            if(null != officeDTO && org.apache.commons.lang.StringUtils.isNotBlank(officeDTO.getParentIds())){
                                offices = this.getCompanyFromTree(offices);
                            }
                        }
                    }
                }
            }
        }
        return offices;
    }

    /**
     * 获取嘉溢数据
     * @param list
     * @param extId
     * @param type
     * @param showAll
     * @param showMyOffice
     * @return
     */
    public List <OfficeDTO> getJyRootTree(List<OfficeDTO> list, String extId, String type, String showAll, String showMyOffice) {
        List<OfficeDTO> offices = Lists.newArrayList ();
        // 获取到所有parent_id为‘0’的部门数据
        List<Office> children = officeMapper.getJyChildren(OfficeDTO.getRootId());
//        List<Office> children = super.getChildren(new Office(OfficeDTO.getRootId()));
        List<OfficeDTO> rootTrees = OfficeWrapper.INSTANCE.toDTO (children);
        for (OfficeDTO root : rootTrees) {
            if (this.isUseAble ( extId, type,root, showAll )){
                // 不是被排除节点的子节点
                List<OfficeDTO> officeList = formatListToTree (root, list, extId, type, showAll);
                offices.addAll (officeList);
            }
        }
        if (StringUtils.isNotBlank(showMyOffice)) {
            OfficeDTO officeDTO = UserUtils.getCurrentUserDTO().getOfficeDTO();
            // 排除管理员
            if (!UserUtils.getCurrentUserDTO().isAdmin()){
                if (org.apache.commons.lang.StringUtils.isNotBlank(officeDTO.getParentIds())) {
                    String[] split = officeDTO.getParentIds().split(",");
                    if (split.length > 2) {
                        Office office = officeMapper.selectById(split[2]);
                        if ("0".equals(office.getIsPublic())) {
                            // isPublic为“0”，当前用户的公司为私有，查询的部门包含自己所属公司全部部门和其他的公有部门
                            if(null != officeDTO && org.apache.commons.lang.StringUtils.isNotBlank(officeDTO.getParentIds())){
                                offices = this.getCompanyFromTree(offices);
                            }
                        }
                    } else {
                        if ("0".equals(officeDTO.getIsPublic())) {
                            // isPublic为“0”，当前用户的公司为私有，查询的部门包含自己所属公司全部部门和其他的公有部门
                            if(null != officeDTO && org.apache.commons.lang.StringUtils.isNotBlank(officeDTO.getParentIds())){
                                offices = this.getCompanyFromTree(offices);
                            }
                        }
                    }
                }
            }
        }
        return offices;
    }



    public List <OfficeDTO> getRootTree(List<OfficeDTO> list, String extId, String type, String showAll, String showMyOffice) {
        List<OfficeDTO> offices = Lists.newArrayList ();
        // 获取到所有parent_id为‘0’的部门数据
        //获取当前登录人所属的部门
        List<Office> children = new ArrayList<>();
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        if (!SecurityUtils.getCurrentUserDTO ( ).isAdmin ( )){
            if (userDTO.getCompanyDTO().getName().contains("评估")||userDTO.getCompanyDTO().getName().contains("会计")){
                children = officeMapper.getChildren(OfficeDTO.getRootId(),userDTO.getCompanyDTO().getId());
            } else {
                children = officeMapper.getChildren(OfficeDTO.getRootId(),"");
            }

        } else {
            children = officeMapper.getChildren(OfficeDTO.getRootId(),"");
        }
//        List<Office> children = super.getChildren(new Office(OfficeDTO.getRootId()));
        List<OfficeDTO> rootTrees = OfficeWrapper.INSTANCE.toDTO (children);
        for (OfficeDTO root : rootTrees) {
            if (this.isUseAble ( extId, type,root, showAll )){
                // 不是被排除节点的子节点
                List<OfficeDTO> officeList = formatListToTree (root, list, extId, type, showAll);
                offices.addAll (officeList);
            }
        }
        if (StringUtils.isNotBlank(showMyOffice)) {
            OfficeDTO officeDTO = UserUtils.getCurrentUserDTO().getOfficeDTO();
            // 排除管理员
            if (!UserUtils.getCurrentUserDTO().isAdmin()){
                if (org.apache.commons.lang.StringUtils.isNotBlank(officeDTO.getParentIds())) {
                    String[] split = officeDTO.getParentIds().split(",");
                    if (split.length > 2) {
                        Office office = officeMapper.selectById(split[2]);
                        if ("0".equals(office.getIsPublic())) {
                            // isPublic为“0”，当前用户的公司为私有，查询的部门包含自己所属公司全部部门和其他的公有部门
                            if(null != officeDTO && org.apache.commons.lang.StringUtils.isNotBlank(officeDTO.getParentIds())){
                                offices = this.getCompanyFromTree(offices);
                            }
                        }
                    } else {
                        if ("0".equals(officeDTO.getIsPublic())) {
                            // isPublic为“0”，当前用户的公司为私有，查询的部门包含自己所属公司全部部门和其他的公有部门
                            if(null != officeDTO && org.apache.commons.lang.StringUtils.isNotBlank(officeDTO.getParentIds())){
                                offices = this.getCompanyFromTree(offices);
                            }
                        }
                    }
                }
            }
        }
        return offices;
    }

    public List <OfficeDTO> getOldRootTree(String parentId, List <OfficeDTO> list, String extId, String type, String showAll) {
        List <OfficeDTO> offices = Lists.newArrayList ( );
        parentId = StrUtil.isEmpty ( parentId ) ? OfficeDTO.getRootId ( ) : parentId;
        for (OfficeDTO root : list) {
            if (!root.getName().equals("平台运营")){
                if ( parentId.equals ( root.getParentId ( ) ) ) {
                    if ( this.isUseAble ( extId, type, root, showAll ) ) {
                        // 不是被排除节点的子节点
                        List <OfficeDTO> officeList = formatListToTree ( root, list, extId, type, showAll );
                        offices.addAll ( officeList );
                    }
                }
            }
        }
        return offices;
    }

    /**
     * 在tree数据中找到当前登录人的“集团”以及“公司”
     */
    public List<OfficeDTO> getCompanyFromTree(List<OfficeDTO> rootTrees){
        // 当前登录人的集团id
        String corporationId = UserUtils.getCurrentUserDTO().getCompanyDTO().getId();
        // 公司id
        String parentIds = officeMapper.selectById(UserUtils.getCurrentUserDTO().getOfficeDTO().getId()).getParentIds();
        String companyId = null;
        String[] split = parentIds.split(",");
        if(split.length>2){
            companyId = split[2];
        }else{
            companyId = UserUtils.getCurrentUserDTO().getOfficeDTO().getId();
        }
        List<OfficeDTO> os = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(rootTrees)) {
            String finalCompanyId = companyId;
            rootTrees.stream().forEach(item->{
                /*if ("1".equals(item.getIsPublic())) { // 找到公有的集团
                    OfficeDTO officeDTO = item;
                    if (CollectionUtil.isNotEmpty(item.getChildren())){
                        officeDTO.setChildren(item.getChildren());
                    }
                    os.add(officeDTO);
                }else{
                    if(item.getId().equals(corporationId)){  // 找到登录人的集团
                        OfficeDTO officeDTO = item;
                        if (CollectionUtil.isNotEmpty(item.getChildren())&&!"".equals(finalCompanyId)){
                            List<OfficeDTO> companys = new ArrayList<>();
                            item.getChildren().stream().forEach(child->{
                                if(child.getId().equals(finalCompanyId) || "1".equals(child.getIsPublic())){ // 登录人的公司 或者 公有公司
                                    companys.add(child);
                                }
                            });
                            officeDTO.setChildren(companys);
                        }
                        os.add(officeDTO);
                    }
                }*/
                OfficeDTO officeDTO = item;
                if (CollectionUtil.isNotEmpty(item.getChildren())){
                    officeDTO.setChildren(item.getChildren());
                }
                os.add(officeDTO);
            });
        }
        return os;
    }

    public OfficeDTO getOfficeById(String id){
        return baseMapper.getOfficeById(id);
    }

    public OfficeDTO getParentOfficeById(String id){
        return baseMapper.getParentOfficeById(id);
    }

    public List<String> getOfficeNameByIds(List<String> idList){
        return baseMapper.getOfficeNameByIds(idList);
    }

    public List<OfficeDTO> getAllCompany() {
        QueryWrapper<OfficeDTO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("so.del_flag","0");
        queryWrapper.eq("so.parent_id","0");  // parent_id 为 “0”
        queryWrapper.orderByDesc("so.name");
        return baseMapper.findList(queryWrapper);
    }


    public List <OfficeDTO> formatListToTree(OfficeDTO root, List <OfficeDTO> allList, String extId, String type, String showAll) {
        String rootId = root.getId ( );

        // type为2时，是选择部门，因此禁用type为1的公司节点
        if ( OfficeTypeEnum.OFFICE.getValue ( ).equals ( type ) && root.getType ( ).equals ( OfficeTypeEnum.COMPANY.getValue ( ) ) ) {
            root.setDisabled ( true );
        } else {
            root.setDisabled ( false );
        }
        // 最终的树形态
        List <OfficeDTO> trees = Lists.newArrayList ( );

        // 把需要构造树的所有列表, 根据以父id作为key, 整理为列表
        Map <String, List <OfficeDTO>> treeMap = Maps.newHashMap ( );
        for (OfficeDTO entity : allList) {
            List <OfficeDTO> offices = treeMap.get ( entity.getParent ( ).getId ( ) );
            if ( offices == null ) {
                offices = Lists.newLinkedList ( );
            }

            if ( this.isUseAble ( extId, type, root, showAll ) ) {

                // 如果是查找公司，只返回公司数据，如果是查询部门，则一起返回公司部门数据
                if ( OfficeTypeEnum.COMPANY.getValue ( ).equals ( type ) && entity.getType ( ).equals ( type )
                        || OfficeTypeEnum.OFFICE.getValue ( ).equals ( type )
                        || StrUtil.isBlank ( type )
                ) {

                    // type为2时，是选择部门，因此禁用type为1的公司节点
                    if ( OfficeTypeEnum.OFFICE.getValue ( ).equals ( type ) && entity.getType ( ).equals ( OfficeTypeEnum.COMPANY.getValue ( ) ) ) {
                        entity.setDisabled ( true );
                    } else {
                        entity.setDisabled ( false );
                    }
                    offices.add ( entity );
                }

                treeMap.put ( entity.getParent ( ).getId ( ), offices );
            }
        }

        // 开始递归格式化
        List <OfficeDTO> children = treeMap.get ( rootId );
        if ( children != null ) {
            for (OfficeDTO parent : children) {
                formatFillChildren ( parent, treeMap );
                trees.add ( parent );
            }
        }

        root.setChildren ( trees );
        return Lists.newArrayList ( root );
    }

    /**
     * 从treeMap中取出子节点填入parent, 并递归此操作
     **/
    private void formatFillChildren(OfficeDTO parent, Map <String, List <OfficeDTO>> treeMap) {

        List <OfficeDTO> children = treeMap.get ( parent.getId ( ) );
        parent.setChildren ( children );
        if ( children != null && !children.isEmpty ( ) ) {
            for (OfficeDTO child : children) {
                formatFillChildren ( child, treeMap );
            }
        }
    }

    private boolean isUseAble(String extId, String type, OfficeDTO dto, String showAll) {
        return (StringUtils.isBlank ( extId ) || (extId != null && !extId.equals ( dto.getId ( ) ) && dto.getParentIds ( ).indexOf ( "," + extId + "," ) == -1))
                && (type == null || (type != null && (type.equals ( OfficeTypeEnum.COMPANY.getValue ( ) ) ? type.equals ( dto.getType ( ) ) : true)))
                && (CommonConstants.YES.equals ( showAll ) || CommonConstants.YES.equals ( dto.getUseable ( ) ));
    }

    /**
     * 根据部门名称查询部门信息
     * @param officeName
     * @return
     */
    public List<OfficeDTO> getOfficeAllByOfficeName(String officeName){
        List<OfficeDTO> officeList = officeMapper.getOfficeAllByOfficeName(officeName);

        return officeList;
    }

    /**
     * 根据部门名称查询部门信息
     * @param officeName
     * @return
     */
    public List<OfficeDTO> getOfficeAllByFinanceOfficeName(String officeName){
        List<OfficeDTO> officeList = officeMapper.getOfficeAllByFinanceOfficeName(officeName);

        return officeList;
    }

    public List <OfficeDTO> getRootTree2(List<OfficeDTO> list, String extId, String type, String showAll) {
        List<OfficeDTO> offices = Lists.newArrayList ();
        List<OfficeDTO> rootTrees = officeWrapper.toDTO (super.getChildren (new Office (OfficeDTO.getRootId ())));
        for (OfficeDTO root : rootTrees) {
            if (this.isUseAble ( extId, type,root, showAll )){
                // 不是被排除节点的子节点
                List<OfficeDTO> officeList = formatListToTree2 (root, list, extId, type, showAll);
                offices.addAll (officeList);
            }
        }
        return offices;
    }

    public List<OfficeDTO> formatListToTree2(OfficeDTO root, List<OfficeDTO> allList, String extId, String type, String showAll) {
        String rootId = root.getId ();

        // type为1时，是选择公司，因此禁用type为2的部门节点
        if(OfficeTypeEnum.COMPANY.getValue ().equals(type) && root.getType().equals(OfficeTypeEnum.COMPANY.getValue ())){
            root.setDisabled(false);
        }else {
            root.setDisabled(true);
        }
        // 最终的树形态
        List<OfficeDTO> trees = Lists.newArrayList ();

        // 把需要构造树的所有列表, 根据以父id作为key, 整理为列表
        Map <String, List<OfficeDTO>> treeMap = Maps.newHashMap ();
        for (OfficeDTO entity : allList) {
            List<OfficeDTO> offices = treeMap.get (entity.getParent ().getId ());
            if (offices == null) {
                offices = Lists.newLinkedList ();
            }

            if (this.isUseAble ( extId, type,root, showAll )){
                // type为2时，是选择部门，因此禁用type为1的公司节点
                if(OfficeTypeEnum.COMPANY.getValue ().equals(type) && entity.getType().equals(OfficeTypeEnum.COMPANY.getValue ())){
                    entity.setDisabled(false);
                }else {
                    entity.setDisabled(true);
                }
                offices.add (entity);
                treeMap.put (entity.getParent ().getId (), offices);
            }
        }

        // 开始递归格式化
        List<OfficeDTO> children = treeMap.get (rootId);
        if (children != null) {
            for (OfficeDTO parent : children) {
                formatFillChildren (parent, treeMap);
                trees.add (parent);
            }
        }

        root.setChildren (trees);
        return Lists.newArrayList (root);
    }


    public List<Office> selectListByParentId(String parentId) {
        return officeMapper.selectListByParentId(parentId);
    }

    public List<Office> selectListByIsPublic(String isPublic){
        return officeMapper.selectListByIsPublic(isPublic);
    }


    public List getFinanceTree(List<OfficeDTO> objects, String extId, String type, String showAll, String showMyOffice) {
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        String id = userDTO.getTenantDTO().getId();

        List<OfficeDTO> offices = Lists.newArrayList ();
        // 获取到所有parent_id为‘0’的部门数据
        List<Office> children = officeMapper.getChild(OfficeDTO.getRootId());
        List<OfficeDTO> rootTrees = OfficeWrapper.INSTANCE.toDTO (children);
        switch (id){
            case "10002":   //综合管理部
                for (OfficeDTO root : rootTrees) {
                    if (root.getId().equals("1588068195545808898")||root.getId().equals("1680778353809350658")){
                        if (this.isUseAble ( extId, type,root, showAll )){
                            // 不是被排除节点的子节点
                            List<OfficeDTO> officeList = formatListToTree (root, objects, extId, type, showAll);
                            offices.addAll (officeList);
                        }
                    }
                }
                break;
            case "10005":   //项目公司
                for (OfficeDTO root : rootTrees) {
                    if (root.getId().equals("1588068195545808898")||root.getId().equals("1619953441268330498")){
                        if (this.isUseAble ( extId, type,root, showAll )){
                            // 不是被排除节点的子节点
                            List<OfficeDTO> officeList = formatListToTree (root, objects, extId, type, showAll);
                            offices.addAll (officeList);
                        }
                    }
                }
                break;
            default:
                for (OfficeDTO root : rootTrees) {
                    if (root.getId().equals("1588068195545808898")){
                        if (this.isUseAble ( extId, type,root, showAll )){
                            // 不是被排除节点的子节点
                            List<OfficeDTO> officeList = formatListToTree (root, objects, extId, type, showAll);
                            offices.addAll (officeList);
                        }
                    }
                }
                break;
        }
        if (StringUtils.isNotBlank(showMyOffice)) {
            OfficeDTO officeDTO = UserUtils.getCurrentUserDTO().getOfficeDTO();
            // 排除管理员
            if (!UserUtils.getCurrentUserDTO().isAdmin()){
                if (org.apache.commons.lang.StringUtils.isNotBlank(officeDTO.getParentIds())) {
                    String[] split = officeDTO.getParentIds().split(",");
                    if (split.length > 2) {
                        Office office = officeMapper.selectById(split[2]);
                        if ("0".equals(office.getIsPublic())) {
                            // isPublic为“0”，当前用户的公司为私有，查询的部门包含自己所属公司全部部门和其他的公有部门
                            if(null != officeDTO && org.apache.commons.lang.StringUtils.isNotBlank(officeDTO.getParentIds())){
                                offices = this.getCompanyFromTree(offices);
                            }
                        }
                    } else {
                        if ("0".equals(officeDTO.getIsPublic())) {
                            // isPublic为“0”，当前用户的公司为私有，查询的部门包含自己所属公司全部部门和其他的公有部门
                            if(null != officeDTO && org.apache.commons.lang.StringUtils.isNotBlank(officeDTO.getParentIds())){
                                offices = this.getCompanyFromTree(offices);
                            }
                        }
                    }
                }
            }
        }
        return offices;
    }

    public IPage<OfficeDTO> findListTree(Page<OfficeDTO> page, OfficeDTO officeDTO) throws Exception{
        QueryWrapper<OfficeDTO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("so.del_flag","0");
        queryWrapper.orderByAsc("so.create_time");
        if (ObjectUtil.isNotEmpty(officeDTO)) {
            if (org.apache.commons.lang.StringUtils.isNotBlank(officeDTO.getName())) {
                List<String> ids = new ArrayList<>();
                List<Office> list = this.list(new QueryWrapper<Office>().lambda()
                        .like(org.apache.commons.lang.StringUtils.isNotBlank(officeDTO.getName()),Office::getName, officeDTO.getName())
                );
                list.stream().forEach(item->{
                    ids.add(item.getId());
                    if (org.apache.commons.lang.StringUtils.isNotBlank(item.getParentId())) {
                        String parentId = item.getParentId();
                        while (true) {
                            Office byId = this.getOne(new QueryWrapper<Office>().lambda().eq(Office::getId, parentId));
                            if (ObjectUtil.isNotEmpty(byId)) {
                                ids.add(byId.getId());
                                if (org.apache.commons.lang.StringUtils.isBlank(byId.getParentId())) {
                                    break;
                                } else {
                                    parentId = byId.getParentId();
                                }
                            } else {
                                break;
                            }
                        }
                    }
                    List<String> childIdList = this.list(new QueryWrapper<Office>().lambda().eq(Office::getParentId, item.getId())).stream().map(Office::getId).collect(Collectors.toList());
                    while (true) {
                        if (CollectionUtil.isNotEmpty(childIdList)) {
                            childIdList.stream().forEach(childId->{
                                ids.add(childId);
                            });
                            List<String> childIdS = this.list(new QueryWrapper<Office>().lambda().in(Office::getParentId, childIdList)).stream().map(Office::getId).collect(Collectors.toList());
                            if (CollectionUtil.isNotEmpty(childIdS)) {
                                childIdList = childIdS;
                            } else {
                                break;
                            }
                        } else {
                            break;
                        }
                    }
                });
                List<String> lastIdList = ids.stream().distinct().collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(lastIdList)){
                    queryWrapper.in("so.id",lastIdList);
                } else {
                    return new Page<>();
                }
            }
        }
        return officeMapper.findListTree(page, queryWrapper);
    }
}
