/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved.
 * <a>http://www.crunii.com</a>
 */
package com.crunii.micro.service.sysmgr.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.crunii.micro.common.constants.CommonConstants;
import com.crunii.micro.common.dto.PageReq;
import com.crunii.micro.common.dto.PageRsp;
import com.crunii.micro.common.dto.Result;
import com.crunii.micro.common.excel.ExcelUtil;
import com.crunii.micro.common.exception.BusinessException;
import com.crunii.micro.common.utils.DateUtil;
import com.crunii.micro.common.utils.StreamUtils;
import com.crunii.micro.domain.dto.TsmRoleDto;
import com.crunii.micro.domain.dto.Worker;
import com.crunii.micro.domain.entity.main.TsmOrg;
import com.crunii.micro.domain.entity.main.TsmPropertyValue;
import com.crunii.micro.domain.entity.main.TsmWorkerOrgAll;
import com.crunii.micro.domain.repo.main.*;
import com.crunii.micro.service.sysmgr.api.domain.dto.OrgNode;
import com.crunii.micro.service.sysmgr.api.domain.dto.OrgSimpleVO;
import com.crunii.micro.service.sysmgr.constants.SysmgrConstants;
import com.crunii.micro.service.sysmgr.dto.ChildrenStatisticsRspVO;
import com.crunii.micro.service.sysmgr.dto.org.*;
import com.crunii.micro.service.sysmgr.dto.sysmgr.OrgDto;
import com.crunii.micro.service.sysmgr.dto.sysmgr.OrgTabulationDto;
import com.crunii.micro.service.sysmgr.jdbc.OrgJdbcDao;
import com.crunii.micro.service.sysmgr.service.OrgService;
import com.google.common.base.Stopwatch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.crunii.micro.service.sysmgr.constants.ErrorMsgConstants.*;

/**
 * @author 田平 create 2021/4/25 14:23
 */
@Service
@Slf4j
public class OrgServiceImpl implements OrgService {

    @Resource
    private TsmOrgRepo tsmOrgRepo;

    @Resource
    private OrgJdbcDao orgJdbcDao;

    private static String telephoneExpression = "^[1][3,4,5,7,8,9][0-9]{9}$";
    final Pattern email = Pattern.compile("^(\\w+([-.][A-Za-z0-9]+)*){3,18}@\\w+([-.][A-Za-z0-9]+)*\\.\\w+([-.][A-Za-z0-9]+)*$");
    final Pattern symbol = Pattern.compile("Pattern compile = Pattern.compile(\"[[ _`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\\\\n|\\\\r|\\\\t]+\")");
    final Pattern chinese = Pattern.compile("[\u4e00-\u9fa5]+");
    private final String stratosphere = "stratosphere";//地区-最上级组织
    private final String dataSources = "智慧党建";//数据来源

    @Resource
    private TsmWorkerOrgRepo tsmWorkerOrgRepo;
    @Resource
    private TsmWorkerOrgAllRepo tsmWorkerOrgAllRepo;
    @Resource
    private TsmWorkerRepo tsmWorkerRepo;
    @Resource
    private TsmPropertyValueRepo tsmPropertyValueRepo;

    public TsmOrg getTsmOrg(Long orgId) {
        return tsmOrgRepo.getOne(orgId);
    }

    public Long createOrg(OrgC orgC) {
        validateOrg(orgC);
        Date curr = new Date();
        TsmOrg tsmOrg = new TsmOrg();
        BeanUtils.copyProperties(orgC, tsmOrg);
        tsmOrg.setUpdateTime(curr);
        tsmOrg.setCreateTime(curr);
        tsmOrg.setState(CommonConstants.STATE_VALID);
        tsmOrg.setManagePeople(orgC.getManagePeople());
        tsmOrgRepo.saveAndFlush(tsmOrg);
        return tsmOrg.getOrgId();
    }

    /**
     * 校验组织
     *
     * @param orgC
     */
    private void validateOrg(OrgC orgC) {
        if (orgC == null) {
            throw new BusinessException(ORG_CREATE_REQUEST_ERROR);
        }
        //校验父级组织
        if (ObjectUtil.isEmpty(orgC.getParentOrgId())) {
            throw new BusinessException(ORG_CREATE_REQUEST_NOT_NULL);
        }
        TsmOrg parentOrg = tsmOrgRepo.getOne(orgC.getParentOrgId());
        if (orgC.getParentOrgId() != 0 && (ObjectUtil.isEmpty(parentOrg) || parentOrg.getState() == 0)) {
            throw new BusinessException(ORG_PARENT_NOT_EXIST);
        }
    }

    public boolean checkOrgCode(String orgCode) {
        return orgJdbcDao.checkOrgCode(orgCode);
    }

    public List<OrgNode> getOrgChildren(Long parentOrgId, Integer registrationSystemType) {
        List<OrgNode> orgList = orgJdbcDao.getOrgChildrenNew(parentOrgId, registrationSystemType);
        //手机号脱敏
        for (OrgNode org : orgList) {
            String phone = org.getTelephone();
            if (phone != null && !phone.equals("")) {
                String resultPhone = phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4);
                org.setTelephone(resultPhone);
            }
        }
        return orgList;
    }

    @Override
    public List<OrgSimpleVO> getChildrenByParentOrgIds(List<Long> parentOrgIds) {
        List<TsmOrg> childrenList = tsmOrgRepo.findByParentOrgIdInAndState(parentOrgIds, 1);
        List<OrgSimpleVO> childrenVoList = childrenList.stream().map(item -> {
            OrgSimpleVO vo = new OrgSimpleVO();
            vo.setOrgId(item.getOrgId());
            vo.setOrgCode(item.getOrgCode());
            vo.setOrgName(item.getOrgName());
            vo.setParentOrgId(item.getParentOrgId());
            return vo;
        }).collect(Collectors.toList());
        return childrenVoList;
    }

    /**
     * 通过父组织Id获取子组织(数据权限过滤)
     *
     * @param parentOrgId
     * @return
     */
    public List<OrgNode> getOrgChildrenByParentOrgId(Long parentOrgId) {
        return orgJdbcDao.getOrgChildrenByParentOrgId(parentOrgId);
    }

    @Override
    public List<OrgNode> findOrg(OrgDto orgDto) {
        return orgJdbcDao.findOrg(orgDto);
    }

    public void updateOrg(OrgU orgU) {
        TsmOrg tsmOrg = tsmOrgRepo.getOne(orgU.getOrgId());
        BeanUtils.copyProperties(orgU, tsmOrg);
        if (StringUtils.hasText(orgU.getTelephone())) {
            String mobile = orgU.getTelephone();
            String resultPhone = tsmOrg.getTelephone().substring(0, 3) + "****" + tsmOrg.getTelephone().substring(orgU.getTelephone().length() - 4);
            if (!mobile.equals(resultPhone)) {
                if (mobile.contains("*")) {
                }
                Boolean aBoolean = checkTelephone(mobile);
                if (!aBoolean) {
                }
                tsmOrg.setTelephone(orgU.getTelephone());
            } else {
                tsmOrg.setTelephone(mobile);
            }
        }
        tsmOrg.setUpdateTime(new Date());
        tsmOrgRepo.saveAndFlush(tsmOrg);
    }

    /**
     * 获取所有子组织
     *
     * @param parentOrgId
     * @return
     */
    @Override
    public Set<OrgNode> getAllOrgChildren(Long parentOrgId) {
        List<OrgNode> orgChildren = orgJdbcDao.getOrgChildren(parentOrgId);
        Set<OrgNode> orgNodes = new HashSet<>(orgChildren);
        for (OrgNode orgChild : orgChildren) {
            if (!orgChild.isLeaf()) {
                Set<OrgNode> orgChildrenById = getAllOrgChildren(orgChild.getOrgId());
                if (ObjectUtil.isNotEmpty(orgChildrenById) && orgChildrenById.size() > 0) {
                    orgNodes.addAll(orgChildrenById);
                }
            }
        }
        return orgNodes;
    }

    @Override
    public List<OrgTreeDto> getOrgChildrenTree(Worker worker, OrgTreeReqDto param) {
        List<OrgTreeDto> orgChildrenTree = orgJdbcDao.findOrgChildrenTree(param);
        return orgChildrenTree;
    }

    @Override
    public List<OrgTreeDto> getOrgTreeAuthority(Worker worker, OrgTreeAuthorityReqDto req) {
        // 2024-01-22更改:超级管理员的角色可以查看所有的组织
        List<TsmRoleDto> userRoles = worker.getRoles();
        List<Integer> userRoleIds = StreamUtils.toList(userRoles, TsmRoleDto::getRoleId);
        List<OrgTreeDto> result = null;
        if (StringUtils.hasText(req.getOrgName())) {
            if (userRoleIds.contains(SysmgrConstants.SUPER_ADMIN_ROLE_ID)) {
                // 调用可查看所有组织的方法
                result = orgJdbcDao.findOrgAuthorityBySuperRole(req);
            } else {
                result = orgJdbcDao.findOrgAuthority(worker, req);
            }
        } else if (req.getRecursiveOrNot() == 1) {
            if (userRoleIds.contains(SysmgrConstants.SUPER_ADMIN_ROLE_ID)) {
                // 调用可查看所有组织的方法
                result = orgJdbcDao.getOrgChildBySuperRole(req);
            } else {
                result = orgJdbcDao.getOrgChild(worker, req);
            }
            for (int i = 0; i < result.size(); i++) {
                if (result.get(i).getLeafs() == 1) {
                    result.get(i).setLeaf(true);
                } else {
                    result.get(i).setLeaf(false);
                }
            }
        } else if (req.getRecursiveOrNot() == 0) {
            if (userRoleIds.contains(SysmgrConstants.SUPER_ADMIN_ROLE_ID)) {
                // 调用可查看所有组织的方法
                result = orgJdbcDao.getOrgTreeAuthorityBySuperRole(req);
            } else {
                result = orgJdbcDao.getOrgTreeAuthority(worker, req);
            }
        }
        return result;
    }

    /**
     * 查询团组织
     *
     * @param childrenOrgReqVO
     * @return
     */
    @Override
    public PageRsp<ChildrenOrgRspVO> pageChildrenOrg(PageReq<ChildrenOrgReqVO> childrenOrgReqVO) {
        if(childrenOrgReqVO.getQuery().getIsParent()==null||childrenOrgReqVO.getQuery().getIsParent()==1L){
            return orgJdbcDao.pageChildrenOrg(childrenOrgReqVO);
        }else{
            return orgJdbcDao.pageChildrenOrgNoSubordinate(childrenOrgReqVO);
        }
    }

    @Override
    public Result<Object> exportOrgTabulation(OrgTabulationDto dto) {
        List<OrgTabulationExcel> ycqLeagueVoList = orgJdbcDao.exportOrgTabulation(dto);
        if (ycqLeagueVoList.size() == 0) {
            return Result.ofFail("不存在下级组织");
        }
        ycqLeagueVoList.forEach(e -> e.setOcylIsXztwName(SysmgrConstants.IS_COUNTRY.equals(e.getOcylIsXztw()) ? "是" : "否"));
        try {
            ExcelUtil.writeSingleExcel("下级组织列表", null, ycqLeagueVoList, OrgTabulationExcel.class);
        } catch (IOException e) {
            throw new BusinessException("导出失败");
        }
        return null;
    }

    /**
     * 修改组织
     *
     * @param teamOrgC
     */
    @Override
    public void updateTeamOrg(Worker worker, TeamOrgC teamOrgC) {
        TsmOrg one = tsmOrgRepo.getOne(teamOrgC.getOrgId());
        if (ObjectUtil.isEmpty(one)) {
            throw new BusinessException(ORG_CREATE_ORG_NOT_EXIST);
        }
        TsmOrg parent = tsmOrgRepo.getOne(teamOrgC.getParentOrgId());
        if (ObjectUtil.isEmpty(parent)) {
            throw new BusinessException(ORG_PARENT_NOT_EXIST);
        }
        validateTeamOrg(teamOrgC);
        BeanUtil.copyProperties(teamOrgC, one);
        one.setUpdateUserId(worker.getLoginId());
        one.setUpdateTime(new Date());
        one.setParentOrgCode(parent.getOrgCode());
        tsmOrgRepo.saveAndFlush(one);
        //父级组织设置为非叶子节点
        parent.setIsLeaf(false);
        tsmOrgRepo.saveAndFlush(parent);
    }

    /**
     * 新增组织
     *
     * @param teamOrgC
     * @return
     */
    @Override
    public Long createTeamOrg(Worker worker, TeamOrgC teamOrgC) {
        validateTeamOrg(teamOrgC);
        TsmOrg parent = tsmOrgRepo.getOne(teamOrgC.getParentOrgId());
        if (ObjectUtil.isEmpty(parent)) {
            throw new BusinessException(ORG_PARENT_NOT_EXIST);
        }
        TsmOrg tsmOrg = new TsmOrg();
        Long num = 1L;
        BeanUtil.copyProperties(teamOrgC, tsmOrg);
        tsmOrg.setSortId(num);
        tsmOrg.setUpdateTime(new Date());
        tsmOrg.setCreateTime(new Date());
        tsmOrg.setState(CommonConstants.STATE_VALID);
        tsmOrg.setParentOrgCode(parent.getOrgCode());
        tsmOrg.setIsLeaf(true);
        tsmOrg.setDataSources(dataSources);
        tsmOrgRepo.save(tsmOrg);
        //父级组织设置为非叶子节点
        parent.setIsLeaf(false);
        tsmOrgRepo.saveAndFlush(parent);
        List<TsmOrg> allOrg = tsmOrgRepo.findByParentOrgId(teamOrgC.getParentOrgId());
        //顺序依次后移
        for (TsmOrg org : allOrg) {
            num += 1;
            org.setSortId(num);
        }
        tsmOrgRepo.saveAll(allOrg);
        //给当前用户赋予数据权限
        //tsmWorkerOrgAll表
//        TsmWorkerOrgAll tsmWorkerOrgAll = new TsmWorkerOrgAll();
//        tsmWorkerOrgAll.setOrgId(tsmOrg.getOrgId());
//        tsmWorkerOrgAll.setWorkerId((long) worker.getLoginId());
//        tsmWorkerOrgAll.setOrgCode(tsmOrg.getOrgCode());
//        tsmWorkerOrgAll.setCreateTime(new Date());
//        tsmWorkerOrgAll.setCreateUserId((long) worker.getLoginId());
//        tsmWorkerOrgAll.setRecursiveOrNot(1L);
//        tsmWorkerOrgAllRepo.save(tsmWorkerOrgAll);
        //给拥有当前父级组织的用户写入当前组织权限
        orgJdbcDao.updateWorkerAll(tsmOrg.getOrgId(),tsmOrg.getOrgCode(),parent.getOrgId(),worker.getLoginId());
        return tsmOrg.getOrgId();
    }

    /**
     * 校验新增团组织参数
     *
     * @param teamOrgC
     */
    private void validateTeamOrg(TeamOrgC teamOrgC) {
        //组织类别
        if (!StringUtils.hasText(teamOrgC.getOrgCategoryTree())) {
            throw new BusinessException(ORG_CREATE_TYPE_IS_NULL);
        }
        //组织名称
        if (!StringUtils.hasText(teamOrgC.getOrgName())) {
            throw new BusinessException(ORG_CREATE_NAME_IS_NULL);
        }
        //组织名称不能超过100个字符
        if (teamOrgC.getOrgName().length() > 100) {
            throw new BusinessException(ORG_CREATE_ORG_NAME_OUT);
        }
        //组织名称是否包含特殊字符
        if (symbol.matcher(teamOrgC.getOrgName()).matches()) {
            throw new BusinessException(ORG_CREATE_ORG_NAME_SYMBOL);
        }
        //组织简称
        if (!StringUtils.hasText(teamOrgC.getOrgShortCalled())) {
            throw new BusinessException(ORG_CREATE_SHORT_NAME_IS_NULL);
        }
        //组织简称不能超过100个字符
        if (teamOrgC.getOrgShortCalled().length() > 100) {
            throw new BusinessException(ORG_CREATE_SHORT_ORG_NAME_OUT);
        }
        //组织简称是否包含特殊字符
        if (symbol.matcher(teamOrgC.getOrgShortCalled()).matches()) {
            throw new BusinessException(ORG_CREATE_SHORT_ORG_NAME_SYMBOL);
        }
        //所属行业类别
        if (!StringUtils.hasText(teamOrgC.getOcylIndustryCategory())) {
            throw new BusinessException(ORG_CREATE_TRDE_IS_NULL);
        }
        //父级组织
        if (teamOrgC.getParentOrgId() == null) {
            throw new BusinessException(ORG_CREATE_PARENT_ORG_IS_NULL);
        }
        //联系电话
        if (!StringUtils.hasText(teamOrgC.getTelephone())) {
            throw new BusinessException(ORG_CREATE_TELEPHONE_IS_NULL);
        }
        //是否乡镇党委
        if (teamOrgC.getOcylIsXztw() == null) {
            throw new BusinessException(ORG_CREATE_XZDW_IS_NULL);
        }
        //联系电话
        if (teamOrgC.getTelephone().length() > 30) {
            throw new BusinessException(ORG_CREATE_ORG_NUMBER__OUT);
        }
        //邮箱格式
        if (StringUtils.hasText(teamOrgC.getOrgEmail()) && !email.matcher(teamOrgC.getOrgEmail()).matches()) {
            throw new BusinessException(ORG_CREATE_EMAIL_ERROR);
        }
        //邮箱长度不能超过30
        if (StringUtils.hasText(teamOrgC.getOrgEmail()) && teamOrgC.getOrgEmail().length() > 30) {
            throw new BusinessException(ORG_CREATE_EMAIL_ERROR);
        }
        //组织书记
        if (StringUtils.hasText(teamOrgC.getOrgSecretary()) && teamOrgC.getOrgSecretary().length() > 10) {
            throw new BusinessException(ORG_CREATE_ORG_NUMBER__OUT);
        }
        //组织书记名称是否是汉字
        if (StringUtils.hasText(teamOrgC.getOrgSecretary()) && !chinese.matcher(teamOrgC.getOrgSecretary()).matches()) {
            throw new BusinessException(ORG_CREATE_SECRETARY_ONLY_CHINESE);
        }

    }


    @Override
    public Result<Object> deleteOrg(Long orgId) {
        // 判断该数据是否存在下级组织
        int checkIsBelowOrg = orgJdbcDao.checkIsBelowOrg(orgId);
        if (checkIsBelowOrg > 0) {
            return Result.ofFail("该组织存在下级组织，不可删除!");
        }
        // 判断该组织下是否存在用户
        int checkIsOrgWorker = orgJdbcDao.checkIsOrgWorker(orgId);
        if (checkIsOrgWorker > 0) {
            return Result.ofFail("该组织存在用户，不可删除!");
        }
        orgJdbcDao.deleteOrg(orgId);
        TsmOrg tsmOrg = tsmOrgRepo.getOne(orgId);
        // 这里通过组织原来的父级id的数据,查看上级组织是否还有其他下级组织
        int total = orgJdbcDao.selectCountByOrgParentId(orgId, tsmOrg.getParentOrgId());
        if (total == 0) {
            // 这一步说明删除该组织后,此时的上级组织没有其他下级组织.因此上级组织暂定为叶子结点,is_leaf要改为1(是)
            orgJdbcDao.updateLeaf(SysmgrConstants.LEAF, tsmOrg.getParentOrgId());
        }
        return Result.ofSuccess("操作成功");
    }

    @Override
    public Result<Object> moveDataList(MoveDataListDto dto) {
        // 首先查询已操作上移或者下移的数据信息
        TsmOrg moveOrg = tsmOrgRepo.getOne(dto.getOrgId());
        if (Objects.isNull(moveOrg)) {
            return Result.ofFail("组织不存在!");
        }
        // 因为列表数据是按照上级组织id查询的，因此这里根据上级组织id,需要变更的数据的序列号和前端传的移动类型(上移或下移)来查询出需要被移动的数据
        // 例如 第二行数据, 序列号为3. 第三行数据,序列号为5,用户对第三行数据点击的上移操作,那么原第三行数据序列号要变更为3, 原第二行数据序列号变更为5
        // 2024-01-11改动:因为分页查询下级组织有按钮:是否只查询下级组织, 因此组织上下移动也要根据按钮开启或者关闭来判断调用的dao层方法
        TsmOrg movedOrg;
        if (Objects.isNull(dto.getIsParent())) {
            // 如果前端还没传值，默认为开启了只查询下级组织的按钮来做
            movedOrg = orgJdbcDao.getMovedOrgData(moveOrg.getParentOrgId(), moveOrg.getSortId(),
                    dto.getMoveType());
        } else {
            if (dto.getIsParent()) {
                movedOrg = orgJdbcDao.getMovedOrgData(moveOrg.getParentOrgId(), moveOrg.getSortId(),
                        dto.getMoveType());
            } else {
                movedOrg = orgJdbcDao.getMovedOrgDataSubordinate(moveOrg.getParentOrgId(), moveOrg.getSortId(),
                        dto.getMoveType());
            }
        }
        if (Objects.isNull(movedOrg)) {
            if (1 == dto.getMoveType()) {
                return Result.ofFail("该数据不能上移");
            }
            if (2 == dto.getMoveType()) {
                return Result.ofFail("该数据不能下移");
            }
        }
        // 先变更已操作上移或者下移的数据的序列号，改变后的序列号为被移动的组织信息序列号
        orgJdbcDao.moveOrgSort(moveOrg.getOrgId(), movedOrg.getSortId());
        // 再变更被移动的数据的序列号, 改变后的序列号为已操作的组织序列号
        orgJdbcDao.moveOrgSort(movedOrg.getOrgId(), moveOrg.getSortId());
        return Result.ofSuccess("操作成功!");
    }

    @Override
    public void orgSortData(Long orgId, Long sortId) {
        TsmOrg tsmOrg = tsmOrgRepo.getOne(orgId);
        tsmOrg.setSortId(sortId);
        tsmOrgRepo.saveAndFlush(tsmOrg);
    }

    @Override
    public Result<Object> exportAllOrg(OrgTabulationDto dto, Worker worker) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        String orgId;
        if (StringUtils.hasText(dto.getOrgId())) {
            if (CommonConstants.STATE_NO == Long.parseLong(dto.getOrgId())) {
                // 如果传的orgId为0，不能直接调用后续方法,需要返回错误信息
                return Result.ofFail("请重新选择组织");
            }
            orgId = dto.getOrgId();
        } else {
            // 获取用户的组织id
            orgId = tsmWorkerRepo.findByLoginIdAndState(9999, CommonConstants.STATE_VALID).getOrgId();
        }

        // 最早使用的java递归写法，发现查询速度过慢。后换成达梦数据库 connect by 和 start with 关键字
        List<OrgTabulationExcel> exportAllOrgList = orgJdbcDao.exportAllOrg(dto, orgId);
        stopwatch.elapsed();
        log.info("数据查询耗时时间:" + stopwatch);
        if (exportAllOrgList.size() == 0) {
            return Result.ofFail("不存在下级组织");
        }
        exportAllOrgList.forEach(e -> e.setOcylIsXztwName(SysmgrConstants.IS_COUNTRY.equals(e.getOcylIsXztw()) ? "是" : "否"));
        try {
            ExcelUtil.writeSingleExcel("导出全部组织列表", null, exportAllOrgList, OrgTabulationExcel.class);
        } catch (IOException e) {
            throw new BusinessException("导出失败");
        }
        stopwatch.elapsed();
        log.info("导出总共耗时时间:" + stopwatch);
        return null;
    }

    /**
     * 查询指定父级以及下级
     *
     * @return
     */
    @Override
    public List<OrgTreeOneDto> getOrgByOne() {
        List<OrgTreeOneDto> result = new ArrayList<>();
        List<TsmPropertyValue> values = tsmPropertyValueRepo.findAllByPropCodeAndState(stratosphere, CommonConstants.STATE_VALID);
        if (values.size() == 0) {
            throw new BusinessException(ORG_NOT_CONFIGURATION);
        }
        for (TsmPropertyValue value : values) {
            OrgTreeOneDto orgTreeOneDto = new OrgTreeOneDto();
            TsmOrg tsmOrg = tsmOrgRepo.findByOrgCode(value.getValueCode());
            BeanUtil.copyProperties(tsmOrg, orgTreeOneDto);
            if (!tsmOrg.getIsLeaf()) {
                Set<OrgNode> allOrgChildren = getAllOrgChildren(tsmOrg.getOrgId());
                ArrayList<OrgNode> arrayList = new ArrayList<>(allOrgChildren);
                orgTreeOneDto.setChildren(arrayList);
            }
            result.add(orgTreeOneDto);
        }
        return result;
    }

    @Override
    public PageRsp<ChildrenStatisticsRspVO> pageChildrenStatistics(PageReq<ChildrenOrgReqVO> childrenOrgReqVO) {
        return orgJdbcDao.pageChildrenStatistics(childrenOrgReqVO);
    }

    @Override
    public void exportChildrenStatistics(ChildrenOrgReqVO dto) {
        TsmOrg one = tsmOrgRepo.getOne(dto.getParentOrgId());
        if (ObjectUtil.isEmpty(one)|| !StringUtils.hasText(one.getOrgName())){
            throw new BusinessException(ORG_CREATE_NAME_IS_NULL);
        }
        List<ChildrenStatisticsRspVO> childrenStatistics = orgJdbcDao.getChildrenStatistics(dto);
        try {
            ExcelUtil.writeSingleExcel(one.getOrgName()+"组织信息待完善清单", "sheet", childrenStatistics, ChildrenStatisticsRspVO.class);
        } catch (IOException e) {
            throw new BusinessException("导出失败");
        }
    }

    /**
     * 根据系统查询所属组织
     * @param affiliatingSystem
     * @return
     */
    @Override
    public List<OrgTreeDto> getOrgBySystem(String affiliatingSystem) {
        if (!StringUtils.hasText(affiliatingSystem)){
            throw new BusinessException(REQUEST_ERROR);
        }
        List<String> values = tsmPropertyValueRepo.findByPropCode("affiliatingSystem").stream().map(TsmPropertyValue::getValueCode).collect(Collectors.toList());
        if (!values.contains(affiliatingSystem)){
            throw new BusinessException(ORG_SYSTEM_NOT_EXIST);
        }
        return orgJdbcDao.getOrgBySystem(affiliatingSystem);
    }


    @Override
    public List<OrgTreeDto> getOrgTreeAuthList(Worker worker, OrgTreeAuthorityReqDto req) {
        List<OrgTreeDto> result = null;
        if (StringUtils.hasText(req.getOrgName())) {
            result = orgJdbcDao.findOrgAuthorityParty(worker, req);
        } else if (req.getRecursiveOrNot() == 1) {
            result = orgJdbcDao.getOrgChildParty(worker, req);
            for (int i = 0; i < result.size(); i++) {
                if (result.get(i).getLeafs() == 1) {
                    result.get(i).setLeaf(true);
                } else {
                    result.get(i).setLeaf(false);
                }
            }
        } else if (req.getRecursiveOrNot() == 0) {
            result = orgJdbcDao.getOrgTreeAuthorityParty(worker, req);
        }
        return result;
    }

    /**
     * 团组织统计导出
     * @author leixb
     * @since 2024-01-24 10:58
     */
    @Override
    public void exportOrgStatistics() {
       List<OrgStatisticsVo> results = orgJdbcDao.exportOrgStatistics();
        try {
            ExcelUtil.writeSingleCommonExcel("团组织统计导出", "团组织统计", results, OrgStatisticsVo.class);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("导出团组织统计:", e);
        }
    }


    /**
     * 设置组织管理员
     *
     * @param worker
     * @param orgManPeopleC
     * @return
     */
    @Override
    public Boolean doManagePeople(Worker worker, OrgManPeopleC orgManPeopleC) {
        TsmOrg one = tsmOrgRepo.getOne(orgManPeopleC.getOrgId());
        if (ObjectUtil.isEmpty(one)) {
            throw new BusinessException(ORG_CREATE_ORG_NOT_EXIST);
        }
        if (ObjectUtil.isNotEmpty(orgManPeopleC) && orgManPeopleC.getManagePeople() == null) {
            throw new BusinessException(ORG_CREATE_REQUEST_NOT_NULL);
        }
        one.setManagePeople(orgManPeopleC.getManagePeople());
        one.setUpdateTime(new Date());
        one.setUpdateUserId(worker.getLoginId());
        tsmOrgRepo.save(one);
        return true;
    }

    public static Boolean checkTelephone(String telephone) {
        Pattern pa = Pattern.compile(telephoneExpression);
        Matcher m = pa.matcher(telephone);
        return m.matches();
    }

    @Override
    public List<TsmOrg> getOrgByZoneId(Long zoneId) {
        return tsmOrgRepo.findOrgByZone(zoneId);
    }

    @Override
    public TsmOrg getOrgByOrgName(String orgName) {
        return tsmOrgRepo.getOrgByOrgName(orgName);
    }
}
