package cn.com.qmth.mps.service.impl; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringEscapeUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.interceptor.TransactionAspectSupport; import org.springframework.web.multipart.MultipartFile; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.qmth.boot.core.collection.PageResult; import com.qmth.boot.core.exception.StatusException; import com.qmth.boot.tools.excel.ExcelReader; import com.qmth.boot.tools.excel.enums.ExcelType; import com.qmth.boot.tools.excel.model.DataMap; import cn.com.qmth.mps.bean.CourseInfo; import cn.com.qmth.mps.bean.User; import cn.com.qmth.mps.dao.UserDao; import cn.com.qmth.mps.entity.UserEntity; import cn.com.qmth.mps.enums.Role; import cn.com.qmth.mps.service.SchoolService; import cn.com.qmth.mps.service.UserCourseRelationService; import cn.com.qmth.mps.service.UserService; import cn.com.qmth.mps.util.ByteUtil; import cn.com.qmth.mps.util.PageUtil; import cn.com.qmth.mps.util.SHA256; import cn.com.qmth.mps.vo.user.UserDomain; import cn.com.qmth.mps.vo.user.UserQuery; import cn.com.qmth.mps.vo.user.UserVo; @Service public class UserServiceImpl extends ServiceImpl implements UserService { private static final String DEFAULT_PASSWD = "123456"; @Autowired private UserCourseRelationService userCourseRelationService; @Autowired private SchoolService schoolService; @Override public UserEntity getByLoginName(String phone) { QueryWrapper wrapper = new QueryWrapper<>(); LambdaQueryWrapper lw = wrapper.lambda(); lw.eq(UserEntity::getLoginName, phone); return this.getOne(wrapper); } @Transactional @Override public void saveUser(UserDomain domain, User user) { if (domain.getSchoolId() == null) { throw new StatusException("学校不能为空"); } if (!user.getRole().equals(Role.SUPER_ADMIN) && !user.getSchoolId().equals(domain.getSchoolId())) { throw new StatusException("没有权限"); } if (StringUtils.isBlank(domain.getName())) { throw new StatusException("姓名不能为空"); } if (StringUtils.isBlank(domain.getLoginName())) { throw new StatusException("登录名不能为空"); } if (domain.getId() == null && StringUtils.isBlank(domain.getPasswd())) { throw new StatusException("密码不能为空"); } if (domain.getRole() == null) { throw new StatusException("角色不能为空"); } if (domain.getRole().equals(Role.SUPER_ADMIN)) { throw new StatusException("不能新增超管"); } if (!domain.getRole().equals(Role.SECTION_LEADER) && CollectionUtils.isNotEmpty(domain.getCourse())) { throw new StatusException("只有科组长可关联科目"); } UserEntity ue = null; if (domain.getId() != null) { ue = this.getById(domain.getId()); if (ue == null) { throw new StatusException("未找到用户"); } if (ue.getRoleId().equals(Role.SUPER_ADMIN.getId())) { throw new StatusException("不能编辑超管"); } } else { if (getByLoginName(domain.getLoginName()) != null) { throw new StatusException("登录名已存在"); } ue = new UserEntity(); ue.setPassword(ByteUtil.toHexAscii(SHA256.encode(domain.getPasswd()))); ue.setSchoolId(user.getSchoolId()); ue.setEnable(true); ue.setLoginName(domain.getLoginName()); } ue.setName(domain.getName()); ue.setRoleId(domain.getRole().getId()); this.saveOrUpdate(ue); if (CollectionUtils.isNotEmpty(domain.getCourse())) { Set set = new HashSet<>(); for (String s : domain.getCourse()) { set.add(s); } if (set.size() != domain.getCourse().size()) { throw new StatusException("科目代码不能重复"); } userCourseRelationService.saveCourse(ue.getSchoolId(), ue.getId(), domain.getCourse()); } else { userCourseRelationService.removeCourse(ue.getId()); } } @Transactional @Override public List importUser(Long schoolId, User user, MultipartFile file) { if (!user.getRole().equals(Role.SUPER_ADMIN) && !user.getSchoolId().equals(schoolId)) { throw new StatusException("没有权限"); } InputStream inputStream = null; try { inputStream = file.getInputStream(); List lineList = ExcelReader.create(ExcelType.XLSX, inputStream, 0).getDataMapList(); if (CollectionUtils.isEmpty(lineList)) { throw new StatusException("Excel无内容"); } if (1001 < lineList.size()) { throw new StatusException("数据行数不能超过1000"); } List failRecords = new ArrayList<>(); List userList = new ArrayList<>(); for (int i = 0; i < lineList.size(); i++) { DataMap line = lineList.get(i); StringBuilder msg = new StringBuilder(); UserDomain impuser = new UserDomain(); impuser.setSchoolId(schoolId); String name = trimAndNullIfBlank(line.getValue(0)); if (StringUtils.isBlank(name)) { msg.append(" 姓名不能为空"); } else if (name.length() > 20) { msg.append(" 姓名不能超过20个字符"); } impuser.setName(name); String loginname = trimAndNullIfBlank(line.getValue(1)); if (StringUtils.isBlank(loginname)) { msg.append(" 登录名不能为空"); } else if (loginname.length() > 20) { msg.append(" 登录名不能超过20个字符"); } impuser.setLoginName(loginname); String role = trimAndNullIfBlank(line.getValue(2)); if (StringUtils.isBlank(role)) { msg.append(" 角色名称不能为空"); } else if (Role.getByName(role) == null) { msg.append(" 角色名称错误"); } else if (Role.SUPER_ADMIN.equals(Role.getByName(role))) { msg.append(" 不能新建超级管理员"); } impuser.setRole(Role.getByName(role)); String coursecodes = trimAndNullIfBlank(line.getValue(3)); if (StringUtils.isNotBlank(coursecodes)) { impuser.setCourse(Arrays.asList(coursecodes.split(","))); } if (msg.length() > 0) { failRecords.add(newError(i + 1, msg.toString())); } else { userList.add(impuser); } } if (CollectionUtils.isNotEmpty(failRecords)) { return failRecords; } for (int i = 0; i < userList.size(); i++) { UserDomain cur = userList.get(i); cur.setPasswd(DEFAULT_PASSWD); try { saveUser(cur, user); } catch (StatusException e) { failRecords.add(newError(i + 1, e.getMessage())); } catch (Exception e) { failRecords.add(newError(i + 1, "系统异常")); log.error("用户导入系统异常", e); } } if (CollectionUtils.isNotEmpty(failRecords)) { TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } return failRecords; } catch (StatusException e) { throw e; } catch (Exception e) { throw new StatusException("系统错误", e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } private String trimAndNullIfBlank(String s) { if (StringUtils.isBlank(s)) { return null; } return s.trim(); } private String newError(int lineNum, String msg) { return "第" + lineNum + "行" + msg; } @Override public PageResult page(UserQuery query, User user) { if (query.getSchoolId() == null) { throw new StatusException("学校不能为空"); } if (!user.getRole().equals(Role.SUPER_ADMIN) && !user.getSchoolId().equals(query.getSchoolId())) { throw new StatusException("没有权限"); } IPage iPage = this.baseMapper.page(new Page(query.getPageNumber(), query.getPageSize()), query); if (CollectionUtils.isNotEmpty(iPage.getRecords())) { for (UserVo vo : iPage.getRecords()) { vo.setRole(Role.getById(vo.getRoleId())); if (vo.getRoleId().equals(Role.SECTION_LEADER.getId())) { List cs = userCourseRelationService.getCourses(vo.getId()); vo.setCourseCodes(cs.stream().map(m -> m.getCode()).collect(Collectors.toList())); } } } return PageUtil.of(iPage); } @Override public UserVo info(Long id) { UserEntity ue = this.getById(id); if (ue == null) { throw new StatusException("未找到用户信息"); } UserVo vo = new UserVo(); vo.setEnable(ue.getEnable()); vo.setId(ue.getId()); vo.setRoleId(ue.getRoleId()); vo.setRole(Role.getById(ue.getRoleId())); vo.setLoginName(ue.getLoginName()); vo.setName(ue.getName()); vo.setSchoolId(ue.getSchoolId()); vo.setSchoolName(schoolService.getById(ue.getSchoolId()).getName()); if (vo.getRoleId().equals(Role.SECTION_LEADER.getId())) { List cs = userCourseRelationService.getCourses(vo.getId()); vo.setCourseCodes(cs.stream().map(m -> m.getCode()).collect(Collectors.toList())); } return vo; } @Transactional @Override public void toggle(List ids, Boolean enable, User user) { UpdateWrapper wrapper = new UpdateWrapper<>(); LambdaUpdateWrapper lw = wrapper.lambda(); lw.set(UserEntity::getEnable, enable); lw.in(UserEntity::getId, ids); if (!user.getRole().equals(Role.SUPER_ADMIN)) { lw.eq(UserEntity::getSchoolId, user.getSchoolId()); } this.update(wrapper); } @Transactional @Override public void updatePass(String password, User accessUser) { if (!accessUser.getRole().equals(Role.SUPER_ADMIN)) { throw new StatusException("不能修改超级管理员"); } Long userId = accessUser.getId(); String realPassword = StringEscapeUtils.unescapeJava(password); byte[] bytes = SHA256.encode(realPassword); String encodePassword = ByteUtil.toHexAscii(bytes); UserEntity ue = this.getById(userId); if (ue == null) { throw new StatusException("未找到用户信息"); } ue.setPassword(encodePassword); this.updateById(ue); } @Transactional @Override public void resetPass(Long userId, String passwd, User user) { UserEntity ue = this.getById(userId); if (ue == null) { throw new StatusException("未找到用户信息"); } if (ue.getRoleId().equals(Role.SUPER_ADMIN.getId())) { throw new StatusException("不能修改超级管理员"); } if (!user.getRole().equals(Role.SUPER_ADMIN) && !user.getSchoolId().equals(ue.getSchoolId())) { throw new StatusException("没有权限"); } String pw = ByteUtil.toHexAscii(SHA256.encode(passwd)); UpdateWrapper wrapper = new UpdateWrapper<>(); LambdaUpdateWrapper lw = wrapper.lambda(); lw.set(UserEntity::getPassword, pw); lw.eq(UserEntity::getId, userId); this.update(wrapper); } @Override public UserVo myInfo(User user) { UserEntity ue = this.getById(user.getId()); if (ue == null) { throw new StatusException("未找到用户信息"); } UserVo vo = new UserVo(); vo.setEnable(ue.getEnable()); vo.setId(ue.getId()); vo.setRoleId(ue.getRoleId()); vo.setLoginName(ue.getLoginName()); vo.setName(ue.getName()); vo.setSchoolId(ue.getSchoolId()); vo.setSchoolName(schoolService.getById(ue.getSchoolId()).getName()); if (vo.getRoleId().equals(Role.SECTION_LEADER.getId())) { List cs = userCourseRelationService.getCourses(vo.getId()); if (CollectionUtils.isNotEmpty(cs)) { vo.setCourseCodes(cs.stream().map(m -> m.getCode()).collect(Collectors.toList())); vo.setCourseNames(cs.stream().map(m -> m.getCode() + "-" + m.getName()).collect(Collectors.toList())); } } return vo; } }