kaiyu
2021-03-18 333065f8d9b599b048668a0686ba2ee58944b0e4
screen-api/src/main/java/com/moral/api/service/impl/UserServiceImpl.java
@@ -1,9 +1,33 @@
package com.moral.api.service.impl;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.moral.api.entity.Group;
import com.moral.api.entity.Menu;
import com.moral.api.entity.Organization;
import com.moral.api.entity.User;
import com.moral.api.mapper.GroupMapper;
import com.moral.api.mapper.MenuMapper;
import com.moral.api.mapper.OrganizationMapper;
import com.moral.api.mapper.UserMapper;
import com.moral.api.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moral.util.AESUtils;
import com.moral.util.MD5Utils;
import com.moral.util.RegexUtils;
import com.moral.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
/**
@@ -17,4 +41,218 @@
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public User selectUserInfo(Map<String, Object> parameters) {
        return userMapper.selectUserInfo(parameters);
    }
    @Override
    public Map<String, Object> login(User user) {
        Map<String, Object> resultMap = new LinkedHashMap<>();
        //封装用户信息
        Map<String, Object> userInfo = new LinkedHashMap<>();
        List<Map<String, Object>> groups = new ArrayList<>();
        for (Group group : user.getGroups()) {
            HashMap<String, Object> groupMap = new HashMap<>();
            groupMap.put("groupId", group.getId());
            groupMap.put("groupName", group.getGroupName());
            groups.add(groupMap);
        }
        Organization organization = user.getOrganization();
        userInfo.put("userId", user.getId());
        userInfo.put("account", user.getAccount());
        userInfo.put("userName", user.getUserName());
        userInfo.put("expireTime", user.getExpireTime());
        userInfo.put("isAdmin", user.getIsAdmin());
        userInfo.put("organizationId", user.getOrganizationId());
        userInfo.put("organizationName", organization.getName());
        userInfo.put("locationLevel", organization.getLocationLevel());
        userInfo.put("groups", groups);
        userInfo.putAll(getMenus(user.getId()));
        try {
            //生成token,并存入redis
            String token = TokenUtils.getToken(user.getId().toString(), userInfo);
            resultMap.put("token", token);
        } catch (Exception e) {
            log.error("token生成异常:"+e.getMessage());
        }
        resultMap.putAll(userInfo);
        return resultMap;
    }
    //根据userId获取用户层级菜单
    private Map<String, Object> getMenus(int userId) {
        List<Menu> allMenus = menuMapper.selectUserMenu(userId);
        Map<String, Object> resultMap = new LinkedHashMap<>();
        //第一级菜单
        List<Menu> oneMenu = allMenus.stream()
                .filter(o -> o.getParentId().equals(0))
                .sorted(Comparator.comparing(Menu::getOrder))
                .collect(Collectors.toList());
        List<Map<String, Object>> newList = new ArrayList<>();
        //遍历一级菜单
        oneMenu.forEach(o -> {
            Map<String, Object> menuMap = new LinkedHashMap<>();
            menuMap.put("id", o.getId());
            menuMap.put("name", o.getName());
            menuMap.put("url", o.getUrl());
            menuMap.put("icon", o.getIcon());
            menuMap.put("menus", getMenusByRecursion(o, allMenus));
            newList.add(menuMap);
        });
        resultMap.put("menus", newList);
        return resultMap;
    }
    //获取用户层级菜单递归方法
    private List<Map<String, Object>> getMenusByRecursion(Menu menu, List<Menu> menus) {
        List<List<Map<String, Object>>> resultList = new ArrayList();
        Menu newMenu = new Menu();
        newMenu.setParentId(menu.getId());
        //筛选出下一级菜单信息
        List<Menu> nextLevelMenus = menus.stream()
                .filter(o -> o.getParentId().equals(menu.getId()))
                .collect(Collectors.toList());
        List<Map<String, Object>> list = new ArrayList<>();
        if (nextLevelMenus.size() > 0) {
            //遍历下一级菜单信息,并封装返回参数
            nextLevelMenus.forEach(o -> {
                Map<String, Object> menuMap = new LinkedHashMap<>();
                menuMap.put("id", o.getId());
                menuMap.put("name", o.getName());
                menuMap.put("url", o.getUrl());
                menuMap.put("icon", o.getIcon());
                //调用递归体
                menuMap.put("menus", getMenusByRecursion(o, menus));
                list.add(menuMap);
            });
            resultList.add(list);
        }
        return list;
    }
    @Override
    public Map<String, Object> addUser(User user, String token) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> currentUserInfo = (Map<String, Object>) TokenUtils.getUserInfoByToken(token);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", user.getAccount());
        if (userMapper.selectOne(queryWrapper) != null) {
            resultMap.put("msg", "账户名已存在");
            return resultMap;
        }
        //校验用户信息是否符合规则
        List<String> msgs = checkUserInfo(user);
        if (!msgs.isEmpty()) {
            resultMap.put("msg", msgs);
            return resultMap;
        }
        //密码加密
        String password = MD5Utils.saltMD5(user.getPassword());
        user.setPassword(password);
        user.setIsAdmin(false);
        user.setOrganizationId(Integer.parseInt(currentUserInfo.get("organizationId").toString()));
        //新增账户的过期时间
        Date userExpireTime = user.getExpireTime();
        //当前账户的过期时间
        Date expireTime = (Date) currentUserInfo.get("expireTime");
        if (userExpireTime == null || userExpireTime.getTime() > expireTime.getTime()) {
            user.setExpireTime(expireTime);
        }
        userMapper.insert(user);
        return resultMap;
    }
    @Override
    public Map<String, Object> deleteUser(int userId, String token) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> currentUserInfo = (Map<String, Object>) TokenUtils.getUserInfoByToken(token);
        if (!(boolean) currentUserInfo.get("isAdmin")) {
            resultMap.put("msg", "没有权限");
        } else {
            User user = new User();
            user.setId(userId);
            user.setIsDelete("1");
            userMapper.updateById(user);
        }
        return resultMap;
    }
    @Override
    public Map<String, Object> updateUser(User user, String token) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> currentUserInfo = (Map<String, Object>) TokenUtils.getUserInfoByToken(token);
        if (!(boolean) currentUserInfo.get("isAdmin")) {
            resultMap.put("msg", "没有权限");
            return resultMap;
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", user.getAccount());
        if (userMapper.selectOne(queryWrapper) != null) {
            resultMap.put("msg", "账户已存在");
            return resultMap;
        }
        //校验用户信息是否符合规则
        List<String> msgs = checkUserInfo(user);
        if (!msgs.isEmpty()) {
            resultMap.put("msg", msgs);
            return resultMap;
        }
        //密码Md5加密
        user.setPassword(MD5Utils.saltMD5(user.getPassword()));
        userMapper.updateById(user);
        return resultMap;
    }
    @Override
    public Map<String, Object> getUsers(Map<String, Object> parameters) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> currentUserInfo = (Map<String, Object>) TokenUtils.getUserInfoByToken(parameters.get("token").toString());
        if (!(boolean) currentUserInfo.get("isAdmin")) {
            resultMap.put("msg", "没有权限");
            return resultMap;
        }
        if (!parameters.containsKey("userId")) {
            parameters.put("orgId", currentUserInfo.get("organizationId"));
        }
        List<Map<String, Object>> users = userMapper.selectUsers(parameters);
        resultMap.put("users", users);
        return resultMap;
    }
    private List<String> checkUserInfo(User user) {
        List<String> msgs = new ArrayList<>();
        //验证账户
        if (!RegexUtils.checkAccount(user.getAccount())) {
            msgs.add("账户格式不正确");
        }
        //验证密码
        if (!RegexUtils.checkPassword(user.getPassword())) {
            msgs.add("密码格式不正确");
        }
        //验证邮箱
        if (user.getEmail() != null) {
            if (!RegexUtils.checkEmail(user.getEmail())) {
                msgs.add("邮箱格式不正确");
            }
        }
        //验证手机号
        if (user.getMobile() != null) {
            if (!RegexUtils.checkMobile(user.getMobile())) {
                msgs.add("手机号格式不正确");
            }
        }
        return msgs;
    }
}