package com.mosty.common.core.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.mosty.common.base.constant.enums.DeletedEnum;
import com.mosty.common.base.exception.Asserts;
import com.mosty.common.base.exception.BusinessException;
import com.mosty.common.base.util.ChineseCharacterUtil;
import com.mosty.common.base.util.DateUtils;
import com.mosty.common.core.business.entity.*;
import com.mosty.common.core.business.entity.vo.*;
import com.mosty.common.core.business.mapper.SysDeptMapper;
import com.mosty.common.core.business.service.*;
import com.mosty.common.core.constant.DataPermissionConstant;
import com.mosty.common.core.login.dto.DeptAllVo;
import com.mosty.common.core.login.dto.DeptDTO;
import com.mosty.common.core.util.http.HttpUtils;
import com.mosty.common.token.JwtSysUser;
import com.mosty.common.token.UserInfo;
import com.mosty.common.token.UserInfoManager;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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

@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept>
        implements SysDeptService {
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private SysUserDeptService sysUserDeptService;
    @Resource
    private SysRoleDeptService sysRoleDeptService;
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysUserService sysUserService;

    public static String DEPT_URL = "http://80.149.27.78:8001/no-auth-api/system/jurisdictions/all";

    @Value("${config.orgCode}")
    private String orgCode;


    @Override
    public IPage<SysDept> selectByPage(DeptPage deptPage) {
        QueryWrapper<SysDept> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(deptPage.getDeptName())) {
            queryWrapper.and(wrapper -> wrapper.like("org_name", deptPage.getDeptName()));
        }
        queryWrapper.and(wrapper -> wrapper.eq("xt_zxbz", DeletedEnum.NATURE.code));
        queryWrapper.and(wrapper -> wrapper.eq("parent_id", DeletedEnum.NATURE.code));
//        queryWrapper.and(wrapper -> wrapper.isNull("parent_id"));
        List<OrderItem> orderBy = Lists.newArrayList(OrderItem.asc("id"));
        deptPage.setOrders(orderBy);
        IPage<SysDept> iPage = this.baseMapper.selectPage(deptPage, queryWrapper);
        if (CollectionUtils.isNotEmpty(iPage.getRecords())) {
            List<SysDept> records = iPage.getRecords();
            records.forEach(this::wrapChildList);
            iPage.setRecords(records);
        }
        return iPage;
    }

    @Override
    public List<SysDept> selectDept(DeptQuery dto) {
        if (dto.getParentid() != null) {
            return this.baseMapper.getDeptListByParentId(dto.getParentid(), dto.getDeptname());
        }
        UserInfo user = UserInfoManager.get();
        String ssbm = getSsbm(user);
        return this.baseMapper.getDeptListByOrgcode(ssbm, dto.getDeptname(), dto.getDeptId());
    }

    @Override
    public List<SysDept> selectDeptForLogin(DeptQuery dto) {
        if (dto.getParentid() != null) {
            return this.baseMapper.getDeptListByParentId(dto.getParentid(), dto.getDeptname());
        }
        return this.baseMapper.getDeptListByOrgcode(null, dto.getDeptname(), dto.getDeptId());
    }

    // 获取用户的查询条件
    public String getSsbm(UserInfo user) {
        // 查询用户权限
        SysRoleVO role = null;
        List<SysRoleVO> userRoles = sysRoleService.getUserRoleList(user.getUserId());
        if (!CollectionUtils.isEmpty(userRoles)) {
            int level = Integer.parseInt(userRoles.get(0).getDataPermissionLevel());
            role = userRoles.get(0);
            for (SysRoleVO item : userRoles) {
                if (level > Integer.parseInt(item.getDataPermissionLevel())) {
                    level = Integer.parseInt(item.getDataPermissionLevel());
                    role = item;
                }
            }
        }
        if (role != null) {
            String level = role.getDataPermissionLevel();
            if ("1".equals(level) || "2".equals(level)) {
                return orgCode;
            } else if ("3".equals(level)) {
                return user.getDszDeptCode();
            } else if ("4".equals(level)) {
                return user.getFxjDeptCode();
            } else {
                return user.getDeptCode();
            }
        }
        return user.getDeptCode();
    }


    private void wrapChildList1(SysDept item, List<SysDept> allList) {
//        List<SysDept> list = this.list(
//                new LambdaQueryWrapper<SysDept>()
//                        .eq(SysDept::getParentId, item.getId())
//                        .eq(SysDept::getXtZxbz, DeletedEnum.NATURE.code)
//        );
        List<SysDept> list = allList.stream().filter(it ->
                !Objects.isNull(it.getParentId()) && it.getParentId().equals(item.getId())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(list)) {
            item.setChildDeptList(list);
            list.forEach(it -> this.wrapChildList1(it, allList));
        }
    }

    private void wrapChildList(SysDept item) {
        List<SysDept> list = this.list(
                new LambdaQueryWrapper<SysDept>()
                        .eq(SysDept::getParentId, item.getId())
                        .eq(SysDept::getXtZxbz, DeletedEnum.NATURE.code)
        );
        if (CollectionUtils.isNotEmpty(list)) {
            item.setChildDeptList(list);
            list.forEach(this::wrapChildList);
        }
    }

    // 获取部门
    public IPage<SysDept> getDept(DeptPage deptPage) {
        QueryWrapper<SysDept> queryWrapper = new QueryWrapper<>();
        queryWrapper.and(wrapper -> wrapper.eq("xt_zxbz", DeletedEnum.NATURE.code));
        if (StringUtils.isBlank(deptPage.getDeptName())) {
            if (StringUtils.isNotBlank(deptPage.getOrgCode())) {
                queryWrapper.and(wrapper -> wrapper.eq("org_code", deptPage.getOrgCode()));
            } else {
                queryWrapper.and(wrapper -> wrapper.isNull("parent_id"));
            }
        }
        if (StringUtils.isNotBlank(deptPage.getIds())) {
            List<String> list = Arrays.asList(deptPage.getIds().split(","));
            queryWrapper.in("id", list);
        }
        queryWrapper.like(StringUtils.isNotBlank(deptPage.getDeptName()), "org_name", deptPage.getDeptName());
        List<OrderItem> orderBy = Lists.newArrayList(OrderItem.asc("id"));
        deptPage.setOrders(orderBy);
        return getBaseMapper().selectPage(deptPage, queryWrapper);
    }

    @Override
    public List<DeptDTO> selectUserDeptList(Long userId) {
        return sysDeptMapper.selectUserDeptList(userId);
    }

    @Override
    public List<SysDept> getChildDeptList(Long deptId) {
        QueryWrapper<SysDept> queryWrapper = new QueryWrapper<>();
        queryWrapper.and(wrapper -> wrapper.eq("parent_id", deptId));
        return getBaseMapper().selectList(queryWrapper);
    }

    @Override
    public SysDeptVO getAllChildDeptList(SysDept sysDept, DeptTreeVO deptTreeVO) {
        SysDeptVO sysDeptVO = BeanUtil.copyProperties(sysDept, SysDeptVO.class);

        String keyword = StringUtils.isEmpty(deptTreeVO.getKeyword()) ? null : deptTreeVO.getKeyword();
        QueryWrapper<SysDept> queryWrapper = new QueryWrapper<>();
        UserInfo userInfo = UserInfoManager.get();
        //获取最大权限角色
        String level = userInfo.getLevel();
        if (DataPermissionConstant.DATA_SCOPE_COUNTY.equals(level) || DataPermissionConstant.DATA_SCOPE_DEPT_AND_CHILD.equals(level) || DataPermissionConstant.DATA_SCOPE_DEPT.equals(level) || DataPermissionConstant.DATA_SCOPE_SELF.equals(level)) {
            queryWrapper.and(wrapper -> wrapper.like("root_path", sysDept.getRootPath() + "%"));
        }
        //部门查询
        List<SysDept> allDept = getBaseMapper().selectList(queryWrapper);
        if (CollectionUtils.isEmpty(allDept)) {
            return sysDeptVO;
        }
        List<SysDeptVO> natureList = allDept.stream().filter(dept -> DeletedEnum.NATURE.code.equals(dept.getXtZxbz()))
                .map(dept -> BeanUtil.copyProperties(dept, SysDeptVO.class)).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(natureList)) {
            return sysDeptVO;
        }

        if (keyword != null) {
            Map<Long, SysDeptVO> idMap = natureList.stream().collect(Collectors.toMap(SysDeptVO::getId, vo -> vo));
            Set<SysDeptVO> containSet = Sets.newHashSet();
            natureList.stream().filter(dept -> dept.getOrgName().contains(keyword) || dept.getBmpyszm().toLowerCase().contains(keyword))
                    .forEach(dept -> {
                        try {
                            for (String id : dept.getRootPath().split("_")) {
                                SysDeptVO sysDeptVO1 = idMap.get(Long.parseLong(id));
                                if (sysDeptVO1 != null) {
                                    containSet.add(sysDeptVO1);
                                }
                            }
                        } catch (Exception e) {
                            log.error("解析跟目录地址异常：dept={}" + JSON.toJSONString(dept));
                        }
                    });
            natureList = Lists.newArrayList(containSet);
        }
        // 递归组织组织机构树
        wrapChildList(sysDeptVO, natureList);

        return sysDeptVO;
    }

    @Override
    @JwtSysUser
    public Long saveInfo(AddDeptVO addDeptVO, String ipAddress) {
        SysDept sysDept = BeanUtil.copyProperties(addDeptVO, SysDept.class);
        String lowerCase = ChineseCharacterUtil.getLowerCase(addDeptVO.getOrgName(), false);
        sysDept.setBmpyszm(lowerCase);
        UserInfo userInfo = UserInfoManager.get();
        sysDept.setXtZxbz(DeletedEnum.NATURE.code);
        String rootPath;
        sysDept.setXtZhxgsj(new Date());
        sysDept.setXtCjsj(new Date());
        sysDept.setXtLrip(ipAddress);
        sysDept.setXtZhxgid(userInfo.getUserId());
        sysDept.setXtZhxgrxm(userInfo.getUserName());
        sysDept.setXtZhxgrbmid(userInfo.getDeptId());
        sysDept.setXtZhxgrbm(userInfo.getDeptName());
        sysDept.setBz(addDeptVO.getBz());
        sysDept.setXtLrsj(new Date());
        sysDept.setXtLrrid(userInfo.getUserId());
        sysDept.setXtLrrxm(userInfo.getUserName());
        sysDept.setXtLrrbmid(userInfo.getDeptId().toString());
        sysDept.setXtLrrbm(userInfo.getDeptName());
        this.save(sysDept);
        if (Objects.nonNull(sysDept.getParentId())) {
            SysDept dept = this.getById(addDeptVO.getParentId());
            Asserts.check(dept == null, "传入的父id对应的部门信息不存在");
            rootPath = dept.getRootPath().endsWith("_") ?
                    (dept.getRootPath() + sysDept.getId()) : (dept.getRootPath() + "_" + sysDept.getId());
        } else {
            rootPath = sysDept.getId() + "_";
        }
        sysDept.setRootPath(rootPath);
        sysDeptMapper.updateById(sysDept);
        return sysDept.getId();

    }

    @Override
    @JwtSysUser
    public void updateInfo(SysDeptVO sysDept, String ipAddress) {
        SysDept oldSysDept = this.getBaseMapper().selectById(sysDept.getId());
        Asserts.check(oldSysDept == null, "主键为 %s 的部门信息不存在", sysDept.getId());
        SysDept sysDeptEntity = BeanUtil.copyProperties(sysDept, SysDept.class);
        String lowerCase = ChineseCharacterUtil.getLowerCase(sysDept.getOrgName(), false);
        sysDeptEntity.setBmpyszm(lowerCase);
        UserInfo userInfo = UserInfoManager.get();
        sysDeptEntity.setXtZxbz(DeletedEnum.NATURE.code);
        sysDeptEntity.setXtZhxgsj(new Date());
        sysDeptEntity.setXtLrip(ipAddress);
        sysDeptEntity.setXtZhxgid(userInfo.getUserId());
        sysDeptEntity.setXtZhxgrxm(userInfo.getUserName());
        sysDeptEntity.setXtZhxgrbmid(userInfo.getDeptId());
        sysDeptEntity.setXtZhxgrbm(userInfo.getDeptName());
        this.updateById(sysDeptEntity);

    }

    @Override
    @JwtSysUser
    public void delete(DeleteDeptVO deleteDeptVO, String ipAddress, UserInfo userInfo) {
        SysDept oldSysDept = this.getBaseMapper().selectById(deleteDeptVO.getId());
        Asserts.check(oldSysDept == null, "主键为 %s 的部门信息不存在", deleteDeptVO.getId());
        //判断部门角色表
        List<SysUserDept> userDepts = sysUserDeptService.listByDeptId(deleteDeptVO.getId());
        Asserts.check(!CollectionUtils.isEmpty(userDepts), "主键为 %s 的部门含有关联角色，请解绑", deleteDeptVO.getId());
        //判断部门用户表
        List<SysRoleDept> roleDepts = sysRoleDeptService.listByDeptId(deleteDeptVO.getId());
        Asserts.check(!CollectionUtils.isEmpty(roleDepts), "主键为 %s 的部门含有关联用户，请解绑", deleteDeptVO.getId());
        oldSysDept.setXtZxbz(DeletedEnum.NATURE.code);
        oldSysDept.setXtZhxgsj(new Date());
        oldSysDept.setXtLrip(ipAddress);
        oldSysDept.setXtZhxgid(userInfo.getUserId());
        oldSysDept.setXtZhxgrxm(userInfo.getUserName());
        oldSysDept.setXtZhxgrbmid(userInfo.getDeptId());
        oldSysDept.setXtZhxgrbm(userInfo.getDeptName());
        oldSysDept.setXtZxbz(1);
        oldSysDept.setXtZxyy(deleteDeptVO.getXtZxyy());
        this.updateById(oldSysDept);
    }

    @Override
    public IPage<UserDeptVO> selectUserPageByDept(UserByDeptPage userByDeptPage) {
        return sysDeptMapper.selectUserPageByDept(userByDeptPage);
    }

    @Override
    public IPage<RoleDeptVO> selectRolePageByDept(RoleByDeptPage roleByDeptPage) {
        return sysDeptMapper.selectRolePageByDept(roleByDeptPage);
    }

    @Override
    public void saveRoleDeptInfo(AddRoleDeptVO roleDeptVO) {
        SysDept dept = this.getById(roleDeptVO.getDeptId());
        Asserts.check(dept == null, "主键为 %s 的部门信息不存在", roleDeptVO.getDeptId());
        List<SysRoleDept> sysRoleDeptList = new ArrayList<>();
        List<Long> roleIds = roleDeptVO.getRoleIds();
        roleIds.forEach(roleId -> {
            SysRole role = sysRoleService.getById(roleId);
            Asserts.check(role == null, "主键为 %s 的角色信息不存在", roleDeptVO.getDeptId());
            SysRoleDept sysRoleDept = new SysRoleDept();
            sysRoleDept.setDeptId(roleDeptVO.getDeptId());
            sysRoleDept.setRoleId(roleId);
            sysRoleDeptList.add(sysRoleDept);
        });
        sysRoleDeptService.remove(new LambdaQueryWrapper<SysRoleDept>().eq(SysRoleDept::getDeptId, roleDeptVO.getDeptId()));
        sysRoleDeptService.saveBatch(sysRoleDeptList);
    }

    @Override
    public void saveUserDeptInfo(AddUserDeptVO addUserDeptVO) {
        SysUser user = sysUserService.getById(addUserDeptVO.getUserId());
        Asserts.check(user == null, "主键为 %s 的用户信息不存在", addUserDeptVO.getUserId());
        SysDept dept = this.getById(addUserDeptVO.getDeptId());
        Asserts.check(dept == null, "主键为 %s 的部门信息不存在", addUserDeptVO.getDeptId());
        SysUserDept userDept = sysUserDeptService.getByDeptIdAndUserId(addUserDeptVO.getDeptId(), addUserDeptVO.getUserId());
        Asserts.check(userDept != null, "该部门已经含有当前用户");
        SysUserDept sysUserDept = BeanUtil.copyProperties(addUserDeptVO, SysUserDept.class);
        sysUserDeptService.save(sysUserDept);
    }

    @Override
    public void deleteUserDeptInfo(DeleteUserDeptVO deleteUserDeptVO) {
        sysUserDeptService.remove(new LambdaQueryWrapper<SysUserDept>().eq(SysUserDept::getDeptId, deleteUserDeptVO.getDeptId())
                .in(SysUserDept::getUserId, deleteUserDeptVO.getUserIds()));
    }

    @Override
    public List<Long> getAllChildDeptIds(Long deptId) {
        List<Long> ids = new ArrayList<>();
        wrapChildIdList(deptId, ids);
        return ids;
    }


    private void wrapChildIdList(Long id, List<Long> ids) {
        List<SysDept> list = this.list(new LambdaQueryWrapper<SysDept>().eq(SysDept::getParentId, id).eq(SysDept::getXtZxbz, DeletedEnum.NATURE.code));

        if (CollectionUtils.isNotEmpty(list)) {
            List<Long> deptIds = list.stream().map(SysDept::getId).collect(Collectors.toList());
            ids.addAll(deptIds);
            list.forEach(dept -> wrapChildIdList(dept.getId(), ids));
        }
    }

    /**
     * 递归查询子部门集合
     *
     * @param sysDeptVO  当前部门信息
     * @param natureList 所有部门信息
     */
    private void wrapChildList(SysDeptVO sysDeptVO, List<SysDeptVO> natureList) {
        Long rootId = sysDeptVO.getId();
        List<SysDeptVO> collect = natureList.stream().filter(dept -> rootId.equals(dept.getParentId())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(collect)) {
            sysDeptVO.setChildDeptList(collect);
        }
        if (CollectionUtils.isNotEmpty(collect)) {
            collect.forEach(dept -> wrapChildList(dept, natureList));
        }
    }

    @Override
    public SysDept getDeptByOrgCode(String orgCode) {
        LambdaQueryWrapper<SysDept> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysDept::getOrgCode, orgCode).eq(SysDept::getXtZxbz, DeletedEnum.NATURE.code);
        return sysDeptMapper.selectOne(lambdaQueryWrapper);
    }

    @Override
    public Boolean deptSys() {
        Map<String, Object> params = new HashMap<>();
        String rs = HttpUtils.executeGet(DEPT_URL, params);
        JSONObject json = JSONObject.parseObject(rs);
        if (json.getBoolean("success")) {
            JSONArray array = json.getJSONArray("data");
            if (CollectionUtils.isNotEmpty(array)) {
                for (int i = 0; i < array.size(); i++) {
                    JSONObject deptJson = array.getJSONObject(i);
                    String orgCode = deptJson.getString("jurisdictionCode");
                    if (orgCode.startsWith("511421")) {
                        String xtLrsj = deptJson.getString("createTime");
                        xtLrsj = xtLrsj.replace("T", " ");
                        String xtZhxgsj = deptJson.getString("lastModifiedTime");
                        xtZhxgsj = xtZhxgsj.replace("T", " ");
                        Integer xtZxbz = DeletedEnum.NATURE.code;
                        if (!"1".equals(deptJson.getString("zt"))) {
                            xtZxbz = DeletedEnum.DELETED.code;
                        }
                        SysDept sysDept = getDeptByOrgCode(orgCode);
                        if (sysDept == null) {
                            sysDept = new SysDept();
                        }
                        sysDept.setOrgCode(deptJson.getString("jurisdictionCode"));
                        sysDept.setOrgName(deptJson.getString("jurisdictionName"));
//                        String orgJc = deptJson.getString("jurisdictionName").replace("四川省眉山市", "");
//                        sysDept.setOrgJc(orgJc);
                        sysDept.setXtCjsj(new Date());
                        sysDept.setXtLrsj(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, xtLrsj));
                        sysDept.setXtZhxgsj(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, xtZhxgsj));
                        sysDept.setXzqh("511421");
                        sysDept.setXtZxbz(xtZxbz);
                        if (sysDept.getId() == null) {
                            String rootPath = "";
                            String lowerCase = ChineseCharacterUtil.getLowerCase(sysDept.getOrgName(), false);
                            sysDept.setBmpyszm(lowerCase);
                            this.save(sysDept);
                            JSONObject parent = deptJson.getJSONObject("parent");
                            if (Objects.nonNull(parent)) {
                                String parentOrgCode = parent.getString("jurisdictionCode");
                                if (parentOrgCode.startsWith("511421")) {
                                    SysDept dept = getDeptByOrgCode(parentOrgCode);
                                    Asserts.check(dept == null, "传入的父CODE对应的部门信息不存在");
                                    rootPath = dept.getRootPath().endsWith("_") ?
                                            (dept.getRootPath() + sysDept.getId()) : (dept.getRootPath() + "_" + sysDept.getId());
                                }
                            } else {
                                rootPath = sysDept.getId() + "_";
                            }
                            sysDept.setRootPath(rootPath);
                            sysDeptMapper.updateById(sysDept);
                        } else {
                            sysDept.setXtZxbz(DeletedEnum.NATURE.code);
                            sysDeptMapper.updateById(sysDept);
                        }
                    }
                }
            }
        }
        return true;
    }

    @Override
    public IPage<SysDept> getDeptList(DeptPage deptPage) {
        if (StringUtils.isBlank(deptPage.getOrgCode())) {
            throw new BusinessException("orgCode不能为null");
        }
        deptPage.setOrgCode(deptPage.getOrgCode());
        IPage<SysDept> iPage = getDept(deptPage);
        if (CollectionUtils.isNotEmpty(iPage.getRecords())) {
            List<SysDept> records = iPage.getRecords();
            records.forEach(this::wrapChildList);
            iPage.setRecords(records);
        }
        return iPage;
    }

    @Override
    public List<String> getChildDept(String deptid) {
        SysDept dept = this.baseMapper.selectById(deptid);
        List<String> deptIds = new ArrayList<>();
        this.getChildList(dept, deptIds);
        return deptIds;
    }

    @Override
    public List<String> getChildDeptByOrgCode(String orgcode) {
        SysDept dept = this.baseMapper.selectOne(
                new LambdaQueryWrapper<SysDept>()
                        .eq(SysDept::getXtZxbz, "0")
                        .eq(SysDept::getOrgCode, orgcode)
        );
        List<String> orgcodes = new ArrayList<>();
        this.getChildListByOrgcode(dept, orgcodes);
        return orgcodes;
    }

    @Override
    public DeptAllVo getOrgByDeptId(String deptid) {
        DeptAllVo vo = new DeptAllVo();
        SysDept dept = this.baseMapper.selectById(deptid);
        if (dept != null) {
            vo.setOrgType(dept.getOrgType());
            vo.setOrgLevel(dept.getOrgLevel());
            vo.setOrgBizType(dept.getOrgBizType());
            String rootPath = dept.getRootPath();
            // 省厅
            if (dept.getParentId() == 0) {
                this.setDept(vo, dept);
                return vo;
            }
            if (rootPath != null) {
                String[] paths = rootPath.split("_");
                this.setDept(vo, dept);
                SysDept dept1 = this.baseMapper.selectById(paths[1]);
                this.setDsz(vo, dept1);
                if (paths.length == 2 || paths.length == 3) {
                    this.setFxj(vo, dept);
                } else if (paths.length >= 4) {
                    SysDept dept2 = this.baseMapper.selectById(paths[2]);
                    this.setFxj(vo, dept2);
                }
            }
        }
        return vo;
    }

    @Override
    public List<DeptDTO> buildDtoListBySysList(List<SysDept> sysDeptList) {
        if(CollectionUtils.isEmpty(sysDeptList)){
            return null;
        }

        List<DeptDTO> resultList = new ArrayList<>();
        for(SysDept entity : sysDeptList){
            DeptDTO dto = new DeptDTO();
            //部门id
            dto.setDeptId(entity.getId());
            //部门祖籍列表
            dto.setPath(entity.getRootPath());
            //部门名称
            dto.setDeptName(entity.getOrgName());
            //部门简称
            dto.setDeptJc(entity.getOrgJc());
            //部门编码
            dto.setDeptCode(entity.getOrgCode());
            //部门等级
            dto.setDeptLevel(entity.getOrgLevel());
            //所在部门业务类型代码
            dto.setDeptBizType(entity.getOrgBizType());
            resultList.add(dto);
        }
        return resultList;
    }


    // 设置分县局
    private void setFxj(DeptAllVo vo, SysDept dept) {
        if (dept != null) {
            vo.setFxjid(dept.getId());
            vo.setFxjcode(dept.getOrgCode());
            vo.setFxjname(dept.getOrgName());
        }
    }

    // 设置地市州
    private void setDsz(DeptAllVo vo, SysDept dept) {
        if (dept != null) {
            vo.setDszid(dept.getId());
            vo.setDszcode(dept.getOrgCode());
            vo.setDszname(dept.getOrgName());
        }
    }

    // 设置所属单位
    private void setDept(DeptAllVo vo, SysDept dept) {
        if (dept != null) {
            vo.setDeptid(dept.getId());
            vo.setDeptcode(dept.getOrgCode());
            vo.setDeptname(dept.getOrgName());
        }
    }

    private void getChildListByOrgcode(SysDept dept, List<String> orgcodes) {
        orgcodes.add(String.valueOf(dept.getOrgCode()));
        List<SysDept> tempList1 = this.baseMapper.selectList(
                new LambdaQueryWrapper<SysDept>()
                        .eq(SysDept::getParentId, dept.getId())
        );
        if (tempList1.size() > 0) {
            orgcodes.addAll(tempList1.stream().map(SysDept::getOrgCode).collect(Collectors.toList()));
            tempList1.forEach(item -> this.getChildListByOrgcode(item, orgcodes));
        }
    }

    private void getChildList(SysDept dept, List<String> deptIds) {
        deptIds.add(String.valueOf(dept.getId()));
        List<SysDept> tempList1 = this.baseMapper.selectList(
                new LambdaQueryWrapper<SysDept>()
                        .eq(SysDept::getParentId, dept.getId())
        );
        if (tempList1.size() > 0) {
            deptIds.addAll(tempList1.stream().map(item -> String.valueOf(item.getId())).collect(Collectors.toList()));
            tempList1.forEach(item -> this.getChildList(item, deptIds));
        }
    }

    public List<Long> getDeptUser(Long deptId) {
        List<Long> userIds = new ArrayList<>();
        List<String> childDepts = getChildDept(String.valueOf(deptId));
        System.out.println("childDepts--->" + JSONArray.toJSONString(childDepts));
        List<SysUserDept> deptUsers = sysUserDeptService.listByDeptIds(childDepts);
        System.out.println("deptUsers---->" + JSONArray.toJSONString(deptUsers));
        if (CollectionUtils.isNotEmpty(deptUsers)) {
            deptUsers.forEach(item -> {
                userIds.add(item.getUserId());
            });
        }
        return userIds;
    }

}




