package com.storlead.system.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.common.ecode.PasswordEncoder;
import com.storlead.framework.auth.vo.LoginUser;
import com.storlead.framework.common.result.Result;
import com.storlead.framework.util.LoginUserUtil;
import com.storlead.system.pojo.entity.RoleEntity;
import com.storlead.system.pojo.entity.UserRoleEntity;
import com.storlead.system.service.IRoleService;
import com.storlead.system.service.IUserRoleService;
import com.storlead.system.util.SystemConfigItemCacheUtil;
import com.storlead.system.util.SystemSettingCacheCheckUtil;
import com.storlead.user.model.UserInfo;
import com.storlead.user.model.UserQueryModel;
import com.storlead.user.pojo.dto.SetUserDetailDTO;
import com.storlead.user.pojo.dto.UserParam;
import com.storlead.user.pojo.entity.DeptEntity;
import com.storlead.user.pojo.entity.UserEntity;
import com.storlead.user.pojo.vo.SetUserDetailVo;
import com.storlead.user.pojo.vo.UserVo;
import com.storlead.user.pojo.vo.WxUserVO;
import com.storlead.user.service.IDepartService;
import com.storlead.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Resource;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * @program: sp-cloud
 * @description:
 * @author: chenkq
 * @create: 2022-05-20 12:08
 */
@Slf4j
@Api(tags = "用户: 用户管理（含公共列表/拼音/下级/直属领导查询）")
@RestController
@RequestMapping("/sys/user")
public class UserApiController {

    @Resource
    private IUserService userService;

    @Resource
    private IUserRoleService userRoleService;

    @Resource
    private IRoleService roleService;

    @Resource
    private IDepartService departService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @ApiOperation("保存员工")
    @PostMapping("save")
    public Result save(@RequestBody UserEntity user) {
        Result r = SystemSettingCacheCheckUtil.checkAddDataMode();
        if (!r.isSuccess()) {
            return r;
        }
        if (StrUtil.isBlank(user.getMobile())) {
            return Result.error("手机号不能为空!");
        }
        if(Objects.isNull(user.getId())) {
            String defaultPassWord = SystemConfigItemCacheUtil.getDefaultPassWord();
            user.setDataSource(1);
            user.setPassword(passwordEncoder.encode(defaultPassWord));
        }
        UserEntity oUser = userService.getOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getMobile,user.getMobile()).eq(UserEntity::getIsDelete,0).last("limit 1"));
        if (Objects.nonNull(oUser)) {
            if (!oUser.getId().equals(user.getId())) {
                return Result.error("手机'"+user.getMobile()+"'号已被占用!");
            }
        }

        if (Objects.nonNull(user.getDeptId())) {
            DeptEntity dept = departService.getById(user.getDeptId());
            if (Objects.nonNull(dept)) {
                user.setOrgRouteCode(dept.getRouteCode());
                user.setSubCompanyId(dept.getSubCompanyId());
                user.setCompanyId(dept.getCompanyId());
                user.setSubCompanyId(dept.getSubCompanyId());
            }
        }
        if (Objects.nonNull(user.getManagerId())) {
            UserEntity u = userService.getById(user.getManagerId());
            if (Objects.nonNull(u)) {
                user.setManagers(u.getManagers()+","+user.getManagerId().toString());
            } else {
                user.setManagers(user.getManagerId().toString());
            }
        }
        userService.saveOrUpdate(user);
        return Result.ok();
    }

    @ApiOperation("根据部门id查询用户")
    @PostMapping("listByDeptId")
    public Result listByDeptId(Long deptId) {

        List<UserEntity> list = userService.list(
                new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getDeptId,deptId)
                        .ne(UserEntity::getStatus,Integer.valueOf(5))
                        .eq(UserEntity::getIsDelete,0));
        return Result.result(list);
    }

    @ApiOperation("分页查询用户")
    @PostMapping("pageUserlist")
    public Result pageUserlist(@RequestBody UserParam param) {
        IPage<UserVo> page = new Page<>(param.getPageIndex(),param.getPageSize());
        LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<UserEntity>(new UserEntity());
        queryWrapper.eq(UserEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        if (StrUtil.isNotBlank(param.getBlurry())) {
            queryWrapper.like(UserEntity::getUserName,param.getBlurry()).or().like(UserEntity::getRealName,param.getBlurry());
        }
        if (StrUtil.isNotBlank(param.getOrgRouteCode())) {
            queryWrapper.likeRight(UserEntity::getOrgRouteCode,param.getOrgRouteCode());
        }
//        if (Objects.isNull(param.getStatus())) {
//            queryWrapper.ne(UserEntity::getStatus,Integer.valueOf(5));
//        } else {
//            queryWrapper.ne(UserEntity::getStatus,param.getStatus());
//        }
        if (!param.getIsIncludeResign()) {
            queryWrapper.ne(UserEntity::getStatus,Integer.valueOf(5));
        }
        queryWrapper.orderByDesc(UserEntity::getEmail);
        List<UserVo> us  = userService.listWithScopeVo(page,queryWrapper,param);
        if (CollectionUtil.isNotEmpty(us)) {
            List<Long> userIds = us.stream().map(UserVo::getId).collect(Collectors.toList());
            List<UserRoleEntity> userRolels = userRoleService.selectUserRole(new LambdaQueryWrapper<UserRoleEntity>().in(UserRoleEntity::getUserId,userIds));
            if (CollectionUtil.isNotEmpty(userRolels)) {
                List<RoleEntity> rs = roleService.list(new LambdaQueryWrapper<RoleEntity>().in(RoleEntity::getId,userRolels.stream().map(UserRoleEntity::getRoleId).collect(Collectors.toList())));
                us.forEach(u -> {
                    List<RoleEntity> roles = rs.stream().filter(r -> userRolels.stream().anyMatch(ur -> ur.getRoleId().equals(r.getId()) && ur.getUserId().equals(u.getId()))).collect(Collectors.toList());
                    if(CollectionUtil.isNotEmpty(roles)) {
                        u.setRoleNames(roles.stream().map(RoleEntity::getName).collect(Collectors.toList()));
                        u.setRoleIds(roles.stream().map(RoleEntity::getId).collect(Collectors.toList()));
                    }
                });
            }

            us.forEach(e -> {
                e.setIdNum("");
                e.setPassword("");
                e.setBankCardNum("");
                e.setBankName("");
                e.setEducation("");
                e.setAddress("");
                e.setBirthday(null);
                e.setEmail("");
            });
        }
        page.setRecords(us);
        return Result.result(page);
    }


    @ApiOperation("分页查询用户")
    @PostMapping("pagelist")
    public Result pagelist(@RequestBody UserParam param) {

//        param.setCommonQueryOrderBy("UserEntity");

        IPage<UserVo> page = new Page<>(param.getPageIndex(),param.getPageSize());
        LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<UserEntity>(new UserEntity());
        queryWrapper.eq(UserEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        if (StrUtil.isNotBlank(param.getBlurry())) {
            queryWrapper.like(UserEntity::getUserName,param.getBlurry()).or().like(UserEntity::getRealName,param.getBlurry());
        }


        LambdaQueryWrapper<DeptEntity> dlp = new LambdaQueryWrapper<>();
        dlp.eq(DeptEntity::getEnabled,1);
        dlp.eq(DeptEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
        List<DeptEntity> deptEntities = departService.list(dlp);
        if (CollectionUtil.isNotEmpty(deptEntities)) {
            List<Long> deptIds = deptEntities.stream().map(DeptEntity::getId).collect(Collectors.toList());
            queryWrapper.in(UserEntity::getDeptId,deptIds);
        }
        if (StrUtil.isNotBlank(param.getOrgRouteCode())) {
            queryWrapper.likeRight(UserEntity::getOrgRouteCode,param.getOrgRouteCode());
        }
//        if (Objects.isNull(param.getStatus())) {
//            queryWrapper.ne(UserEntity::getStatus,Integer.valueOf(5));
//        } else {
//            queryWrapper.ne(UserEntity::getStatus,param.getStatus());
//        }
        if (!param.getIsIncludeResign()) {
            // 在职
            queryWrapper.ne(UserEntity::getStatus,Integer.valueOf(5));
            queryWrapper.eq(UserEntity::getEnabled,1);
        } else {
            queryWrapper.and(wrapper ->
                    wrapper.eq(UserEntity::getStatus, 5) // 离职
                            .or(w -> w.ne(UserEntity::getStatus, 5) // 在职
                                    .eq(UserEntity::getEnabled, 1)) // 并且启用
            );
        }
        queryWrapper.orderByDesc(UserEntity::getEmail);
        List<UserVo> us  = userService.listWithScopeVo(page,queryWrapper,param);
        if (CollectionUtil.isNotEmpty(us)) {
            List<Long> userIds = us.stream().map(UserVo::getId).collect(Collectors.toList());
            List<UserRoleEntity> userRolels = userRoleService.selectUserRole(new LambdaQueryWrapper<UserRoleEntity>().in(UserRoleEntity::getUserId,userIds));
            if (CollectionUtil.isNotEmpty(userRolels)) {
                List<RoleEntity> rs = roleService.list(new LambdaQueryWrapper<RoleEntity>().in(RoleEntity::getId,userRolels.stream().map(UserRoleEntity::getRoleId).collect(Collectors.toList())));
                us.forEach(u -> {
                    List<RoleEntity> roles = rs.stream().filter(r -> userRolels.stream().anyMatch(ur -> ur.getRoleId().equals(r.getId()) && ur.getUserId().equals(u.getId()))).collect(Collectors.toList());
                    if(CollectionUtil.isNotEmpty(roles)) {
                        u.setRoleNames(roles.stream().map(RoleEntity::getName).collect(Collectors.toList()));
                        u.setRoleIds(roles.stream().map(RoleEntity::getId).collect(Collectors.toList()));
                    }
                });
            }

            us.forEach(e -> {
                e.setIdNum("");
                e.setPassword("");
                e.setBankCardNum("");
                e.setBankName("");
                e.setEducation("");
                e.setAddress("");
                e.setBirthday(null);
                e.setEmail("");
            });
        }
        page.setRecords(us);
        return Result.result(page);
    }

    @ApiOperation("分页查询用户")
    @PostMapping("pageScopelist")
    public Result pageScopelist(@RequestBody UserParam param) {

        IPage<UserVo> page = new Page<>(param.getPageIndex(),param.getPageSize());
        LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<UserEntity>(new UserEntity());
        queryWrapper.eq(UserEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        if (StrUtil.isNotBlank(param.getBlurry())) {
            queryWrapper.like(UserEntity::getUserName,param.getBlurry()).or().like(UserEntity::getRealName,param.getBlurry());
        }
        if (StrUtil.isNotBlank(param.getOrgRouteCode())) {
            queryWrapper.likeRight(UserEntity::getOrgRouteCode,param.getOrgRouteCode());
        }
        if (!param.getIsIncludeResign()) {
            queryWrapper.ne(UserEntity::getStatus,Integer.valueOf(5));
        }
        queryWrapper.orderByDesc(UserEntity::getEmail);
        List<UserVo> us  = userService.listWithScopeVo(page,queryWrapper,param);
        if (CollectionUtil.isNotEmpty(us)) {
            List<Long> userIds = us.stream().map(UserVo::getId).collect(Collectors.toList());
            List<UserRoleEntity> userRolels = userRoleService.selectUserRole(new LambdaQueryWrapper<UserRoleEntity>().in(UserRoleEntity::getUserId,userIds));
            if (CollectionUtil.isNotEmpty(userRolels)) {
                List<RoleEntity> rs = roleService.list(new LambdaQueryWrapper<RoleEntity>().in(RoleEntity::getId,userRolels.stream().map(UserRoleEntity::getRoleId).collect(Collectors.toList())));
                us.forEach(u -> {
                    List<RoleEntity> roles = rs.stream().filter(r -> userRolels.stream().anyMatch(ur -> ur.getRoleId().equals(r.getId()) && ur.getUserId().equals(u.getId()))).collect(Collectors.toList());
                    if(CollectionUtil.isNotEmpty(roles)) {
                        u.setRoleNames(roles.stream().map(RoleEntity::getName).collect(Collectors.toList()));
                        u.setRoleIds(roles.stream().map(RoleEntity::getId).collect(Collectors.toList()));
                    }
                });
            }

            us.forEach(e -> {
                e.setIdNum("");
                e.setPassword("");
                e.setBankCardNum("");
                e.setBankName("");
                e.setEducation("");
                e.setAddress("");
                e.setBirthday(null);
                e.setEmail("");
            });
        }
        page.setRecords(us);
        return Result.result(page);
    }

    @ApiOperation("删除人员数据")
    @PostMapping("delete")
    public Result delete(Long [] ids) {
        if (ids == null || ids.length == 0) {
            return Result.error("参数错误");
        }
        LambdaUpdateWrapper<UserEntity> update = new LambdaUpdateWrapper();
        update.in(UserEntity::getId,Arrays.asList(ids));
        update.set(UserEntity::getIsDelete,1);
        userService.update(update);
        return Result.ok();
    }


    @ApiOperation("标记冻结")
    @PostMapping("markFreeze")
    public Result markFreeze(Long [] ids,Integer isFreeze) {
        if (ids == null || ids.length == 0) {
            return Result.error("参数错误");
        }
        LambdaUpdateWrapper<UserEntity> update = new LambdaUpdateWrapper();
        update.in(UserEntity::getId,Arrays.asList(ids));
        update.set(UserEntity::getIsFreeze,isFreeze);
        userService.update(update);
        if(Integer.valueOf(0).equals(isFreeze)) {
            userService.updateLastFollowUpTime(Arrays.asList(ids));
        }
        return Result.ok();
    }


    @ApiOperation("删除人员数据")
    @PostMapping("deleteById")
    public Result deleteById(Long id) {
        if (id == null) {
            return Result.error("参数错误");
        }
        LambdaUpdateWrapper<UserEntity> update = new LambdaUpdateWrapper();
        update.eq(UserEntity::getId,id);
        update.set(UserEntity::getIsDelete,1);
        userService.update(update);
        return Result.ok();
    }

    @ApiOperation("修改真是姓名")
    @PostMapping("updateRealName")
    public Result deleteById(Long id,String realName) {
        if (id == null) {
            return Result.error("参数错误");
        }
        LambdaUpdateWrapper<UserEntity> update = new LambdaUpdateWrapper();
        update.eq(UserEntity::getId,id);
        update.set(UserEntity::getRealName,realName);
        userService.update(update);
        return Result.ok();
    }


    @ApiOperation("启用禁用员工")
    @PostMapping("enable")
    public Result setEnable(Long [] ids,Boolean enable) {
        if (ids == null || ids.length == 0) {
            return Result.error("参数错误");
        }
        LambdaUpdateWrapper<UserEntity> update = new LambdaUpdateWrapper();
        update.in(UserEntity::getId,Arrays.asList(ids));
        update.set(UserEntity::getEnabled,enable);
        Boolean re =  userService.update(update);
        if (re) {
            return Result.ok();
        } else {
            return Result.error("操作失败");
        }
    }


    @ApiOperation("根据ids查询用户")
    @PostMapping("queryByIds")
    public Result queryByIds(Long [] ids) {
        if (ids == null || ids.length == 0) {
            return Result.error("参数错误");
        }
        LambdaUpdateWrapper<UserEntity> query = new LambdaUpdateWrapper();
        query.in(UserEntity::getId,Arrays.asList(ids));
        List<UserEntity> list  =  userService.list(query);
        return Result.result(list);
    }


    @ApiOperation("同步OA数据")
    @PostMapping("syncOa")
    public Result syncOa() {
       userService.syncOa();
       return Result.ok();
    }

    @ApiOperation("重置密码")
    @PostMapping("resetPassword")
    public Result resetPassword(Long userId) {
        if  (Objects.isNull(userId)) {
            return Result.error("参数错误");
        }
        String defaultPassWord = SystemConfigItemCacheUtil.getDefaultPassWord();
        LambdaUpdateWrapper<UserEntity> update = new LambdaUpdateWrapper<UserEntity>();
        update.eq(UserEntity::getId,userId);
        update.set(UserEntity::getPassword,passwordEncoder.encode(defaultPassWord));
        userService.update(update);
        return Result.ok();
    }

    @ApiOperation("修改用户信息")
    @PostMapping("updateUserInfo")
    public Result setPhone(SetUserDetailDTO dto) {
        Long userId = LoginUserUtil.getCurrentUserId();
        if  (Objects.isNull(userId)) {
            return Result.error("您未登录");
        }
        if  (StrUtil.isBlank(dto.getAvatar())) {
            return Result.error("参数错误,头像url不能为空");
        }
        if  (StrUtil.isBlank(dto.getMobile())) {
            return Result.error("参数错误,手机号不能为空");
        }
        UserEntity entity = userService.getById(userId);
        if (Objects.isNull(entity)) {
            return Result.error("未找到当前用户,请重新登录");
        }
        UserEntity oUser = userService.getOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getMobile,dto.getMobile()).eq(UserEntity::getIsDelete,0).last("limit 1"));
        if (Objects.nonNull(oUser)) {
            if (!oUser.getId().equals(userId)) {
                return Result.error("该手机'"+dto.getMobile()+"'号已被占用!");
            }
        }
        if  (StrUtil.isNotBlank(dto.getEmail())) {
            oUser = userService.getOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getMobile,dto.getEmail()).eq(UserEntity::getIsDelete,0).last("limit 1"));
            if (Objects.nonNull(oUser)) {
                if (!oUser.getId().equals(userId)) {
                    return Result.error("该邮箱'"+dto.getEmail()+"'已被占用!");
                }
            }
        }
        LambdaUpdateWrapper<UserEntity> update = new LambdaUpdateWrapper<>();
        update.eq(UserEntity::getId, userId);

        update.set(UserEntity::getAvatar, dto.getAvatar())
              .set(UserEntity::getEmail, dto.getEmail())
              .set(UserEntity::getNickName, dto.getNickName())
              .set(UserEntity::getRealName, dto.getRealName())
              .set(UserEntity::getMobile, dto.getMobile())
              .set(UserEntity::getSex, dto.getSex())
              .set(UserEntity::getBirthday, dto.getBirthday());

        if (StrUtil.isNotBlank(dto.getJobDes())) {
            update.set(UserEntity::getJobDes, dto.getJobDes());
        }

        try {
            boolean result = userService.update(update);
            if (!result) {
                return Result.error("更新用户信息失败，请重试。");
            }
        } catch (Exception e) {
            log.error("更新用户信息发生错误: {}", e.getMessage());
            return Result.error("系统错误，更新用户信息失败。");
        }

        if (StrUtil.isNotBlank(dto.getDeptJobDes()) && Objects.nonNull(entity.getDeptId())) {
            DeptEntity dept = departService.getById(entity.getDeptId());
            if (!dto.getDeptJobDes().equals(dept.getDeptJobDes())) {
                if (Integer.valueOf(0).equals(entity.getIsLeader())) {
                    return Result.error("只有领导才能设置部门职责");
                }
                LambdaUpdateWrapper<DeptEntity> dUpdate = new LambdaUpdateWrapper<DeptEntity>();
                dUpdate.eq(DeptEntity::getId,entity.getDeptId());
                dUpdate.set(DeptEntity::getDeptJobDes,dto.getDeptJobDes());
                departService.update(dUpdate);
            }
        }
        return Result.ok();
    }

    @ApiOperation("获取用户基础信息")
    @PostMapping("getSimpleUserInfo")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = SetUserDetailVo.class)
    })
    public Result getSimpleUserInfo() {
        Long userId = LoginUserUtil.getCurrentUserId();
        if  (Objects.isNull(userId)) {
            return Result.error("您未登录");
        }
        UserVo entity = userService.getUserInfoById(userId);

        SetUserDetailVo detailVo = new SetUserDetailVo();
        detailVo.setDeptId(entity.getDeptId());
        detailVo.setId(entity.getId());
        detailVo.setDeptName(entity.getDeptName());
        detailVo.setAvatar(entity.getAvatar());
        detailVo.setJobId(entity.getJobId());
        detailVo.setJobName(entity.getJobName());
        detailVo.setEmail(entity.getEmail());
        detailVo.setMobile(entity.getMobile());
        detailVo.setUserName(entity.getRealName());
        detailVo.setJobDes(entity.getJobDes());
        detailVo.setIsLeader(entity.getIsLeader());
        DeptEntity dept = departService.getById(entity.getDeptId());
        if (Objects.nonNull(dept)) {
            detailVo.setDeptJobDes(dept.getDeptJobDes());
        }
        return Result.result(detailVo);
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiOperation(value = "公共接口-用户信息-列表", notes = "公共接口-用户信息-列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = UserInfo.class)
    })
    public Result<List<UserInfo>> queryTreeList(UserQueryModel userQueryModel) {
        Result<List<UserInfo>> result = new Result<>();
        try {
            List<UserInfo> list = userService.getUserListBySearch(userQueryModel);
            result.setResult(list);
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    @RequestMapping(value = "/user-list-pinyin", method = RequestMethod.GET)
    @ApiOperation(value = "公共接口-用户信息-列表（按拼音首字母排序）", notes = "公共接口-用户信息-列表（按拼音首字母排序）")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = UserInfo.class)
    })
    public Result<List<WxUserVO>> userListPinyin(UserQueryModel userQueryModel) {
        Result<List<WxUserVO>> result = new Result<>();
        try {
            List<WxUserVO> wxUserInfoList = userService.getPingyinUserList(userQueryModel);
            result.setResult(wxUserInfoList);
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    @RequestMapping(value = "/list-subordinate", method = RequestMethod.GET)
    @ApiOperation(value = "公共接口-下级用户信息-列表", notes = "公共接口-下级用户信息-列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = UserInfo.class)
    })
    public Result<List<UserInfo>> listSubordinate(UserQueryModel userQueryModel) {
        Result<List<UserInfo>> result = new Result<>();
        try {
            LoginUser loginUser = LoginUserUtil.getLoginUser();
            List<UserInfo> list = userService.getUserListBySearch(userQueryModel);
            List<Long> allSubordinate = userService.getAllSubordinate(loginUser.getId());
            Set<Long> allSubordinateSet = new HashSet<>(allSubordinate);
            list = list.stream().filter((u) -> allSubordinateSet.contains(u.getId())).collect(Collectors.toList());
            result.setResult(list);
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    @GetMapping(value = "/findManager")
    @ApiOperation(value = "公共接口-用户信息-查看当前用户领导", notes = "公共接口-用户信息-查看当前用户领导")
    public Result<UserEntity> findManager() {
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        UserEntity user = userService.getById(loginUser.getManagerId());
        return Result.result(user);
    }

    public void updateManagerId(UserEntity user,Long oldManagerId){
        if (Objects.isNull(user)) {
            return;
        }
        if (Objects.isNull(user.getManagerId())) {
            return;
        }
        List<UserEntity> userEntities = userService.list(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getManagerId,user.getId()));
        for (UserEntity userEntity : userEntities) {
            if (StrUtil.isNotBlank(userEntity.getManagers())) {
                String routeCodeStr = ","+userEntity.getManagers()+",";
                routeCodeStr = routeCodeStr.replace(","+oldManagerId+",",","+userEntity.getManagerId()+",");
                StringUtils.startsWithIgnoreCase(routeCodeStr,",");
                StringUtils.endsWithIgnoreCase(routeCodeStr,",");

                LambdaUpdateWrapper<UserEntity> updateWrapper = new LambdaUpdateWrapper();
                updateWrapper.eq(UserEntity::getId,userEntity.getId());
                updateWrapper.set(UserEntity::getManagers,routeCodeStr);
                userService.update(updateWrapper);
            }
        }

    }



}
