package com.sundot.airport.system.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.validation.Validator;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.sundot.airport.common.core.domain.BaseLargeScreenQueryParamDto;
import com.sundot.airport.common.core.domain.LargeScreenHomePageUserInfoSqlDto;
import com.sundot.airport.common.core.domain.ResetUserPostDto;
import com.sundot.airport.common.core.domain.ResetUserRoleDto;
import com.sundot.airport.common.core.domain.entity.SysDept;
import com.sundot.airport.common.core.domain.entity.SysDictData;
import com.sundot.airport.common.dto.SysUserConditionDto;
import com.sundot.airport.common.dto.UserInfo;
import com.sundot.airport.common.enums.DeptType;
import com.sundot.airport.common.enums.RoleTypeEnum;
import com.sundot.airport.system.domain.SysLargeScreenCooperationDto;
import com.sundot.airport.system.domain.SysLargeScreenCooperationItemDto;
import com.sundot.airport.system.domain.SysLargeScreenCooperationQueryParamDto;
import com.sundot.airport.system.enums.SubjectiveImpressionEnum;
import com.sundot.airport.system.service.ISysDictDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import com.sundot.airport.common.annotation.DataScope;
import com.sundot.airport.common.constant.UserConstants;
import com.sundot.airport.common.core.domain.entity.SysRole;
import com.sundot.airport.common.core.domain.entity.SysUser;
import com.sundot.airport.common.exception.ServiceException;
import com.sundot.airport.common.utils.SecurityUtils;
import com.sundot.airport.common.utils.StringUtils;
import com.sundot.airport.common.utils.bean.BeanValidators;
import com.sundot.airport.common.utils.spring.SpringUtils;
import com.sundot.airport.system.domain.SysPost;
import com.sundot.airport.system.domain.SysUserPost;
import com.sundot.airport.system.domain.SysUserRole;
import com.sundot.airport.system.mapper.SysPostMapper;
import com.sundot.airport.system.mapper.SysRoleMapper;
import com.sundot.airport.system.mapper.SysUserMapper;
import com.sundot.airport.system.mapper.SysUserPostMapper;
import com.sundot.airport.system.mapper.SysUserRoleMapper;
import com.sundot.airport.system.service.ISysConfigService;
import com.sundot.airport.system.service.ISysDeptService;
import com.sundot.airport.system.service.ISysUserService;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    protected Validator validator;

    @Autowired
    private ISysDictDataService sysDictDataService;

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user) {
        return userMapper.selectUserList(user);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllocatedList(SysUser user) {
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUnallocatedList(SysUser user) {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过手机号查询用户
     *
     * @param phonenumber 手机号
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByPhonenumber(String phonenumber) {
        return userMapper.selectUserByPhonenumber(phonenumber);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkUserNameUnique(user.getUserName());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user) {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user) {
        return userMapper.insertUser(user) > 0;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        return userMapper.updateUser(user);
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param userId 用户ID
     * @param avatar 头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(Long userId, String avatar) {
        return userMapper.updateUserAvatar(userId, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param userId   用户ID
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(Long userId, String password) {
        return userMapper.resetUserPwd(userId, password);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>(posts.length);
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    deptService.checkDeptDataScope(user.getDeptId());
                    String password = configService.selectConfigByKey("sys.user.initPassword");
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    userMapper.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(u);
                    checkUserDataScope(u.getUserId());
                    deptService.checkDeptDataScope(user.getDeptId());
                    user.setUserId(u.getUserId());
                    user.setUpdateBy(operName);
                    userMapper.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 通过用户ID查询用户各级领导
     *
     * @param userId   用户ID
     * @param deptType 部门类型
     * @return 领导信息
     */
    @Override
    public SysUser selectDeptLeaderByUserId(Long userId, String deptType) {
        UserInfo userInfo = new UserInfo();
        SysUser sysUser = selectUserById(userId);
        BeanUtils.copyProperties(sysUser, userInfo);
        if (Objects.isNull(userInfo.getDeptId())) {
            return null;
        }
        List<SysDept> deptList = deptService.selectAllDept(userInfo.getDeptId());
        if (CollectionUtil.isEmpty(deptList)) {
            return null;
        }
        Collections.reverse(deptList);
        SysDept teams = deptList.stream().filter(x -> StrUtil.equals(DeptType.TEAMS.getCode(), x.getDeptType())).findFirst().orElse(new SysDept());
        SysDept department = deptList.stream().filter(x -> StrUtil.equals(DeptType.MANAGER.getCode(), x.getDeptType())).findFirst().orElse(new SysDept());
        SysDept brigade = deptList.stream().filter(x -> StrUtil.equals(DeptType.BRIGADE.getCode(), x.getDeptType())).findFirst().orElse(new SysDept());
        SysDept station = deptList.stream().filter(x -> StrUtil.equals(DeptType.STATION.getCode(), x.getDeptType())).findFirst().orElse(new SysDept());
        userInfo.setTeamsId(teams.getDeptId());
        userInfo.setTeamsName(teams.getDeptName());
        userInfo.setDepartmentId(department.getDeptId());
        userInfo.setDepartmentName(department.getDeptName());
        userInfo.setBrigadeId(brigade.getDeptId());
        userInfo.setBrigadeName(brigade.getDeptName());
        userInfo.setStationId(station.getDeptId());
        userInfo.setStationName(station.getDeptName());

        Long deptId;
        if (StrUtil.equals(DeptType.TEAMS.getCode(), deptType)) {
            deptId = userInfo.getTeamsId();
        } else if (StrUtil.equals(DeptType.MANAGER.getCode(), deptType)) {
            deptId = userInfo.getDepartmentId();
        } else if (StrUtil.equals(DeptType.BRIGADE.getCode(), deptType)) {
            deptId = userInfo.getBrigadeId();
        } else if (StrUtil.equals(DeptType.STATION.getCode(), deptType)) {
            deptId = userInfo.getStationId();
        } else {
            return null;
        }
        if (Objects.isNull(deptId)) {
            return null;
        }
        return deptService.deptLeader(deptId);
    }

    /**
     * 重置班组长和安检员的岗位为旅检的所有二级岗位
     *
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int resetUserPost() {
        // 查询所有班组长和安检员
        List<Long> userIdList = userMapper.selectBzzAndAjy();
        // 根据父ID查询所有子元素
        List<SysPost> sysPostList = postMapper.selectPostByParentId(-1L);
        if (CollectionUtil.isEmpty(userIdList) || CollectionUtil.isEmpty(sysPostList)) {
            return 0;
        }
        List<Long> postIdList = sysPostList.stream().map(SysPost::getPostId).collect(Collectors.toList());
        for (Long userId : userIdList) {
            // 创建数据
            SysUser user = new SysUser();
            user.setUserId(userId);
            user.setPostIds(postIdList.toArray(new Long[0]));
            // 删除用户与岗位关联
            userPostMapper.deleteUserPostByUserId(userId);
            // 新增用户与岗位管理
            insertUserPost(user);
        }
        return 1;
    }

    /**
     * 重置指定人员的指定角色
     *
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int resetUserRole(ResetUserRoleDto resetUserRoleDto) {
        List<SysUserRole> list = new ArrayList<>();
        List<SysRole> sysRoleList = roleMapper.selectRoleList(new SysRole());
        List<Long> roleIdList = sysRoleList.stream().filter(sysRole -> resetUserRoleDto.getRoleKeyList().contains(sysRole.getRoleKey())).map(SysRole::getRoleId).distinct().collect(Collectors.toList());
        resetUserRoleDto.getUserNameList().forEach(x -> {
            SysUser sysUser = userMapper.selectUserByUserName(x);
            if (sysUser == null) {
                throw new ServiceException("根据【" + x + "】未查询到用户信息");
            }
            userRoleMapper.deleteUserRoleByUserId(sysUser.getUserId());
            roleIdList.forEach(y -> {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(sysUser.getUserId());
                sysUserRole.setRoleId(y);
                list.add(sysUserRole);
            });
        });
        if (CollUtil.isNotEmpty(list)) {
            userRoleMapper.batchUserRole(list);
        }
        return 1;
    }

    /**
     * 根据角色标识查询用户列表
     *
     * @param roleKeyList 角色标识
     * @return 用户列表
     */
    @Override
    public List<SysUser> selectUserListByRoleKey(List<String> roleKeyList) {
        return userMapper.selectUserListByRoleKey(roleKeyList);
    }

    @Override
    public List<SysUser> selectUserListByRoleKeyAndDeptId(List<String> roleKeyList, Long stationId) {
        return userMapper.selectUserListByRoleKeyAndDeptId(roleKeyList, stationId);
    }

    /**
     * 根据组织ID查询用户列表
     *
     * @param deptId 组织ID
     * @return 用户信息集合
     */
    @Override
    public List<SysUser> selectUserByDeptId(Long deptId) {
        return userMapper.selectUserByDeptId(deptId);
    }

    /**
     * 根据用户ID列表查询用户列表
     *
     * @param list 用户ID列表
     * @return 用户信息集合
     */
    @Override
    public List<SysUser> selectByUserIdList(List<Long> list) {
        return userMapper.selectByUserIdList(list);
    }

    /**
     * 能力画像-协同配合
     *
     * @param dto 上行参数
     * @return 能力画像-协同配合
     */
    @Override
    public SysLargeScreenCooperationDto cooperation(SysLargeScreenCooperationQueryParamDto dto) {
        SysLargeScreenCooperationDto result = new SysLargeScreenCooperationDto();
        // 性别
        List<SysLargeScreenCooperationItemDto> sexList = new ArrayList<>();
        // 生肖
        List<SysLargeScreenCooperationItemDto> zodiacList = new ArrayList<>();
        // 血型
        List<SysLargeScreenCooperationItemDto> blooGroupList = new ArrayList<>();
        // 星座
        List<SysLargeScreenCooperationItemDto> constellationList = new ArrayList<>();
        // 性格特征
        List<SysLargeScreenCooperationItemDto> characterCharacteristicsList = new ArrayList<>();
        // 工作风格
        List<SysLargeScreenCooperationItemDto> workingStyleList = new ArrayList<>();
        // 主观印象
        List<SysLargeScreenCooperationItemDto> subjectiveImpressionList = new ArrayList<>();

        if (ObjUtil.isNull(dto.getDeptId())) {
            // 查询条件处理
            List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
            if (CollUtil.isEmpty(roles)) {
                return null;
            }
            List<String> roleKeyList = roles.stream().map(SysRole::getRoleKey).collect(Collectors.toList());
            if (roleKeyList.contains(RoleTypeEnum.admin.getCode())) {
                List<SysUser> sysUserList = userMapper.selectUserAll();
                sysUserList = sysUserList.stream().filter(item -> item.getRoles().stream().anyMatch(sysRole -> RoleTypeEnum.banzuzhang.getCode().equals(sysRole.getRoleKey()) || RoleTypeEnum.SecurityCheck.getCode().equals(sysRole.getRoleKey()))).collect(Collectors.toList());
                extracted(sysUserList, sexList, zodiacList, blooGroupList, constellationList, characterCharacteristicsList, workingStyleList, subjectiveImpressionList);
            } else if (roleKeyList.contains(RoleTypeEnum.test.getCode()) || roleKeyList.contains(RoleTypeEnum.zhijianke.getCode())) {
                List<SysUser> sysUserList = userMapper.selectUserByDeptId(SecurityUtils.getLoginUser().getDeptId());
                sysUserList = sysUserList.stream().filter(item -> item.getRoles().stream().anyMatch(sysRole -> RoleTypeEnum.banzuzhang.getCode().equals(sysRole.getRoleKey()) || RoleTypeEnum.SecurityCheck.getCode().equals(sysRole.getRoleKey()))).collect(Collectors.toList());
                extracted(sysUserList, sexList, zodiacList, blooGroupList, constellationList, characterCharacteristicsList, workingStyleList, subjectiveImpressionList);
            } else if (roleKeyList.contains(RoleTypeEnum.jingli.getCode()) || roleKeyList.contains(RoleTypeEnum.xingzheng.getCode())) {
                List<SysUser> sysUserList = userMapper.selectUserByDeptId(SecurityUtils.getLoginUser().getDeptId());
                sysUserList = sysUserList.stream().filter(item -> item.getRoles().stream().anyMatch(sysRole -> RoleTypeEnum.banzuzhang.getCode().equals(sysRole.getRoleKey()) || RoleTypeEnum.SecurityCheck.getCode().equals(sysRole.getRoleKey()))).collect(Collectors.toList());
                extracted(sysUserList, sexList, zodiacList, blooGroupList, constellationList, characterCharacteristicsList, workingStyleList, subjectiveImpressionList);
            } else if (roleKeyList.contains(RoleTypeEnum.kezhang.getCode())) {
                List<SysUser> sysUserList = userMapper.selectUserByDeptId(SecurityUtils.getLoginUser().getDeptId());
                sysUserList = sysUserList.stream().filter(item -> item.getRoles().stream().anyMatch(sysRole -> RoleTypeEnum.banzuzhang.getCode().equals(sysRole.getRoleKey()) || RoleTypeEnum.SecurityCheck.getCode().equals(sysRole.getRoleKey()))).collect(Collectors.toList());
                extracted(sysUserList, sexList, zodiacList, blooGroupList, constellationList, characterCharacteristicsList, workingStyleList, subjectiveImpressionList);
            } else if (roleKeyList.contains(RoleTypeEnum.banzuzhang.getCode())) {
                // 团队配合
                List<SysUser> sysUserList = userMapper.selectUserByDeptId(SecurityUtils.getLoginUser().getDeptId());
                sysUserList.forEach(item -> {
                    if (StringUtils.isNotEmpty(item.getTeamCooperation())) {
                        List<Long> list = Arrays.stream(item.getTeamCooperation().split(",")).map(Long::valueOf).collect(Collectors.toList());
                        item.setTeamCooperationList(selectByUserIdList(list));
                    }
                });
                result.setTeamCooperationList(sysUserList);
                extracted(sysUserList, sexList, zodiacList, blooGroupList, constellationList, characterCharacteristicsList, workingStyleList, subjectiveImpressionList);
            } else if (roleKeyList.contains(RoleTypeEnum.SecurityCheck.getCode())) {
                return null;
            } else {
                return null;
            }
        } else {
            SysDept sysDept = deptService.selectDeptById(dto.getDeptId());
            if (ObjUtil.isNull(sysDept)) {
                return null;
            }
            List<SysUser> sysUserList = userMapper.selectUserByDeptId(dto.getDeptId());
            sysUserList = sysUserList.stream().filter(item -> item.getRoles().stream().anyMatch(sysRole -> RoleTypeEnum.banzuzhang.getCode().equals(sysRole.getRoleKey()) || RoleTypeEnum.SecurityCheck.getCode().equals(sysRole.getRoleKey()))).collect(Collectors.toList());
            if (StrUtil.equals("TEAMS", sysDept.getDeptType())) {
                sysUserList.forEach(item -> {
                    if (StringUtils.isNotEmpty(item.getTeamCooperation())) {
                        List<Long> list = Arrays.stream(item.getTeamCooperation().split(",")).map(Long::valueOf).collect(Collectors.toList());
                        item.setTeamCooperationList(selectByUserIdList(list));
                    }
                });
                result.setTeamCooperationList(sysUserList);
            }
            extracted(sysUserList, sexList, zodiacList, blooGroupList, constellationList, characterCharacteristicsList, workingStyleList, subjectiveImpressionList);
        }
        result.setSexList(sexList);
        result.setZodiacList(zodiacList);
        result.setBlooGroupList(blooGroupList);
        result.setConstellationList(constellationList);
        result.setCharacterCharacteristicsList(characterCharacteristicsList);
        result.setWorkingStyleList(workingStyleList);
        result.setSubjectiveImpressionList(subjectiveImpressionList);
        return result;
    }

    /**
     * 协同配合数据处理
     *
     * @param sysUserList 用户列表
     * @return 协同配合数据处理
     */
    private void extracted(List<SysUser> sysUserList, List<SysLargeScreenCooperationItemDto> sexList, List<SysLargeScreenCooperationItemDto> zodiacList, List<SysLargeScreenCooperationItemDto> blooGroupList, List<SysLargeScreenCooperationItemDto> constellationList, List<SysLargeScreenCooperationItemDto> characterCharacteristicsList, List<SysLargeScreenCooperationItemDto> workingStyleList, List<SysLargeScreenCooperationItemDto> subjectiveImpressionList) {
        if (CollUtil.isEmpty(sysUserList)) {
            return;
        }
        // 性别
        SysDictData sexDictData = new SysDictData();
        sexDictData.setDictType("sys_user_sex");
        List<SysDictData> sexDictDataList = sysDictDataService.selectDictDataList(sexDictData);
        Map<String, String> sexDictDataMap = sexDictDataList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        Map<String, Long> sexMap = sysUserList.stream().filter(item -> StringUtils.isNotEmpty(item.getSex())).collect(Collectors.groupingBy(SysUser::getSex, Collectors.counting()));
        long sexTotal = sexMap.values().stream()
                .mapToLong(Long::longValue)
                .sum();
        sexMap.forEach((key, value) -> {
            SysLargeScreenCooperationItemDto sexItem = new SysLargeScreenCooperationItemDto();
            sexItem.setCode(key);
            sexItem.setName(sexDictDataMap.getOrDefault(key, key));
            sexItem.setCount(value);
            sexItem.setScale(BigDecimal.valueOf(100).multiply(BigDecimal.valueOf(value)).divide(BigDecimal.valueOf(sexTotal), 2, RoundingMode.HALF_UP));
            sexList.add(sexItem);
        });
        // 生肖
        SysDictData zodiacDictData = new SysDictData();
        zodiacDictData.setDictType("sys_user_odiac");
        List<SysDictData> zodiacDictDataList = sysDictDataService.selectDictDataList(zodiacDictData);
        Map<String, String> zodiacDictDataMap = zodiacDictDataList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        Map<String, Long> zodiacMap = sysUserList.stream().filter(item -> StringUtils.isNotEmpty(item.getZodiac())).collect(Collectors.groupingBy(SysUser::getZodiac, Collectors.counting()));
        long zodiacTotal = zodiacMap.values().stream()
                .mapToLong(Long::longValue)
                .sum();
        zodiacMap.forEach((key, value) -> {
            SysLargeScreenCooperationItemDto zodiacItem = new SysLargeScreenCooperationItemDto();
            zodiacItem.setCode(key);
            zodiacItem.setName(zodiacDictDataMap.getOrDefault(key, key));
            zodiacItem.setCount(value);
            zodiacItem.setScale(BigDecimal.valueOf(100).multiply(BigDecimal.valueOf(value)).divide(BigDecimal.valueOf(zodiacTotal), 2, RoundingMode.HALF_UP));
            zodiacList.add(zodiacItem);
        });
        // 血型
        SysDictData blooGroupDictData = new SysDictData();
        blooGroupDictData.setDictType("sys_user_blood_group");
        List<SysDictData> blooGroupDictDataList = sysDictDataService.selectDictDataList(blooGroupDictData);
        Map<String, String> blooGroupDictDataMap = blooGroupDictDataList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        Map<String, Long> blooGroupMap = sysUserList.stream().filter(item -> StringUtils.isNotEmpty(item.getBlooGroup())).collect(Collectors.groupingBy(SysUser::getBlooGroup, Collectors.counting()));
        long blooGroupTotal = blooGroupMap.values().stream()
                .mapToLong(Long::longValue)
                .sum();
        blooGroupMap.forEach((key, value) -> {
            SysLargeScreenCooperationItemDto blooGroupMapItem = new SysLargeScreenCooperationItemDto();
            blooGroupMapItem.setCode(key);
            blooGroupMapItem.setName(blooGroupDictDataMap.getOrDefault(key, key));
            blooGroupMapItem.setCount(value);
            blooGroupMapItem.setScale(BigDecimal.valueOf(100).multiply(BigDecimal.valueOf(value)).divide(BigDecimal.valueOf(blooGroupTotal), 2, RoundingMode.HALF_UP));
            blooGroupList.add(blooGroupMapItem);
        });
        // 星座
        SysDictData constellationDictData = new SysDictData();
        constellationDictData.setDictType("sys_user_constellation");
        List<SysDictData> constellationDictDataList = sysDictDataService.selectDictDataList(constellationDictData);
        Map<String, String> constellationDictDataMap = constellationDictDataList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        Map<String, Long> constellationMap = sysUserList.stream().filter(item -> StringUtils.isNotEmpty(item.getConstellation())).collect(Collectors.groupingBy(SysUser::getConstellation, Collectors.counting()));
        long constellationTotal = constellationMap.values().stream()
                .mapToLong(Long::longValue)
                .sum();
        constellationMap.forEach((key, value) -> {
            SysLargeScreenCooperationItemDto constellationItem = new SysLargeScreenCooperationItemDto();
            constellationItem.setCode(key);
            constellationItem.setName(constellationDictDataMap.getOrDefault(key, key));
            constellationItem.setCount(value);
            constellationItem.setScale(BigDecimal.valueOf(100).multiply(BigDecimal.valueOf(value)).divide(BigDecimal.valueOf(constellationTotal), 2, RoundingMode.HALF_UP));
            constellationList.add(constellationItem);
        });
        // 性格特征
        SysDictData characterCharacteristicsDictData = new SysDictData();
        characterCharacteristicsDictData.setDictType("sys_user_character_characteristics");
        List<SysDictData> characterCharacteristicsDictDataList = sysDictDataService.selectDictDataList(characterCharacteristicsDictData);
        Map<String, String> characterCharacteristicsDictDataMap = characterCharacteristicsDictDataList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        Map<String, Long> characterCharacteristicsMap = sysUserList.stream().filter(item -> StringUtils.isNotEmpty(item.getCharacterCharacteristics())).collect(Collectors.groupingBy(SysUser::getCharacterCharacteristics, Collectors.counting()));
        long characterCharacteristicsTotal = characterCharacteristicsMap.values().stream()
                .mapToLong(Long::longValue)
                .sum();
        characterCharacteristicsMap.forEach((key, value) -> {
            SysLargeScreenCooperationItemDto characterCharacteristicsItem = new SysLargeScreenCooperationItemDto();
            characterCharacteristicsItem.setCode(key);
            characterCharacteristicsItem.setName(characterCharacteristicsDictDataMap.getOrDefault(key, key));
            characterCharacteristicsItem.setCount(value);
            characterCharacteristicsItem.setScale(BigDecimal.valueOf(100).multiply(BigDecimal.valueOf(value)).divide(BigDecimal.valueOf(characterCharacteristicsTotal), 2, RoundingMode.HALF_UP));
            characterCharacteristicsList.add(characterCharacteristicsItem);
        });
        // 工作风格
        SysDictData workingStyleDictData = new SysDictData();
        workingStyleDictData.setDictType("sys_user_working_style");
        List<SysDictData> workingStyleDictDataList = sysDictDataService.selectDictDataList(workingStyleDictData);
        Map<String, String> workingStyleDictDataMap = workingStyleDictDataList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        Map<String, Long> workingStyleMap = sysUserList.stream().filter(item -> StringUtils.isNotEmpty(item.getWorkingStyle())).collect(Collectors.groupingBy(SysUser::getWorkingStyle, Collectors.counting()));
        long workingStyleTotal = workingStyleMap.values().stream()
                .mapToLong(Long::longValue)
                .sum();
        workingStyleMap.forEach((key, value) -> {
            SysLargeScreenCooperationItemDto workingStyleItem = new SysLargeScreenCooperationItemDto();
            workingStyleItem.setCode(key);
            workingStyleItem.setName(workingStyleDictDataMap.getOrDefault(key, key));
            workingStyleItem.setCount(value);
            workingStyleItem.setScale(BigDecimal.valueOf(100).multiply(BigDecimal.valueOf(value)).divide(BigDecimal.valueOf(workingStyleTotal), 2, RoundingMode.HALF_UP));
            workingStyleList.add(workingStyleItem);
        });
        // 主观印象-开始
        // 主观印象-性格特质
        SysDictData personalityTraitDictData = new SysDictData();
        personalityTraitDictData.setDictType("sys_user_personality_trait");
        List<SysDictData> personalityTraitDictDataList = sysDictDataService.selectDictDataList(personalityTraitDictData);
        Map<String, String> personalityTraitDictDataMap = personalityTraitDictDataList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        Map<String, Long> personalityTraitCountMap = sysUserList.stream()
                .flatMap(item -> Stream.of(item.getSelfAssessmentPersonalityTrait(), item.getColleagueCommentsPersonalityTrait(), item.getSuperiorEvaluationPersonalityTrait(), item.getSubordinateEvaluationPersonalityTrait()))
                .filter(Objects::nonNull)
                .filter(StrUtil::isNotEmpty)
                .collect(Collectors.groupingBy(
                        Function.identity(),
                        Collectors.counting()
                ));
        List<SysLargeScreenCooperationItemDto> personalityTraitItemChildren = new ArrayList<>();
        personalityTraitCountMap.forEach((key, value) -> {
            SysLargeScreenCooperationItemDto personalityTraitItem = new SysLargeScreenCooperationItemDto();
            personalityTraitItem.setCode(key);
            personalityTraitItem.setName(personalityTraitDictDataMap.getOrDefault(key, key));
            personalityTraitItem.setCount(value);
            personalityTraitItemChildren.add(personalityTraitItem);
        });
        long personalityTraitTotal = personalityTraitCountMap.values().stream()
                .mapToLong(Long::longValue)
                .sum();
        SysLargeScreenCooperationItemDto personalityTraitItem = new SysLargeScreenCooperationItemDto();
        personalityTraitItem.setCode(SubjectiveImpressionEnum.personality_trait.getCode());
        personalityTraitItem.setName(SubjectiveImpressionEnum.personality_trait.getDesc());
        personalityTraitItem.setCount(personalityTraitTotal);
        personalityTraitItem.setChildren(personalityTraitItemChildren);
        if (personalityTraitTotal > 0) {
            subjectiveImpressionList.add(personalityTraitItem);
        }
        // 主观印象-能力表现
        SysDictData capabilityPerformanceDictData = new SysDictData();
        capabilityPerformanceDictData.setDictType("sys_user_capability_performance");
        List<SysDictData> capabilityPerformanceDictDataList = sysDictDataService.selectDictDataList(capabilityPerformanceDictData);
        Map<String, String> capabilityPerformanceDictDataMap = capabilityPerformanceDictDataList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        Map<String, Long> capabilityPerformanceCountMap = sysUserList.stream()
                .flatMap(item -> Stream.of(item.getSelfAssessmentCapabilityPerformance(), item.getColleagueCommentsCapabilityPerformance(), item.getSuperiorEvaluationCapabilityPerformance(), item.getSubordinateEvaluationCapabilityPerformance()))
                .filter(Objects::nonNull)
                .filter(StrUtil::isNotEmpty)
                .collect(Collectors.groupingBy(
                        Function.identity(),
                        Collectors.counting()
                ));
        List<SysLargeScreenCooperationItemDto> capabilityPerformanceItemChildren = new ArrayList<>();
        capabilityPerformanceCountMap.forEach((key, value) -> {
            SysLargeScreenCooperationItemDto capabilityPerformanceItem = new SysLargeScreenCooperationItemDto();
            capabilityPerformanceItem.setCode(key);
            capabilityPerformanceItem.setName(capabilityPerformanceDictDataMap.getOrDefault(key, key));
            capabilityPerformanceItem.setCount(value);
            capabilityPerformanceItemChildren.add(capabilityPerformanceItem);
        });
        long capabilityPerformanceTotal = personalityTraitCountMap.values().stream()
                .mapToLong(Long::longValue)
                .sum();
        SysLargeScreenCooperationItemDto capabilityPerformanceItem = new SysLargeScreenCooperationItemDto();
        capabilityPerformanceItem.setCode(SubjectiveImpressionEnum.capability_performance.getCode());
        capabilityPerformanceItem.setName(SubjectiveImpressionEnum.capability_performance.getDesc());
        capabilityPerformanceItem.setCount(capabilityPerformanceTotal);
        capabilityPerformanceItem.setChildren(capabilityPerformanceItemChildren);
        if (capabilityPerformanceTotal > 0) {
            subjectiveImpressionList.add(capabilityPerformanceItem);
        }
        // 主观印象-人际互动
        SysDictData interpersonalInteractionDictData = new SysDictData();
        interpersonalInteractionDictData.setDictType("sys_user_interpersonal_interaction");
        List<SysDictData> interpersonalInteractionDictDataList = sysDictDataService.selectDictDataList(interpersonalInteractionDictData);
        Map<String, String> interpersonalInteractionDictDataMap = interpersonalInteractionDictDataList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        Map<String, Long> interpersonalInteractionCountMap = sysUserList.stream()
                .flatMap(item -> Stream.of(item.getSelfAssessmentInterpersonalInteraction(), item.getColleagueCommentsInterpersonalInteraction(), item.getSuperiorEvaluationInterpersonalInteraction(), item.getSubordinateEvaluationInterpersonalInteraction()))
                .filter(Objects::nonNull)
                .filter(StrUtil::isNotEmpty)
                .collect(Collectors.groupingBy(
                        Function.identity(),
                        Collectors.counting()
                ));
        List<SysLargeScreenCooperationItemDto> interpersonalInteractionItemChildren = new ArrayList<>();
        interpersonalInteractionCountMap.forEach((key, value) -> {
            SysLargeScreenCooperationItemDto interpersonalInteractionItem = new SysLargeScreenCooperationItemDto();
            interpersonalInteractionItem.setCode(key);
            interpersonalInteractionItem.setName(interpersonalInteractionDictDataMap.getOrDefault(key, key));
            interpersonalInteractionItem.setCount(value);
            interpersonalInteractionItemChildren.add(interpersonalInteractionItem);
        });
        long interpersonalInteractionTotal = interpersonalInteractionCountMap.values().stream()
                .mapToLong(Long::longValue)
                .sum();
        SysLargeScreenCooperationItemDto interpersonalInteractionItem = new SysLargeScreenCooperationItemDto();
        interpersonalInteractionItem.setCode(SubjectiveImpressionEnum.interpersonal_interaction.getCode());
        interpersonalInteractionItem.setName(SubjectiveImpressionEnum.interpersonal_interaction.getDesc());
        interpersonalInteractionItem.setCount(interpersonalInteractionTotal);
        interpersonalInteractionItem.setChildren(interpersonalInteractionItemChildren);
        if (interpersonalInteractionTotal > 0) {
            subjectiveImpressionList.add(interpersonalInteractionItem);
        }
        // 主观印象-成长潜力
        SysDictData growthPotentialDictData = new SysDictData();
        growthPotentialDictData.setDictType("sys_user_growth_potential");
        List<SysDictData> growthPotentialDictDataList = sysDictDataService.selectDictDataList(growthPotentialDictData);
        Map<String, String> growthPotentialDictDataMap = growthPotentialDictDataList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        Map<String, Long> growthPotentialCountMap = sysUserList.stream()
                .flatMap(item -> Stream.of(item.getSelfAssessmentGrowthPotential(), item.getColleagueCommentsGrowthPotential(), item.getSuperiorEvaluationGrowthPotential(), item.getSubordinateEvaluationGrowthPotential()))
                .filter(Objects::nonNull)
                .filter(StrUtil::isNotEmpty)
                .collect(Collectors.groupingBy(
                        Function.identity(),
                        Collectors.counting()
                ));
        List<SysLargeScreenCooperationItemDto> growthPotentialItemChildren = new ArrayList<>();
        growthPotentialCountMap.forEach((key, value) -> {
            SysLargeScreenCooperationItemDto growthPotentialItem = new SysLargeScreenCooperationItemDto();
            growthPotentialItem.setCode(key);
            growthPotentialItem.setName(growthPotentialDictDataMap.getOrDefault(key, key));
            growthPotentialItem.setCount(value);
            growthPotentialItemChildren.add(growthPotentialItem);
        });
        long growthPotentialTotal = growthPotentialCountMap.values().stream()
                .mapToLong(Long::longValue)
                .sum();
        SysLargeScreenCooperationItemDto growthPotentialItem = new SysLargeScreenCooperationItemDto();
        growthPotentialItem.setCode(SubjectiveImpressionEnum.growth_potential.getCode());
        growthPotentialItem.setName(SubjectiveImpressionEnum.growth_potential.getDesc());
        growthPotentialItem.setCount(growthPotentialTotal);
        growthPotentialItem.setChildren(growthPotentialItemChildren);
        if (growthPotentialTotal > 0) {
            subjectiveImpressionList.add(growthPotentialItem);
        }
        // 主观印象-结束
    }


    /**
     * 总体概览-工作风格
     *
     * @param dto 上行参数
     * @return 总体概览-工作风格
     */
    @Override
    public String getWorkingStyle(BaseLargeScreenQueryParamDto dto) {
        if (ObjUtil.isNotNull(dto.getUserId())) {
            // 个人
            SysUser sysUser = userMapper.selectUserById(dto.getUserId());
            return sysUser.getWorkingStyle();
        } else {
            // 组织
            List<SysUser> sysUserList = userMapper.selectUserByDeptId(dto.getDeptId());
            sysUserList = sysUserList.stream().filter(item -> item.getRoles().stream().anyMatch(sysRole -> RoleTypeEnum.banzuzhang.getCode().equals(sysRole.getRoleKey()) || RoleTypeEnum.SecurityCheck.getCode().equals(sysRole.getRoleKey()))).collect(Collectors.toList());
            List<String> workingStyleList = sysUserList.stream().map(SysUser::getWorkingStyle).filter(ObjUtil::isNotEmpty).collect(Collectors.toList());
            return findMostFrequentElement(workingStyleList);
        }
    }

    /**
     * 总体概览-主观印象
     *
     * @param dto 上行参数
     * @return 总体概览-主观印象
     */
    @Override
    public String getSubjectiveImpression(BaseLargeScreenQueryParamDto dto) {
        if (ObjUtil.isNotNull(dto.getUserId())) {
            // 个人
            SysUser sysUser = userMapper.selectUserById(dto.getUserId());
            List<String> list = Stream.of(
                            sysUser.getSelfAssessmentPersonalityTrait(),
                            sysUser.getSelfAssessmentCapabilityPerformance(),
                            sysUser.getSelfAssessmentInterpersonalInteraction(),
                            sysUser.getSelfAssessmentGrowthPotential(),
                            sysUser.getColleagueCommentsPersonalityTrait(),
                            sysUser.getColleagueCommentsCapabilityPerformance(),
                            sysUser.getColleagueCommentsInterpersonalInteraction(),
                            sysUser.getColleagueCommentsGrowthPotential(),
                            sysUser.getSuperiorEvaluationPersonalityTrait(),
                            sysUser.getSuperiorEvaluationCapabilityPerformance(),
                            sysUser.getSuperiorEvaluationInterpersonalInteraction(),
                            sysUser.getSuperiorEvaluationGrowthPotential(),
                            sysUser.getSubordinateEvaluationPersonalityTrait(),
                            sysUser.getSubordinateEvaluationCapabilityPerformance(),
                            sysUser.getSubordinateEvaluationInterpersonalInteraction(),
                            sysUser.getSubordinateEvaluationGrowthPotential()
                    )
                    .filter(Objects::nonNull) // 过滤null值
                    .filter(str -> !str.trim().isEmpty()) // 过滤空字符串
                    .collect(Collectors.toList());
            return findMostFrequentElement(list);
        } else {
            // 组织
            List<SysUser> sysUserList = userMapper.selectUserByDeptId(dto.getDeptId());
            sysUserList = sysUserList.stream().filter(item -> item.getRoles().stream().anyMatch(sysRole -> RoleTypeEnum.banzuzhang.getCode().equals(sysRole.getRoleKey()) || RoleTypeEnum.SecurityCheck.getCode().equals(sysRole.getRoleKey()))).collect(Collectors.toList());
            List<String> list = sysUserList.stream()
                    .flatMap(sysUser -> Stream.of(
                            sysUser.getSelfAssessmentPersonalityTrait(),
                            sysUser.getSelfAssessmentCapabilityPerformance(),
                            sysUser.getSelfAssessmentInterpersonalInteraction(),
                            sysUser.getSelfAssessmentGrowthPotential(),
                            sysUser.getColleagueCommentsPersonalityTrait(),
                            sysUser.getColleagueCommentsCapabilityPerformance(),
                            sysUser.getColleagueCommentsInterpersonalInteraction(),
                            sysUser.getColleagueCommentsGrowthPotential(),
                            sysUser.getSuperiorEvaluationPersonalityTrait(),
                            sysUser.getSuperiorEvaluationCapabilityPerformance(),
                            sysUser.getSuperiorEvaluationInterpersonalInteraction(),
                            sysUser.getSuperiorEvaluationGrowthPotential(),
                            sysUser.getSubordinateEvaluationPersonalityTrait(),
                            sysUser.getSubordinateEvaluationCapabilityPerformance(),
                            sysUser.getSubordinateEvaluationInterpersonalInteraction(),
                            sysUser.getSubordinateEvaluationGrowthPotential()
                    ))
                    .filter(Objects::nonNull) // 过滤null值
                    .filter(str -> !str.trim().isEmpty()) // 过滤空字符串
                    .collect(Collectors.toList());
            return findMostFrequentElement(list);
        }
    }

    /**
     * 查询用户列表
     *
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectUserAll() {
        return userMapper.selectUserAll();
    }

    /**
     * 获取最频繁的元素
     */
    private String findMostFrequentElement(List<String> list) {
        // 列表为空
        if (CollUtil.isEmpty(list)) {
            return null;
        }

        // 统计每个元素的出现次数
        Map<String, Long> frequencyMap = list.stream()
                .collect(Collectors.groupingBy(
                        e -> e,
                        Collectors.counting()
                ));

        // 找到最大出现次数
        Long maxFrequency = frequencyMap.values().stream()
                .max(Long::compareTo)
                .orElse(0L);

        // 获取第一个出现次数等于最大次数的元素
        return frequencyMap.entrySet().stream()
                .filter(entry -> entry.getValue().equals(maxFrequency))
                .map(Map.Entry::getKey)
                .findFirst()
                .orElse(null);
    }

    /**
     * 首页-用户信息
     *
     * @return 首页-用户信息
     */
    @Override
    public List<LargeScreenHomePageUserInfoSqlDto> homePageUserInfo() {
        return userMapper.homePageUserInfo();
    }

    /**
     * 重置指定部门中指定角色的人员的指定岗位
     */
    @Override
    public int resetUserPostByDept(ResetUserPostDto resetUserPostDto) {
        // 获取指定部门下指定角色的用户
        List<Long> userIdList = new ArrayList<>();
        resetUserPostDto.getDeptIdList().forEach(deptId -> {
            List<SysUser> sysUserList = selectUserListByRoleKeyAndDeptId(resetUserPostDto.getRoleKeyList(), deptId);
            List<Long> userIds = sysUserList.stream().map(SysUser::getUserId).collect(Collectors.toList());
            userIdList.addAll(userIds);
        });
        // 获取指定岗位
        List<Long> postIdList = new ArrayList<>();
        resetUserPostDto.getPostParentIdList().forEach(postParentId -> {
            List<SysPost> sysPostList = postMapper.selectPostByParentId(postParentId);
            List<Long> postIds = sysPostList.stream().map(SysPost::getPostId).collect(Collectors.toList());
            postIdList.addAll(postIds);
        });
        // 更新用户岗位
        for (Long userId : userIdList) {
            // 创建数据
            SysUser user = new SysUser();
            user.setUserId(userId);
            user.setPostIds(postIdList.toArray(new Long[0]));
            // 删除用户与岗位关联
            userPostMapper.deleteUserPostByUserId(userId);
            // 新增用户与岗位管理
            insertUserPost(user);
        }
        return 1;
    }

    /**
     * 查询用户列表
     *
     * @param dto 查询用户列表参数
     * @return 用户信息集合
     */
    @Override
    public List<SysUser> selectUserListByDeptIdAndRoleKeyListAndUserName(SysUserConditionDto dto) {
        return userMapper.selectUserListByDeptIdAndRoleKeyListAndUserName(dto.getDeptId(), dto.getRoleKeyList(), dto.getNickName());
    }

    @Override
    public List<LargeScreenHomePageUserInfoSqlDto> homePageUserInfoByBrigadeId(Long brigadeId) {
        return userMapper.homePageUserInfoByBrigadeId(brigadeId);
    }

    @Override
    public List<LargeScreenHomePageUserInfoSqlDto> homePageUserInfoByDepartmentId(Long departmentId) {
        return userMapper.homePageUserInfoByDepartmentId(departmentId);
    }
}
