package com.lideeyunji.service.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.annotations.VisibleForTesting;
import com.lideeyunji.service.infra.api.IApiFileApi;
import com.lideeyunji.service.system.controller.vo.user.profile.UserProfileUpdatePasswordReqVO;
import com.lideeyunji.service.system.controller.vo.user.profile.UserProfileUpdateReqVO;
import com.lideeyunji.service.system.controller.vo.user.user.*;
import com.lideeyunji.service.system.entity.*;
import com.lideeyunji.service.system.controller.vo.user.user.*;
import com.lideeyunji.service.system.entity.*;
import com.lideeyunji.service.system.enums.RoleCodeEnum;
import com.lideeyunji.service.system.mapper.*;
import com.lideeyunji.service.system.service.*;
import com.lideeyunji.tool.framework.common.enums.CommonStatusEnum;
import com.lideeyunji.tool.framework.common.exception.ServiceException;
import com.lideeyunji.tool.framework.common.pojo.PageResult;
import com.lideeyunji.tool.framework.common.util.collection.CollectionUtils;
import com.lideeyunji.tool.framework.common.util.object.BeanUtils;
import com.lideeyunji.tool.framework.permission.core.util.DataPermissionUtils;
import com.lideeyunji.service.system.mapper.*;
import com.lideeyunji.service.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.lideeyunji.service.system.constant.ErrorCodeConstants.*;
import static com.lideeyunji.tool.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.lideeyunji.tool.framework.common.util.collection.CollectionUtils.convertList;
import static com.lideeyunji.tool.framework.common.util.collection.CollectionUtils.convertSet;

/**
 * 后台用户 Service 实现类
 *
 * @author 金灯剑客
 */
@Service("adminUserService")
@Slf4j
public class AdminUserServiceImpl implements IAdminUserService {

    @Value("${sys.user.init-password:123456}")
    private String userInitPassword;

    @Resource
    private AdminUserMapper userMapper;

    @Resource
    private IDeptService deptService;
    @Resource
    private IPostService postService;
    @Resource
    private IRoleService roleService;
    @Resource
    private IDutyService dutyService;
    @Resource
    private IPositionService positionService;
    @Resource
    private IRankService rankService;

    @Resource
    private IPermissionService permissionService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    @Lazy // 延迟，避免循环依赖报错
    private ITenantService tenantService;

    @Resource
    private UserDeptMapper userDeptMapper;

    @Resource
    private UserPostMapper userPostMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private UserDutyMapper userDutyMapper;

    @Resource
    private UserPositionMapper userPositionMapper;

    @Resource
    private UserRankMapper userRankMapper;

    @Resource
    private IApiFileApi apiFileApi;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createUser(UserSaveReqVO vo) {
        // 校验账户配合
        tenantService.handleTenantInfo(tenant -> {
            long count = userMapper.selectCount();
            if (count >= tenant.getAccountCount()) {
                throw exception(USER_COUNT_MAX, tenant.getAccountCount());
            }
        });
        // 校验正确性
        validateUserForCreateOrUpdate(null, vo.getUsername(), vo.getMobile(), vo.getEmail());

        //部门列表

        Set<Long> deptIdSet = Optional.ofNullable(vo.getDeptInfoList())
                .orElse(Collections.emptyList())
                .stream()
                .map(UserSaveReqVO.DeptInfo::getDeptId)
                .collect(Collectors.toSet());
        // 插入用户
        AdminUserDO user = BeanUtils.toBean(vo, AdminUserDO.class);
        user.setStatus(CommonStatusEnum.ENABLE.getStatus()); // 默认开启
        user.setPassword(encodePassword(vo.getPassword())); // 加密密码
        user.setDeptId(StrUtil.join(",",deptIdSet));//部门列表
        user.setTenantId(vo.getTenantId());//租户id
        userMapper.insert(user);
        // 插入关联-岗位，角色
        Long userId = user.getId();
        //更新部门
        handleUserDept(userId,vo);
        // 更新岗位
        handleUserPost(userId,vo);
        //更新角色
        handleUserRole(userId,vo);
        //更新职务
        handleUserDuty(userId,vo);
        //更新职位
        handleUserPosition(userId,vo);
        //更新职级别
        handleUserRank(userId,vo);

        return user.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(UserSaveReqVO updateReqVO) {
        updateReqVO.setPassword(null); // 特殊：此处不更新密码
        // 校验正确性
        validateUserForCreateOrUpdate(updateReqVO.getId(), updateReqVO.getUsername(), updateReqVO.getMobile(), updateReqVO.getEmail());

        Set<Long> deptIdSet = Optional.ofNullable(updateReqVO.getDeptInfoList())
                .orElse(Collections.emptyList())
                .stream()
                .map(UserSaveReqVO.DeptInfo::getDeptId)
                .collect(Collectors.toSet());

        // 更新用户
        AdminUserDO updateObj = BeanUtils.toBean(updateReqVO, AdminUserDO.class);
        updateObj.setDeptId(StrUtil.join(",",deptIdSet));
        userMapper.updateById(updateObj);
        Long userId = updateReqVO.getId();
        //租户管理员
        boolean supAdminFlag = this.isSupAdmin(userId);//是否是超级管理员
        boolean tenantAdminFlag = this.isTenantAdmin(userId);//是否是租户管理员
        if(supAdminFlag || tenantAdminFlag){
            return;
        }

        //更新部门
        handleUserDept(userId,updateReqVO);
        // 更新岗位
        handleUserPost(userId,updateReqVO);
        //更新角色
        handleUserRole(userId,updateReqVO);
        //更新职务
        handleUserDuty(userId,updateReqVO);
        //更新职位
        handleUserPosition(userId,updateReqVO);
        //更新职级别
        handleUserRank(userId,updateReqVO);

    }
    private void handleUserDept(Long userId,UserSaveReqVO reqVO) {
        //先清掉再加
        userDeptMapper.deleteByUserId(userId);

        List<UserSaveReqVO.DeptInfo> deptInfoList = reqVO.getDeptInfoList();
        if (CollectionUtil.isEmpty(deptInfoList)) {
            return;
        }
        userDeptMapper.insertBatch(convertList(deptInfoList,
                deptInfo -> new UserDeptDO().setUserId(userId).setDeptId(deptInfo.getDeptId())));
    }

    private void handleUserPost(Long userId,UserSaveReqVO reqVO) {
        //先清掉再加
        userPostMapper.deleteByUserId(userId);

        List<UserSaveReqVO.DeptInfo> deptInfoList = reqVO.getDeptInfoList();
        if (CollectionUtil.isEmpty(deptInfoList)) {
            return;
        }
        //处理岗位
        for (UserSaveReqVO.DeptInfo deptInfo : deptInfoList) {
            Long deptId = deptInfo.getDeptId();
            Set<Long> postIds = deptInfo.getPostIds();
            if(CollectionUtil.isEmpty(postIds)){
                continue;
            }
            userPostMapper.insertBatch(convertList(postIds,
                    postId -> new UserPostDO().setUserId(userId).setDeptId(deptId).setPostId(postId)));
        }
    }


    //更新用户角色
    private void handleUserRole(Long userId,UserSaveReqVO reqVO){
        //先清掉再加
        userRoleMapper.deleteListByUserId(userId);

        List<UserSaveReqVO.DeptInfo> deptInfoList = reqVO.getDeptInfoList();
        if (CollectionUtil.isEmpty(deptInfoList)) {
            return;
        }
        //处理角色
        for (UserSaveReqVO.DeptInfo deptInfo : deptInfoList) {
            Long deptId = deptInfo.getDeptId();
            Set<Long> roleIds = deptInfo.getRoleIds();
            if(CollectionUtil.isEmpty(roleIds)){
                continue;
            }
            userRoleMapper.insertBatch(convertList(roleIds,
                    roleId -> new UserRoleDO().setUserId(userId).setDeptId(deptId).setRoleId(roleId)));
        }
    }

    //更新用户职务
    private void handleUserDuty(Long userId,UserSaveReqVO reqVO){
        //先清掉再加
        userDutyMapper.deleteByUserId(userId);

        List<UserSaveReqVO.DeptInfo> deptInfoList = reqVO.getDeptInfoList();
        if (CollectionUtil.isEmpty(deptInfoList)) {
            return;
        }

        for (UserSaveReqVO.DeptInfo deptInfo : deptInfoList) {
            Long deptId = deptInfo.getDeptId();
            Set<Long> dutyIds = deptInfo.getDutyIds();
            if(CollectionUtil.isEmpty(dutyIds)){
                continue;
            }
            userDutyMapper.insertBatch(convertList(dutyIds,
                    dutyId -> new UserDutyDO().setUserId(userId).setDeptId(deptId).setDutyId(dutyId)));
        }
    }

    //更新用户职位
    private void handleUserPosition(Long userId,UserSaveReqVO reqVO) {
        //先清掉再加
        userPositionMapper.deleteByUserId(userId);

        List<UserSaveReqVO.DeptInfo> deptInfoList = reqVO.getDeptInfoList();
        if (CollectionUtil.isEmpty(deptInfoList)) {
            return;
        }

        for (UserSaveReqVO.DeptInfo deptInfo : deptInfoList) {
            Long deptId = deptInfo.getDeptId();
            Set<Long> positionIds = deptInfo.getPositionIds();
            if(CollectionUtil.isEmpty(positionIds)){
                continue;
            }
            userPositionMapper.insertBatch(convertList(positionIds,
                    positionId -> new UserPositionDO().setUserId(userId).setDeptId(deptId).setPositionId(positionId)));
        }
    }

    //更新用户职位
    private void handleUserRank(Long userId,UserSaveReqVO reqVO) {
        //先清掉再加
        userRankMapper.deleteByUserId(userId);

        Set<Long> rankIds = reqVO.getRankIds();
        if (CollectionUtil.isEmpty(rankIds)) {
            return;
        }
        userRankMapper.insertBatch(convertList(rankIds,
                rankId -> new UserRankDO().setUserId(userId).setRankId(rankId)));
    }


    @Override
    public void updateUserLogin(Long id, String loginIp,Long loginDeptId,Long loginRoleId) {
        userMapper.updateById(new AdminUserDO().setId(id).setLoginIp(loginIp).setLoginDeptId(loginDeptId).setLoginRoleId(loginRoleId).setLoginDate(LocalDateTime.now()));
    }

    @Override
    public void updateUserProfile(Long id, UserProfileUpdateReqVO reqVO) {
        // 校验正确性
        validateUserExists(id);
        validateEmailUnique(id, reqVO.getEmail());
        validateMobileUnique(id, reqVO.getMobile());
        // 执行更新
        userMapper.updateById(BeanUtils.toBean(reqVO, AdminUserDO.class).setId(id));
    }

    @Override
    public void updateUserPassword(Long id, UserProfileUpdatePasswordReqVO reqVO) {
        // 校验旧密码密码
        validateOldPassword(id, reqVO.getOldPassword());
        // 执行更新
        AdminUserDO updateObj = new AdminUserDO().setId(id);
        updateObj.setPassword(encodePassword(reqVO.getNewPassword())); // 加密密码
        userMapper.updateById(updateObj);
    }

    @Override
    public String updateUserAvatar(Long id, InputStream avatarFile) {
        validateUserExists(id);
        // 存储文件
        String avatar = apiFileApi.createFile(IoUtil.readBytes(avatarFile));
        // 更新路径
        AdminUserDO sysUserDO = new AdminUserDO();
        sysUserDO.setId(id);
        sysUserDO.setAvatar(avatar);
        userMapper.updateById(sysUserDO);
        return avatar;
    }

    @Override
    public void updateUserPassword(Long id, String password) {
        // 校验用户存在
        validateUserExists(id);
        // 更新密码
        AdminUserDO updateObj = new AdminUserDO();
        updateObj.setId(id);
        updateObj.setPassword(encodePassword(password)); // 加密密码
        userMapper.updateById(updateObj);
    }

    @Override
    public void updateUserStatus(Long id, Integer status) {
        // 校验用户存在
        validateUserExists(id);
        // 更新状态
        AdminUserDO updateObj = new AdminUserDO();
        updateObj.setId(id);
        updateObj.setStatus(status);
        userMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(Long id) {
        // 校验用户存在
        validateUserExists(id);
        // 删除用户
        userMapper.deleteById(id);
        // 删除用户关联数据
        permissionService.processUserDeleted(id);
        // 删除用户岗位
        userPostMapper.deleteByUserId(id);
        // 删除用户职务
        userDutyMapper.deleteByUserId(id);
        // 删除用户职位
        userPositionMapper.deleteByUserId(id);
        // 删除用户职级
        userRankMapper.deleteByUserId(id);

    }

    @Override
    public AdminUserDO getUserByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public AdminUserDO getUserByMobile(String mobile) {
        return userMapper.selectByMobile(mobile);
    }

    @Override
    public AdminUserDO getUserByEmail(String email) {
        return userMapper.selectByEmail(email);
    }


    @Override
    public PageResult<AdminUserDO> getUserPage(UserPageReqVO reqVO) {
        return userMapper.selectPage(reqVO, getDeptCondition(reqVO.getDeptId()));
    }

    @Override
    public AdminUserDO getUser(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public List<AdminUserDO> getUserListByDeptIds(Collection<Long> deptIds) {
        if (CollUtil.isEmpty(deptIds)) {
            return Collections.emptyList();
        }
        return userMapper.selectListByDeptIds(deptIds);
    }

    @Override
    public List<AdminUserDO> getUserListByPostIds(Collection<Long> postIds) {
        if (CollUtil.isEmpty(postIds)) {
            return Collections.emptyList();
        }
        Set<Long> userIds = convertSet(userPostMapper.selectListByPostIds(postIds), UserPostDO::getUserId);
        if (CollUtil.isEmpty(userIds)) {
            return Collections.emptyList();
        }
        return userMapper.selectBatchIds(userIds);
    }

    @Override
    public List<AdminUserDO> getUserList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        return userMapper.selectBatchIds(ids);
    }

    @Override
    public void validateUserList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return;
        }
        // 获得岗位信息
        List<AdminUserDO> users = userMapper.selectBatchIds(ids);
        Map<Long, AdminUserDO> userMap = CollectionUtils.convertMap(users, AdminUserDO::getId);
        // 校验
        ids.forEach(id -> {
            AdminUserDO user = userMap.get(id);
            if (user == null) {
                throw exception(USER_NOT_EXISTS);
            }
            if (!CommonStatusEnum.ENABLE.getStatus().equals(user.getStatus())) {
                throw exception(USER_IS_DISABLE, user.getNickname());
            }
        });
    }

    @Override
    public List<AdminUserDO> getUserListByNickname(String nickname) {
        return userMapper.selectListByNickname(nickname);
    }

    /**
     * 获得部门条件：查询指定部门的子部门编号们，包括自身
     *
     * @param deptId 部门编号
     * @return 部门编号集合
     */
    private Set<Long> getDeptCondition(Long deptId) {
        if (deptId == null) {
            return Collections.emptySet();
        }
        Set<Long> deptIds = convertSet(deptService.getChildDeptList(deptId), DeptDO::getId);
        deptIds.add(deptId); // 包括自身
        return deptIds;
    }

    private void validateUserForCreateOrUpdate(Long id, String username, String mobile, String email) {
        // 关闭数据权限，避免因为没有数据权限，查询不到数据，进而导致唯一校验不正确
        DataPermissionUtils.executeIgnore(() -> {
            // 校验用户存在
            validateUserExists(id);
            // 校验用户名唯一
            validateUsernameUnique(id, username);
            // 校验手机号唯一
            validateMobileUnique(id, mobile);
            // 校验邮箱唯一
            validateEmailUnique(id, email);
        });
    }

    @VisibleForTesting
    void validateUserExists(Long id) {
        if (id == null) {
            return;
        }
        AdminUserDO user = userMapper.selectById(id);
        if (user == null) {
            throw exception(USER_NOT_EXISTS);
        }
    }

    @VisibleForTesting
    void validateUsernameUnique(Long id, String username) {
        if (StrUtil.isBlank(username)) {
            return;
        }
        AdminUserDO user = userMapper.selectByUsername(username);
        if (user == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的用户
        if (id == null) {
            throw exception(USER_USERNAME_EXISTS);
        }
        if (!user.getId().equals(id)) {
            throw exception(USER_USERNAME_EXISTS);
        }
    }

    @VisibleForTesting
    void validateEmailUnique(Long id, String email) {
        if (StrUtil.isBlank(email)) {
            return;
        }
        AdminUserDO user = userMapper.selectByEmail(email);
        if (user == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的用户
        if (id == null) {
            throw exception(USER_EMAIL_EXISTS);
        }
        if (!user.getId().equals(id)) {
            throw exception(USER_EMAIL_EXISTS);
        }
    }

    @VisibleForTesting
    void validateMobileUnique(Long id, String mobile) {
        if (StrUtil.isBlank(mobile)) {
            return;
        }
        AdminUserDO user = userMapper.selectByMobile(mobile);
        if (user == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的用户
        if (id == null) {
            throw exception(USER_MOBILE_EXISTS);
        }
        if (!user.getId().equals(id)) {
            throw exception(USER_MOBILE_EXISTS);
        }
    }

    /**
     * 校验旧密码
     *
     * @param id          用户 id
     * @param oldPassword 旧密码
     */
    @VisibleForTesting
    void validateOldPassword(Long id, String oldPassword) {
        AdminUserDO user = userMapper.selectById(id);
        if (user == null) {
            throw exception(USER_NOT_EXISTS);
        }
        if (!isPasswordMatch(oldPassword, user.getPassword())) {
            throw exception(USER_PASSWORD_FAILED);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 添加事务，异常则回滚所有导入
    public UserImportRespVO importUserList(List<UserImportExcelVO> importUsers, boolean isUpdateSupport) {
        if (CollUtil.isEmpty(importUsers)) {
            throw exception(USER_IMPORT_LIST_IS_EMPTY);
        }
        UserImportRespVO respVO = UserImportRespVO.builder().createUsernames(new ArrayList<>())
                .updateUsernames(new ArrayList<>()).failureUsernames(new LinkedHashMap<>()).build();
        importUsers.forEach(importUser -> {
            // 校验，判断是否有不符合的原因
            try {
                validateUserForCreateOrUpdate(null, null, importUser.getMobile(), importUser.getEmail());
            } catch (ServiceException ex) {
                respVO.getFailureUsernames().put(importUser.getUsername(), ex.getMessage());
                return;
            }
            // 判断如果不存在，在进行插入
            AdminUserDO existUser = userMapper.selectByUsername(importUser.getUsername());
            if (existUser == null) {
                userMapper.insert(BeanUtils.toBean(importUser, AdminUserDO.class)
                        .setPassword(encodePassword(userInitPassword))); // 设置默认密码及空岗位编号数组
                respVO.getCreateUsernames().add(importUser.getUsername());
                return;
            }
            // 如果存在，判断是否允许更新
            if (!isUpdateSupport) {
                respVO.getFailureUsernames().put(importUser.getUsername(), USER_USERNAME_EXISTS.getMsg());
                return;
            }
            AdminUserDO updateUser = BeanUtils.toBean(importUser, AdminUserDO.class);
            updateUser.setId(existUser.getId());
            userMapper.updateById(updateUser);
            respVO.getUpdateUsernames().add(importUser.getUsername());
        });
        return respVO;
    }

    @Override
    public List<AdminUserDO> getUserListByStatus(Integer status) {
        return userMapper.selectListByStatus(status);
    }

    @Override
    public boolean isPasswordMatch(String rawPassword, String encodedPassword) {
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    //获取部门详情
    @Override
    public List<UserRespVO.DeptInfo> getDeptInfo(Long userId, Set<Long> deptIdSet) {
        List<UserRespVO.DeptInfo> resultList = new ArrayList<>();
        if(CollectionUtil.isEmpty(deptIdSet)){
            return resultList;
        }
        //部门列表
        List<DeptDO> deptList = deptService.getDeptList();
        Map<Long, DeptDO> deptMap = CollectionUtils.convertMap(deptList, DeptDO::getId);
        //职位
        List<PostDO> postList = postService.getPostList();
        Map<Long, PostDO> postMap = CollectionUtils.convertMap(postList, PostDO::getId);
        //角色
        List<RoleDO> roleList = roleService.getRoleList();
        Map<Long, RoleDO> roleMap = CollectionUtils.convertMap(roleList, RoleDO::getId);
        //职务
        List<DutyDO> dutyList = dutyService.getDutyList();
        Map<Long, DutyDO> dutyMap = CollectionUtils.convertMap(dutyList, DutyDO::getId);
        //职位
        List<PositionDO> positionList = positionService.getPositionList();
        Map<Long, PositionDO> positionMap = CollectionUtils.convertMap(positionList, PositionDO::getId);

        for (Long deptId : deptIdSet) {
            DeptDO deptDO = deptMap.get(deptId);
            if (deptDO == null) {
                continue;
            }

            UserRespVO.DeptInfo deptInfo = new UserRespVO.DeptInfo();
            deptInfo.setDeptId(deptDO.getId());
            deptInfo.setDeptName(deptDO.getName());
            deptInfo.setPostInfoList(getPostInfoList(userId, deptId, postMap));//职位列表
            deptInfo.setRoleInfoList(getRoleInfoList(userId, deptId, roleMap));//角色列表
            deptInfo.setDutyInfoList(getDutyInfoList(userId,deptId,dutyMap));//职务列表
            deptInfo.setPositionInfoList(getPositionInfoList(userId,deptId,positionMap));//职位列表
            resultList.add(deptInfo);
        }
        return resultList;
    }

    //获取职级详情
    @Override
    public List<UserRespVO.IdName> getRankInfo(Long userId) {
        //职级
        List<RankDO> rankList = rankService.getRankList();
        Map<Long, RankDO> rankMap = CollectionUtils.convertMap(rankList, RankDO::getId);
        List<UserRespVO.IdName> rankInfoList = getRankInfoList(userId, rankMap);
        return rankInfoList;
    }

    //获取用户角色
    @Override
    public List<UserRoleDO> getUserRoleList(Long userId,Long deptId){
        List<UserRoleDO> userRoleDOList = userRoleMapper.selectListByUserId(userId, deptId);
        return userRoleDOList;
    }
    //是否是租户管理员
    @Override
    public boolean isTenantAdmin(Long userId){
        List<RoleDO> roleList = roleService.getRoleList();
        Map<Long, RoleDO> roleMap = CollectionUtils.convertMap(roleList, RoleDO::getId);

        List<UserRoleDO> userRoleDOList = userRoleMapper.selectListByUserId(userId);
        if(CollectionUtil.isEmpty(userRoleDOList)){
            return false;
        }
        boolean tenantAdmin=false;
        for(UserRoleDO userRoleDO:userRoleDOList){
            Long roleId = userRoleDO.getRoleId();
            RoleDO roleDO = roleMap.get(roleId);
            if(roleDO==null){
                continue;
            }
            String code = roleDO.getCode();
            if(RoleCodeEnum.isTenantAdmin(code)){
                tenantAdmin=true;
                break;
            }
        }
        return tenantAdmin;
    }

    @Override
    public boolean isSupAdmin(Long userId){
        if(userId==1){
            return true;
        }
        List<RoleDO> roleList = roleService.getRoleList();
        Map<Long, RoleDO> roleMap = CollectionUtils.convertMap(roleList, RoleDO::getId);

        List<UserRoleDO> userRoleDOList = userRoleMapper.selectListByUserId(userId);
        if(CollectionUtil.isEmpty(userRoleDOList)){
            return false;
        }
        boolean supAdmin=false;
        for(UserRoleDO userRoleDO:userRoleDOList){
            Long roleId = userRoleDO.getRoleId();
            RoleDO roleDO = roleMap.get(roleId);
            if(roleDO==null){
                continue;
            }
            String code = roleDO.getCode();
            if(RoleCodeEnum.isSuperAdmin(code)){
                supAdmin=true;
                break;
            }
        }
        return supAdmin;
    }


    private List<UserRespVO.IdName> getPostInfoList(Long userId, Long deptId, Map<Long, PostDO> postMap) {
        List<UserRespVO.IdName> postInfoList = new ArrayList<>();
        List<UserPostDO> userPostDOList = userPostMapper.selectListByUserId(userId, deptId);
        for (UserPostDO userPostDO : userPostDOList) {
            Long postId = userPostDO.getPostId();
            PostDO postDO = postMap.get(postId);
            if (postDO == null) {
                continue;
            }
            UserRespVO.IdName postInfo = new UserRespVO.IdName(postDO.getId(), postDO.getName());
            postInfoList.add(postInfo);
        }
        return postInfoList;
    }

    private List<UserRespVO.IdName> getRoleInfoList(Long userId, Long deptId, Map<Long, RoleDO> roleMap) {
        List<UserRespVO.IdName> idNameList = new ArrayList<>();
        List<UserRoleDO> list = userRoleMapper.selectListByUserId(userId, deptId);
        for (UserRoleDO userRoleDO : list) {
            Long roleId = userRoleDO.getRoleId();
            RoleDO roleDO = roleMap.get(roleId);
            if (roleDO == null) {
                continue;
            }
            UserRespVO.IdName roleInfo = new UserRespVO.IdName(roleDO.getId(), roleDO.getName());
            idNameList.add(roleInfo);
        }
        return idNameList;
    }

    private List<UserRespVO.IdName> getDutyInfoList(Long userId, Long deptId, Map<Long, DutyDO> dutyMap) {
        List<UserRespVO.IdName> idNameList = new ArrayList<>();
        List<UserDutyDO> list = userDutyMapper.selectListByUserId(userId, deptId);
        for (UserDutyDO userDutyDO : list) {
            Long dutyId = userDutyDO.getDutyId();
            DutyDO dutyDO = dutyMap.get(dutyId);
            if (dutyDO == null) {
                continue;
            }
            UserRespVO.IdName roleInfo = new UserRespVO.IdName(dutyDO.getId(), dutyDO.getName());
            idNameList.add(roleInfo);
        }
        return idNameList;
    }

    private List<UserRespVO.IdName> getPositionInfoList(Long userId, Long deptId, Map<Long, PositionDO> positionMap) {
        List<UserRespVO.IdName> idNameList = new ArrayList<>();
        List<UserPositionDO> list = userPositionMapper.selectListByUserId(userId, deptId);
        for (UserPositionDO userPositionDO : list) {
            Long positionId = userPositionDO.getPositionId();
            PositionDO positionDO = positionMap.get(positionId);
            if (positionDO == null) {
                continue;
            }
            UserRespVO.IdName roleInfo = new UserRespVO.IdName(positionDO.getId(), positionDO.getName());
            idNameList.add(roleInfo);
        }
        return idNameList;
    }
    private List<UserRespVO.IdName> getRankInfoList(Long userId, Map<Long, RankDO> rankMap) {
        List<UserRespVO.IdName> idNameList = new ArrayList<>();
        List<UserRankDO> list = userRankMapper.selectListByUserId(userId);
        for (UserRankDO userRankDO : list) {
            Long rankId = userRankDO.getRankId();
            RankDO rankDO = rankMap.get(rankId);
            if (rankDO == null) {
                continue;
            }
            UserRespVO.IdName roleInfo = new UserRespVO.IdName(rankDO.getId(), rankDO.getName());
            idNameList.add(roleInfo);
        }
        return idNameList;
    }

    /**
     * 对密码进行加密
     *
     * @param password 密码
     * @return 加密后的密码
     */
    private String encodePassword(String password) {
        return passwordEncoder.encode(password);
    }

}
