package com.gkhy.hazmat.system.service.impl; import cn.hutool.core.codec.Base64; import cn.hutool.core.util.ObjectUtil; import com.alibaba.excel.EasyExcel; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.gkhy.hazmat.common.annotation.DataScope; import com.gkhy.hazmat.common.api.CommonPage; import com.gkhy.hazmat.common.api.CommonResult; import com.gkhy.hazmat.common.constant.CacheConstant; import com.gkhy.hazmat.common.constant.UserConstant; import com.gkhy.hazmat.common.domain.entity.SysUser; import com.gkhy.hazmat.common.enums.UserStatus; import com.gkhy.hazmat.common.enums.UserTypeEnum; import com.gkhy.hazmat.common.exception.ApiException; import com.gkhy.hazmat.common.utils.*; import com.gkhy.hazmat.system.domain.SysUserRole; import com.gkhy.hazmat.system.mapper.SysUserMapper; import com.gkhy.hazmat.system.mapper.SysUserRoleMapper; import com.gkhy.hazmat.system.service.SysConfigService; import com.gkhy.hazmat.system.service.SysUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.validation.Validator; import java.io.IOException; import java.util.*; import java.util.concurrent.TimeUnit; /** *

* 用户表 服务实现类 *

* * @author kzy * @since 2023-10-17 14:26:29 */ @Service public class SysUserServiceImpl extends ServiceImpl implements SysUserService { @Autowired private RedisUtils redisUtils; @Autowired private SysConfigService configService; @Autowired private Validator validator; @Autowired private SysUserRoleMapper roleMapper; @Override public CommonPage selectUserList(SysUser user) { SysUser currentUser= SecurityUtils.getLoginUser().getUser(); List users=new ArrayList<>(); if(currentUser.getUserType().equals(UserTypeEnum.COMPANY_USER.getCode())){ user.setCompanyId(currentUser.getCompanyId()); Map paramsMap=new HashMap<>(); paramsMap.put("userType",currentUser.getUserType()); user.setParams(paramsMap); } PageUtils.startPage(); users=baseMapper.userList(user); return CommonPage.restPage(users); } @Override public SysUser selectUserByUsername(String username) { String key=redisUtils.generateKey(CacheConstant.SYS_USER_NAME+username); SysUser sysUser =null; if(redisUtils.hasKey(key)){ sysUser= (SysUser) redisUtils.get(key); }else { sysUser = baseMapper.getUserByUsername(username); redisUtils.set(key,sysUser,10, TimeUnit.MINUTES); } return sysUser; } public void delCacheByUsername(String username){ String key=redisUtils.generateKey(CacheConstant.SYS_USER_NAME+username); redisUtils.del(key); } @Override public SysUser selectUserByPhone(String phone) { return baseMapper.getUserByPhone(phone); } @Override public SysUser selectUserById(Long userId) { SysUser user = baseMapper.getUserById(userId); SysUser currentUser=SecurityUtils.getLoginUser().getUser(); if(currentUser.getUserType().equals(UserTypeEnum.NORMAL_USER.getCode())&&user!=null){ if(!Objects.equals(user.getId(), currentUser.getId())){ throw new ApiException("无权限查重其他用户信息"); } } return user; } @Override public int deleteUserById(Long userId) { SysUser user=checkUserDataScope(userId); delCacheByUsername(user.getUsername()); return baseMapper.deleteUserById(userId); } @Override public int addUser(SysUser user) { checkRequestData(user); checkUserAllowed(user); user.setCreateBy(SecurityUtils.getUsername()); user.setPassword(SecurityUtils.encryptPassword(Base64.decodeStr(user.getPassword()))); int row=baseMapper.insert(user); SysUserRole ur = new SysUserRole(); ur.setUserId(user.getId()); ur.setRoleId(100L); roleMapper.insert(ur); if(row<1){ throw new ApiException("新增用户失败"); } return row; } @Override public int updateUser(SysUser user) { checkRequestData(user); checkUserAllowed(user); user.setUpdateBy(SecurityUtils.getUsername()); user.setPassword(null); int row=baseMapper.updateById(user); if(row<1){ throw new ApiException("更新用户信息失败"); } delCacheByUsername(user.getUsername()); return row; } public void checkRequestData(SysUser user){ if(!(user.getUserType().equals(UserTypeEnum.SYSTEM_USER.getCode()) || user.getUserType().equals(UserTypeEnum.CHECK_USER.getCode()) )&&user.getCompanyId()==null){ throw new ApiException("所属公司不能为空"); } if(!checkUsernameUnique(user)){ throw new ApiException("登录账号已存在"); } if(StringUtils.isNotBlank(user.getPhone())&&!checkPhoneUnique(user)){ throw new ApiException("手机号已存在"); } } @Override public int updateUserStatus(SysUser user) { SysUser existUser=checkUserDataScope(user.getId()); SysUser su=new SysUser().setId(user.getId()).setStatus(user.getStatus()); su.setUpdateBy(SecurityUtils.getUsername()); int row= baseMapper.updateById(su); if(row<1){ throw new ApiException("更新用户状态失败"); } delCacheByUsername(existUser.getUsername()); return row; } @Override public boolean resetUserPwd(SysUser user) { SysUser existUser=checkUserDataScope(user.getId()); SysUser su=new SysUser().setId(user.getId()).setPassword(SecurityUtils.encryptPassword(Base64.decodeStr(user.getPassword()))); su.setUpdateBy(SecurityUtils.getUsername()); delCacheByUsername(existUser.getUsername()); return updateById(su); } @Override public boolean checkUsernameUnique(SysUser user) { Long userId = user.getId()==null? -1L : user.getId(); SysUser info = baseMapper.checkLoginNameUnique(user.getUsername()); if (info!=null && info.getId().longValue() != userId.longValue()) { return UserConstant.NOT_UNIQUE; } return UserConstant.UNIQUE; } @Override public boolean checkPhoneUnique(SysUser user) { Long userId = user.getId()==null ? -1L : user.getId(); SysUser info = baseMapper.checkPhoneUnique(user.getPhone()); if (info!=null && info.getId().longValue() != userId.longValue()) { return UserConstant.NOT_UNIQUE; } return UserConstant.UNIQUE; } @Override public void checkUserAllowed(SysUser user) { SysUser currentUser=SecurityUtils.getLoginUser().getUser(); Integer currentUserType=currentUser.getUserType(); Integer userType=user.getUserType(); if(currentUserType.equals(UserTypeEnum.SYSTEM_USER.getCode())){ if(!userType.equals(UserTypeEnum.COMPANY_USER.getCode())&&!userType.equals(UserTypeEnum.SYSTEM_USER.getCode())&&!userType.equals(UserTypeEnum.CHECK_USER.getCode())){ throw new ApiException("管理员只能操作管理员和企业级用户"); } }else if(user.getId()!=null&& user.getId().equals(currentUser.getId())){ return; }else if(userType<=currentUserType){ throw new ApiException("没有权限操作高级用户类型的用户"); }else{ if(user.getCompanyId()!=null){ if(!user.getCompanyId().equals(currentUser.getCompanyId())){ throw new ApiException("无权限操作其他公司用户"); } } } } @Override public SysUser checkUserDataScope(Long userId) { if(userId==null){ throw new ApiException("用户id为空!"); } SysUser user = getById(userId); if (ObjectUtil.isNull(user)) { throw new ApiException("用户数据不存在!"); } checkUserAllowed(user); return user; } @Override @DataScope(deptAlias = "d", userAlias = "u") public List selectAllocatedList(SysUser user) { return baseMapper.selectAllocatedList(user); } /** * 根据条件分页查询未分配用户角色列表 * * @param user 用户信息 * @return 用户信息集合信息 */ @Override @DataScope(deptAlias = "d", userAlias = "u") public List selectUnallocatedList(SysUser user) { return baseMapper.selectUnallocatedList(user); } @Override public void insertUserAuth(Long userId, Long[] roleIds) { roleMapper.deleteUserRoleByUserId(userId); insertUserRole(userId, roleIds); } @Override public Integer importUserExcel(MultipartFile file) throws IOException { if(ObjectUtil.isEmpty(file)){ throw new ApiException("上传文件不能为空"); } SysUser currentUser = SecurityUtils.getLoginUser().getUser(); List> dataList = EasyExcel.read(file.getInputStream()) .sheet() .doReadSync(); if(dataList == null || dataList.isEmpty()){ throw new ApiException("导入数据不能为空"); } List userList = new ArrayList<>(); int rowIndex = 1; for(Map data : dataList){ rowIndex++; String username = data.get(0); String name = data.get(1); String sexStr = data.get(2); String password = data.get(3); String phone = data.get(4); validateUserData(username, name, sexStr, password, phone, rowIndex); if(!checkUsernameUnique(new SysUser().setUsername(username))){ throw new ApiException("第" + rowIndex + "行登录账号[" + username + "]已存在"); } if(!checkPhoneUnique(new SysUser().setPhone(phone))){ throw new ApiException("第" + rowIndex + "行手机号[" + phone + "]已存在"); } SysUser user = new SysUser(); user.setUsername(username.trim()); user.setName(name.trim()); user.setPhone(phone.trim()); Integer sex = parseSex(sexStr, rowIndex); user.setSex(sex); user.setUserType(UserTypeEnum.NORMAL_USER.getCode()); user.setStatus(UserStatus.OK.getCode()); if(!currentUser.getUserType().equals(UserTypeEnum.SYSTEM_USER.getCode()) && !currentUser.getUserType().equals(UserTypeEnum.CHECK_USER.getCode())){ user.setCompanyId(currentUser.getCompanyId()); } String encryptedPassword = SecurityUtils.encryptPassword(password.trim()); user.setPassword(encryptedPassword); user.setCreateBy(currentUser.getUsername()); userList.add(user); } if(!userList.isEmpty()){ if(userList.size() > 100){ int pageSize = 100; while (true){ List users = userList.subList(0, Math.min(userList.size(), pageSize)); saveBatch(users); for(SysUser savedUser : users){ SysUserRole ur = new SysUserRole(); ur.setUserId(savedUser.getId()); ur.setRoleId(100L); roleMapper.insert(ur); } if(users.size() < pageSize){ break; } userList = userList.subList(pageSize, userList.size()); if(userList.isEmpty()){ break; } } }else{ saveBatch(userList); for(SysUser savedUser : userList){ SysUserRole ur = new SysUserRole(); ur.setUserId(savedUser.getId()); ur.setRoleId(100L); roleMapper.insert(ur); } } } return userList.size(); } private void validateUserData(String username, String name, String sexStr, String password, String phone, int rowIndex){ if(StringUtils.isBlank(username)){ throw new ApiException("第" + rowIndex + "行登录账号为空"); } if(StringUtils.isBlank(name)){ throw new ApiException("第" + rowIndex + "用户名称为空"); } if(StringUtils.isBlank(password)){ throw new ApiException("第" + rowIndex + "行密码为空"); } if(StringUtils.isBlank(phone)){ throw new ApiException("第" + rowIndex + "行手机号码为空"); } if(phone.length() != 11){ throw new ApiException("第" + rowIndex + "行手机号长度不正确"); } if(!phone.matches("^[1][3,4,5,6,7,8,9][0-9]{9}$")){ throw new ApiException("第" + rowIndex + "行手机号码格式有误"); } } private Integer parseSex(String sexStr, int rowIndex){ if(StringUtils.isBlank(sexStr)){ return 2; } String trimmedSex = sexStr.trim(); if("男".equals(trimmedSex) || "0".equals(trimmedSex)){ return 0; }else if("女".equals(trimmedSex) || "1".equals(trimmedSex)){ return 1; }else{ return 2; } } /** * 新增用户角色信息 * * @param userId 用户ID * @param roleIds 角色组 */ public void insertUserRole(Long userId, Long[] roleIds) { if (StringUtils.isNotEmpty(roleIds)) { // 新增用户与角色管理 List list = new ArrayList(roleIds.length); for (Long roleId : roleIds) { SysUserRole ur = new SysUserRole(); ur.setUserId(userId); ur.setRoleId(roleId); list.add(ur); } roleMapper.batchUserRole(list); } } }