jinpengyong
2023-11-08 31c65cd4f338256b76efebdb2f1f29deb170969f
screen-api/src/main/java/com/moral/api/service/impl/UserServiceImpl.java
@@ -1,40 +1,50 @@
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.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.entity.UserGroup;
import com.moral.api.mapper.MenuMapper;
import com.moral.api.mapper.UserGroupMapper;
import com.moral.api.mapper.UserMapper;
import com.moral.api.pojo.UserBo;
import com.moral.api.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moral.api.config.Interceptor.UserHelper;
import com.moral.api.entity.*;
import com.moral.api.mapper.*;
import com.moral.api.pojo.bo.UserBO;
import com.moral.api.pojo.enums.AllocationApproveEnum;
import com.moral.api.pojo.enums.FileTableEnum;
import com.moral.api.pojo.enums.StateEnum;
import com.moral.api.pojo.enums.SysDictTypeEnum;
import com.moral.api.pojo.vo.file.FileVo;
import com.moral.api.pojo.vo.user.QxUser;
import com.moral.api.service.FileTableService;
import com.moral.api.service.ResponsibilityUnitService;
import com.moral.api.service.UserService;
import com.moral.api.utils.OperationLogUtils;
import com.moral.api.utils.WechatUtils;
import com.moral.api.vo.WxMssVo;
import com.moral.constant.Constants;
import com.moral.constant.ResponseCodeEnum;
import com.moral.util.AESUtils;
import com.moral.util.MD5Utils;
import com.moral.util.RegexUtils;
import com.moral.util.TokenUtils;
import com.moral.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;
/**
 * <p>
@@ -45,6 +55,7 @@
 * @since 2021-03-09
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
@@ -56,17 +67,261 @@
    @Autowired
    private UserGroupMapper userGroupMapper;
    @Autowired
    private UserLogMapper userLogMapper;
    @Autowired
    private FileTableService fileTableService;
    @Autowired
    private OperationLogUtils operationLogUtils;
    @Autowired
    private ResponsibilityUnitMapper responsibilityUnitMapper;
    @Autowired
    private ResponsibilityUnitService responsibilityUnitService;
    @Value("${AES.KEY}")
    private String AESKey;
    @Override
    public UserBo selectUserInfo(Map<String, Object> parameters) {
    public UserBO selectUserInfo(Map<String, Object> parameters) {
        return userMapper.selectUserInfo(parameters);
    }
    /**
     * 小程序登陆
     * @param parameters
     * @return
     */
    @Override
    @Transactional
    public Map<String, Object> loginSmallRoutine(Map<String, Object> parameters) {
        UserBO userBo = selectUserInfo(parameters);
        String openId = parameters.get("openId").toString();
        Map<String, Object> result = new HashMap<>();
        //校验账户
        if (userBo == null) {
            result.put("code", ResponseCodeEnum.ACCOUNT_NOT_EXIST.getCode());
            result.put("msg", ResponseCodeEnum.ACCOUNT_NOT_EXIST.getMsg());
            return result;
        }
        //校验是否删除
        if (Constants.DELETE.equals(userBo.getIsDelete())) {
            result.put("code", ResponseCodeEnum.ACCOUNT_IS_DELETE.getCode());
            result.put("msg", ResponseCodeEnum.ACCOUNT_IS_DELETE.getMsg());
            return result;
        }
        ResponsibilityUnit responsibilityUnit = responsibilityUnitMapper.selectById(userBo.getUnitId());
        List<Integer> list = responsibilityUnitMapper.selectCodeList(SysDictTypeEnum.SYS_DEVICE.value, userBo.getId());
        //封装用户信息
        Map<String, Object> userInfo = new LinkedHashMap<>();
        userInfo.put("userId", userBo.getId());
        userInfo.put("account", userBo.getAccount());
        userInfo.put("userName", userBo.getUserName());
        userInfo.put("email", userBo.getEmail());
        userInfo.put("mobile", userBo.getMobile());
        userInfo.put("unitId",userBo.getUnitId());
        userInfo.put("unName",Objects.nonNull(responsibilityUnit)&&Objects.nonNull(responsibilityUnit.getAreaName())?responsibilityUnit.getAreaName():"未选择责任单位");
        userInfo.put("wechat", userBo.getWechat());
        userInfo.put("expireTime", DateUtils.dateToDateString(userBo.getExpireTime()));
        userInfo.put("isAdmin", userBo.getIsAdmin());
        userInfo.put("organizationId",userBo.getOrganizationId());
        userInfo.put("openid", openId);
        try {
            //生成token,并存入redis
            String token = TokenUtils.getTokenApp(new StringBuffer("00").append(userBo.getId().toString()).toString(),userInfo);
            result.put("token", token);
            result.put("userName", userBo.getUserName());
            result.put("unitId",userBo.getUnitId());
            result.put("userId", userBo.getId());
            result.put("account", userBo.getAccount());
            List<FileVo> listFile =  fileTableService.list(userBo.getId(), FileTableEnum.APP_ALLOCATION.value);
            result.put("file", CollectionUtils.isNotEmpty(listFile)?listFile.get(0):new FileVo());
            result.put("unName",Objects.nonNull(responsibilityUnit)&&Objects.nonNull(responsibilityUnit.getUnitName())?responsibilityUnit.getUnitName():"管理员登陆");
            result.put("device",ObjectUtils.isEmpty(list)? StateEnum.NOT_EFFECTIVE.value :StateEnum.TAKE_EFFECT.value);
        } catch (Exception e) {
            log.error("token生成异常:" + e.getMessage());
            result.put("code", ResponseCodeEnum.TOKEN_CREATE_ERROR.getCode());
            result.put("msg", ResponseCodeEnum.TOKEN_CREATE_ERROR.getMsg());
            return result;
        }
        sysLog("登陆了用户:" + userBo.getAccount()+";openId:"+openId,userBo);
        //添加openId到user表中
        User user = userMapper.selectById(userBo.getId());
        user.setOpenId(openId);
        userMapper.updateById(user);
        return result;
    }
    @Override
    public Map<String, Object> wxLogin(String code) {
        Map<String, Object> result = new HashMap<>();
        // 用户非敏感信息:rawData
        // 签名:signature
//        JSONObject rawDataJson = JSON.parseObject(rawData);
        // 1.接收小程序发送的code
        // 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
        JSONObject SessionKeyOpenId = WechatUtils.getSessionKeyOrOpenId(code);
        // 3.接收微信接口服务 获取返回的参数
        String openid = SessionKeyOpenId.getString("openid");
//        String sessionKey = SessionKeyOpenId.getString("session_key");
        // 4.校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
//        String signature2 = DigestUtils.sha1Hex(rawData + sessionKey);
//        if (!signature.equals(signature2)) {
//           return ResultMessage.ok().message("签名校验失败");
//            return ResultMessage.ok("签名校验失败");
//            throw new BusinessException("签名校验失败");
//        }
        // 5.根据返回的User实体类,判断用户是否是新用户,是的话,将用户信息存到数据库;
        LambdaQueryWrapper<User> lqw = Wrappers.lambdaQuery();
        lqw.eq(User::getOpenId, openid);
        User user = userMapper.selectOne(lqw);
        if (user == null) {
            result.put("code", ResponseCodeEnum.USER_NOT_EXIST.getCode());
            result.put("msg", ResponseCodeEnum.USER_NOT_EXIST.getMsg());
            result.put("openId",openid);
            return result;
            // 用户信息入库
//            String nickName = rawDataJson.getString("nickName");
//            String avatarUrl = rawDataJson.getString("avatarUrl");
        }
        Map<String, Object> userInfo = new LinkedHashMap<>();
        userInfo.put("userId", user.getId());
        userInfo.put("account", user.getAccount());
        userInfo.put("userName", user.getUserName());
        userInfo.put("email", user.getEmail());
        userInfo.put("mobile", user.getMobile());
        userInfo.put("unitId",user.getUnitId());
//        userInfo.put("unName",user.getAreaName());
        userInfo.put("organizationId",user.getOrganizationId());
        userInfo.put("wechat", user.getWechat());
        userInfo.put("expireTime", DateUtils.dateToDateString(user.getExpireTime()));
        userInfo.put("isAdmin", user.getIsAdmin());
        ResponsibilityUnit responsibilityUnit = responsibilityUnitMapper.selectById(user.getUnitId());
        List<Integer> list = responsibilityUnitMapper.selectCodeList(SysDictTypeEnum.SYS_DEVICE.value, user.getId());
        try {
            //生成token,并存入redis
            String token = TokenUtils.getTokenApp(new StringBuffer("00").append(user.getId().toString()).toString(),userInfo);
            result.put("token", token);
            result.put("userName", user.getUserName());
            result.put("unitId",user.getUnitId());
            List<FileVo> listFile =  fileTableService.list(user.getId(), FileTableEnum.APP_ALLOCATION.value);
            result.put("file", CollectionUtils.isNotEmpty(listFile)?listFile.get(0):new FileVo());
            result.put("userId", user.getId());
            result.put("account", user.getAccount());
            result.put("device",ObjectUtils.isEmpty(list)? StateEnum.NOT_EFFECTIVE.value : StateEnum.TAKE_EFFECT.value);
            result.put("unName",Objects.nonNull(responsibilityUnit)&&Objects.nonNull(responsibilityUnit.getUnitName())?responsibilityUnit.getUnitName():"管理员登陆");
            result.put("openId",openid);
        } catch (Exception e) {
            log.error("token生成异常:" + e.getMessage());
            result.put("code", ResponseCodeEnum.TOKEN_CREATE_ERROR.getCode());
            result.put("msg", ResponseCodeEnum.TOKEN_CREATE_ERROR.getMsg());
            return result;
        }
        result.put("code", ResponseCodeEnum.SUCCESS.getCode());
        result.put("msg", ResponseCodeEnum.SUCCESS.getMsg());
        sysLog("登陆了用户:" + user.getAccount()+" ;openId:"+openid,user);
        return result;
    }
    @Override
    public boolean updateUserId(Integer userId) {
        User user = userMapper.selectById(userId);
        user.setOpenId("0");
        userMapper.updateById(user);
        sysLog(userId+"退出了小程序",user);
        return true;
    }
    /**
     * 小程序推送
     * @param appAllocationPushUserCond
     */
    @Override
    @Async
    public void pushOneUser(Allocation appAllocationPushUserCond) {
        QxUser currentUser = UserHelper.getCurrentUser();
        ResponsibilityUnit responsibilityUnit = responsibilityUnitMapper.selectById(appAllocationPushUserCond.getUnitId());
        Integer areaCode = responsibilityUnit.getAreaCode();
        List<ResponsibilityUnit> responsibilityUnits = responsibilityUnitService.selectAreaUnit(areaCode.toString().length()>6?responsibilityUnit.getParentCode():responsibilityUnit.getAreaCode());
        //获取unitid
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getIsDelete,Constants.NOT_DELETE);
        Integer state = appAllocationPushUserCond.getState();
        if (state==20){
            wrapper.eq(User::getUnitId,appAllocationPushUserCond.getUnitId());
        }else {
            wrapper.eq(User::getUnitId,ObjectUtils.isEmpty(responsibilityUnits)?0:responsibilityUnits.get(0).getUnitId());
        }
        List<User> users = userMapper.selectList(wrapper);
        if (ObjectUtils.isEmpty(users)){
            return;
        }
        String dateString = DateUtils.dateToDateString(appAllocationPushUserCond.getEscalationTime(),"MM月dd日");
        //这里简单起见我们每次都获取最新的access_token(时间开发中,应该在access_token快过期时再重新获取)
        //小程序订阅
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + WechatUtils.getAccessToken();
        //发送消息
        for (User user : users) {
            if (user.getId().equals(currentUser.getUserId())){
                continue;
            }
            RestTemplate restTemplate = new RestTemplate();
            //拼接推送的模版
            WxMssVo wxMssVo = new WxMssVo();
            wxMssVo.setTouser(user.getOpenId());//用户的openid(要发送给那个用户,通常这里应该动态传进来的)
            wxMssVo.setTemplate_id("YNqUZ1MgMvwY3G-NENVbcmIBR5dUotSdnwcz96CWrho");//订阅消息模板id
            wxMssVo.setLang("zh_CN");
            wxMssVo.setMiniprogramState("formal");
            wxMssVo.setPage("pages/index/index");
            Map<String, Object> m = new HashMap<>();
            HashMap<String, Object> map1 = new HashMap<>();
            HashMap<String, Object> map2 = new HashMap<>();
            HashMap<String, Object> map3 = new HashMap<>();
            HashMap<String, Object> map4 = new HashMap<>();
            map1.put("value",responsibilityUnit.getUnitName()+dateString+"的交办单");
            map2.put("value",appAllocationPushUserCond.getAllocationNum());
            map3.put("value",state==30? AllocationApproveEnum.IN_APPROVAL.name:AllocationApproveEnum.UNDER_RECTIFICATION.name);
            map4.put("value",DateUtils.dateToDateString(new Date(),"yyyy年MM月dd日"));
            m.put("thing18", map1);
            m.put("character_string1", map2);
            m.put("thing2", map3);
            m.put("date4", map4);
            wxMssVo.setData(JSON.toJSON(m));
            ResponseEntity<String> responseEntity =
                    restTemplate.postForEntity(url, wxMssVo, String.class);
            String body = responseEntity.getBody();
            log.info("信息:"+body+"账号:"+user.getAccount());
        }
    }
    private void sysLog(String cont,User user){
        //日志
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        UserLog userLog = new UserLog();
        userLog.setType(Constants.LOGIN_OPERTATE_APP);
        userLog.setIp(WebUtils.getIpAddr(request));
        userLog.setOperateId(user.getId());
        userLog.setOrganizationId(user.getOrganizationId());
        userLog.setContent(cont);
        userLogMapper.insert(userLog);
    }
    @Override
    public Map<String, Object> login(Map<String, Object> parameters) {
        UserBo userBo = selectUserInfo(parameters);
        UserBO userBo = selectUserInfo(parameters);
        Map<String, Object> result = new HashMap<>();
        //校验账户
        if (userBo == null) {
@@ -77,7 +332,7 @@
        //校验密码
        String password = parameters.get("password").toString();
        //密码解密
        //password = AESUtils.decrypt(password, AESKey);
        password = AESUtils.decrypt(password, AESKey);
        if (!MD5Utils.saltMD5Verify(password, userBo.getPassword())) {
            result.put("code", ResponseCodeEnum.PASSWORD_INVALID.getCode());
            result.put("msg", ResponseCodeEnum.PASSWORD_INVALID.getMsg());
@@ -95,48 +350,81 @@
            result.put("msg", ResponseCodeEnum.ACCOUNT_IS_EXPIRE.getMsg());
            return result;
        }
        //封装用户信息
        Map<String, Object> userInfo = new LinkedHashMap<>();
        List<Map<String, Object>> groups = new ArrayList<>();
        for (Group group : userBo.getGroups()) {
            HashMap<String, Object> groupMap = new HashMap<>();
            groupMap.put("groupId", group.getId());
            groupMap.put("groupName", group.getGroupName());
            groups.add(groupMap);
        }
        Organization organization = userBo.getOrganization();
        ResponsibilityUnit responsibilityUnit = responsibilityUnitMapper.selectById(userBo.getUnitId());
        //用户信息
        userInfo.put("userId", userBo.getId());
        userInfo.put("account", userBo.getAccount());
        userInfo.put("userName", userBo.getUserName());
        userInfo.put("expireTime", userBo.getExpireTime());
        userInfo.put("email", userBo.getEmail());
        userInfo.put("mobile", userBo.getMobile());
        userInfo.put("unitId",userBo.getUnitId());
        userInfo.put("unName",Objects.nonNull(responsibilityUnit)&&Objects.nonNull(responsibilityUnit.getAreaName())?responsibilityUnit.getAreaName():"未选择责任单位");
        userInfo.put("wechat", userBo.getWechat());
        userInfo.put("expireTime", DateUtils.dateToDateString(userBo.getExpireTime()));
        userInfo.put("isAdmin", userBo.getIsAdmin());
        userInfo.put("organizationId", userBo.getOrganizationId());
        userInfo.put("organizationName", organization.getName());
        userInfo.put("locationLevel", organization.getLocationLevel());
        userInfo.put("groups", groups);
        userInfo.putAll(getMenus(userBo.getId(), -1));
        //用户组织信息
        Organization organization = userBo.getOrganization();
        Map<String, Object> orgInfo = new LinkedHashMap<>();
        orgInfo.put("id", userBo.getOrganizationId());
        orgInfo.put("name", organization.getName());
        orgInfo.put("locationLevelCode", organization.getLocationLevelCode());
        orgInfo.put("expireTime", DateUtils.dateToDateString(organization.getExpireTime()));
        userInfo.put("organization", orgInfo);
        //用户组信息
        Group group = userBo.getGroup();
        Map<String, Object> groupMap = new LinkedHashMap<>();
        userInfo.put("group", groupMap);
        if (group != null) {
            groupMap.put("id", group.getId());
            groupMap.put("groupName", group.getGroupName());
            userInfo.put("group", groupMap);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userBo.getId());
        //用户菜单信息
        userInfo.putAll(getMenus(map));
        try {
            //生成token,并存入redis
            String token = TokenUtils.getToken(userBo.getId().toString(), userInfo);
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("user", userInfo);
            result.put("data", data);
            result.put("token", token);
        } catch (Exception e) {
            log.error("token生成异常:" + e.getMessage());
            result.put("code", ResponseCodeEnum.TOKEN_CREATE_ERROR.getCode());
            result.put("msg", ResponseCodeEnum.TOKEN_CREATE_ERROR.getMsg());
            return result;
        }
        //日志
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        UserLog userLog = new UserLog();
        userLog.setType(Constants.LOGIN_OPERTATE_TYPE);
        userLog.setIp(WebUtils.getIpAddr(request));
        userLog.setOperateId(userBo.getId());
        userLog.setOrganizationId(userBo.getOrganizationId());
        userLog.setContent("登陆了用户:" + userBo.getAccount());
        userLogMapper.insert(userLog);
        return result;
    }
    //根据userId获取用户层级菜单
    public Map<String, Object> getMenus(int userId, int orgId) {
    @Override
    public Map<String, Object> getCurrentUserInfo() {
        Map<String, Object> userInfo = (Map<String, Object>) TokenUtils.getUserInfo();
        return userInfo;
    }
    @Override
    public Map<String, Object> getMenus(Map<String, Object> parameters) {
        List<Menu> allMenus;
        if (orgId == -1) {
            allMenus = menuMapper.selectUserMenu(userId);
        if (parameters.containsKey("userId")) {
            allMenus = menuMapper.selectUserMenu(Integer.parseInt(parameters.get("userId").toString()));
        } else {
            allMenus = menuMapper.selectOrganizationMenu(orgId);
            allMenus = menuMapper.selectOrganizationMenu(Integer.parseInt(parameters.get("orgId").toString()));
            allMenus.removeIf(m -> "员工管理".equals(m.getName()));
        }
        Map<String, Object> resultMap = new LinkedHashMap<>();
@@ -151,10 +439,10 @@
        oneMenu.forEach(o -> {
            Map<String, Object> menuMap = new LinkedHashMap<>();
            menuMap.put("id", o.getId());
            menuMap.put("name", o.getName());
            menuMap.put("label", o.getName());
            menuMap.put("url", o.getUrl());
            menuMap.put("icon", o.getIcon());
            menuMap.put("menus", getMenusByRecursion(o, allMenus));
            menuMap.put("children", getMenusByRecursion(o, allMenus));
            newList.add(menuMap);
        });
        resultMap.put("menus", newList);
@@ -162,13 +450,13 @@
    }
    //获取用户层级菜单递归方法
    public List<Map<String, Object>> getMenusByRecursion(Menu menu, List<Menu> menus) {
        List<List<Map<String, Object>>> resultList = new ArrayList();
    private List<Map<String, Object>> getMenusByRecursion(Menu menu, List<Menu> menus) {
        Menu newMenu = new Menu();
        newMenu.setParentId(menu.getId());
        //筛选出下一级菜单信息
        List<Menu> nextLevelMenus = menus.stream()
                .filter(o -> o.getParentId().equals(menu.getId()))
                .sorted(Comparator.comparing(Menu::getOrder))
                .collect(Collectors.toList());
        List<Map<String, Object>> list = new ArrayList<>();
        if (nextLevelMenus.size() > 0) {
@@ -176,151 +464,206 @@
            nextLevelMenus.forEach(o -> {
                Map<String, Object> menuMap = new LinkedHashMap<>();
                menuMap.put("id", o.getId());
                menuMap.put("name", o.getName());
                menuMap.put("label", o.getName());
                menuMap.put("url", o.getUrl());
                menuMap.put("icon", o.getIcon());
                //调用递归体
                menuMap.put("menus", getMenusByRecursion(o, menus));
                menuMap.put("children", getMenusByRecursion(o, menus));
                list.add(menuMap);
            });
            resultList.add(list);
        }
        return list;
    }
    @Override
    @Transactional
    public Map<String, Object> addUser(User user, String token) {
    public Map<String, Object> addUser(User user) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> currentUserInfo = (Map<String, Object>) TokenUtils.getUserInfoByToken(token);
        Map<String, Object> currentUserInfo = (Map<String, Object>) TokenUtils.getUserInfo();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", user.getAccount()).eq("is_delete", Constants.NOT_DELETE);
        //校验账户是否存在
        if (user.selectOne(queryWrapper) != null) {
        if (user.selectCount(queryWrapper) > 0) {
            result.put("code", ResponseCodeEnum.ACCOUNT_EXIST.getCode());
            result.put("msg", ResponseCodeEnum.ACCOUNT_EXIST.getMsg());
            return result;
        }
        //正则校验账户
        //校验账户
        if (!RegexUtils.checkAccount(user.getAccount())) {
            result.put("code", ResponseCodeEnum.ACCOUNT_INVALID.getCode());
            result.put("msg", ResponseCodeEnum.ACCOUNT_INVALID.getMsg());
            return result;
        }
        //正则校验账户
        if (user.getEmail() != null && !RegexUtils.checkEmail(user.getEmail())) {
        //校验邮箱
        if (!ObjectUtils.isEmpty(user.getEmail()) && !RegexUtils.checkEmail(user.getEmail())) {
            result.put("code", ResponseCodeEnum.EMAIL_INVALID.getCode());
            result.put("msg", ResponseCodeEnum.EMAIL_INVALID.getMsg());
            return result;
        }
        //正则校验密码
        //校验密码
        String password = user.getPassword();
        //密码解密
        //password = AESUtils.decrypt(password, AESKey);
        password = AESUtils.decrypt(password, AESKey);
        if (!RegexUtils.checkPassword(password)) {
            result.put("code", ResponseCodeEnum.PASSWORD_INVALID.getCode());
            result.put("msg", ResponseCodeEnum.PASSWORD_INVALID.getMsg());
            return result;
        }
        //正则校验手机号
        if (user.getMobile() != null && !RegexUtils.checkMobile(user.getMobile())) {
        //校验手机号
        if (!ObjectUtils.isEmpty(user.getMobile()) && !RegexUtils.checkMobile(user.getMobile())) {
            result.put("code", ResponseCodeEnum.MOBILE_INVALID.getCode());
            result.put("msg", ResponseCodeEnum.MOBILE_INVALID.getMsg());
            return result;
        }
        //密码加密
        user.setPassword(MD5Utils.saltMD5(password));
        user.setOrganizationId((int) currentUserInfo.get("organizationId"));
        Map<String, Object> orgInfo = (Map<String, Object>) currentUserInfo.get("organization");
        Integer orgId = (Integer) orgInfo.get("id");
        user.setOrganizationId(orgId);
        user.setIsAdmin(false);
        //新增账户的过期时间
        Date userExpireTime = user.getExpireTime();
        //当前账户的过期时间
        Date currentUserExpireTime = (Date) currentUserInfo.get("expireTime");
        if (userExpireTime == null || userExpireTime.getTime() > currentUserExpireTime.getTime()) {
            user.setExpireTime(currentUserExpireTime);
        //当前组织的过期时间
        Date orgExpireTime = DateUtils.getDate((String) orgInfo.get("expireTime"), DateUtils.yyyy_MM_dd_HH_mm_ss_EN);
        if (userExpireTime != null) {
            if (orgExpireTime != null && userExpireTime.getTime() > orgExpireTime.getTime()) {
                user.setExpireTime(orgExpireTime);
            } else {
                user.setExpireTime(userExpireTime);
            }
        } else {
            if (orgExpireTime != null) {
                user.setExpireTime(orgExpireTime);
            }
        }
        userMapper.insert(user);
        //日志
        String content = "添加了用户:" + user.getAccount();
        operationLogUtils.insertLog(content, Constants.INSERT_OPERATE_TYPE);
        return result;
    }
    @Override
    @Transactional
    public void deleteUser(User user) {
    public void deleteUser(Integer userId) {
        User user = userMapper.selectById(userId);
        //逻辑删除user
        user.setIsDelete(Constants.DELETE);
        userMapper.updateById(user);
        //逻辑删除user_group
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", userId).set("is_delete", Constants.DELETE);
        userMapper.update(null, updateWrapper);
        //删除user_group
        UpdateWrapper<UserGroup> deleteWrapper = new UpdateWrapper<>();
        deleteWrapper.set("is_delete", Constants.DELETE).eq("user_id", user.getId());
        userGroupMapper.update(null, deleteWrapper);
        deleteWrapper.eq("user_id", userId);
        userGroupMapper.delete(deleteWrapper);
        //清楚redis
        if (TokenUtils.hHasKey(userId.toString())) {
            String token = TokenUtils.hget(userId.toString()).toString();
            TokenUtils.destoryToken(userId.toString(), token);
        }
        //日志
        String content = "删除了用户:" + user.getAccount();
        operationLogUtils.insertLog(content, Constants.DELETE_OPERATE_TYPE);
    }
    @Override
    @Transactional
    public Map<String, Object> updateUser(User user, String token) {
    public Map<String, Object> updateUser(User user) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> currentUserInfo = (Map<String, Object>) TokenUtils.getUserInfoByToken(token);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("id", user.getId())
                .eq("account", user.getAccount())
                .eq("is_delete", Constants.NOT_DELETE);
        //校验账户是否存在
        if (userMapper.selectOne(queryWrapper) != null) {
            result.put("code", ResponseCodeEnum.ACCOUNT_EXIST.getCode());
            result.put("msg", ResponseCodeEnum.ACCOUNT_EXIST.getMsg());
            return result;
        //更新的属性
        Map<String, Object> update = JSONObject.parseObject(JSON.toJSONString(user), Map.class);
        Map<String, Object> currentUserInfo = (Map<String, Object>) TokenUtils.getUserInfo();
        User beforeUser = userMapper.selectById(user.getId());
        Map<String, Object> before = JSONObject.parseObject(JSON.toJSONString(beforeUser), Map.class);
        /*String account = beforeUser.getAccount();
        //account不可修改
        user.setAccount(account);*/
        if (!ObjectUtils.isEmpty(user.getAccount())) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_delete", Constants.NOT_DELETE).eq("account", user.getAccount());
            if (userMapper.selectCount(queryWrapper) > 0) {
                result.put("code", ResponseCodeEnum.ACCOUNT_EXIST.getCode());
                result.put("msg", ResponseCodeEnum.ACCOUNT_EXIST.getMsg());
                return result;
            }
        }
        //正则校验账户
        if (!RegexUtils.checkAccount(user.getAccount())) {
            result.put("code", ResponseCodeEnum.ACCOUNT_INVALID.getCode());
            result.put("msg", ResponseCodeEnum.ACCOUNT_INVALID.getMsg());
            return result;
        }
        //正则校验账户
        if (user.getEmail() != null && !RegexUtils.checkEmail(user.getEmail())) {
        //邮箱校验
        if (!ObjectUtils.isEmpty(user.getEmail()) && !RegexUtils.checkEmail(user.getEmail())) {
            result.put("code", ResponseCodeEnum.EMAIL_INVALID.getCode());
            result.put("msg", ResponseCodeEnum.EMAIL_INVALID.getMsg());
            return result;
        }
        //正则校验密码
        //密码校验
        String password = user.getPassword();
        //密码解密
        //password = AESUtils.decrypt(password, AESKey);
        if (!RegexUtils.checkPassword(password)) {
            result.put("code", ResponseCodeEnum.PASSWORD_INVALID.getCode());
            result.put("msg", ResponseCodeEnum.PASSWORD_INVALID.getMsg());
            return result;
        if (!ObjectUtils.isEmpty(password)) {
            //密码解密
            password = AESUtils.decrypt(password, AESKey);
            if (!RegexUtils.checkPassword(password)) {
                result.put("code", ResponseCodeEnum.PASSWORD_INVALID.getCode());
                result.put("msg", ResponseCodeEnum.PASSWORD_INVALID.getMsg());
                return result;
            }
        }
        //正则校验手机号
        if (user.getMobile() != null && !RegexUtils.checkMobile(user.getMobile())) {
        if (!ObjectUtils.isEmpty(user.getMobile()) && !RegexUtils.checkMobile(user.getMobile())) {
            result.put("code", ResponseCodeEnum.MOBILE_INVALID.getCode());
            result.put("msg", ResponseCodeEnum.MOBILE_INVALID.getMsg());
            return result;
        }
        //密码加密
        //密码MD5加密
        user.setPassword(MD5Utils.saltMD5(password));
        user.setOrganizationId((int) currentUserInfo.get("organizationId"));
        //组织信息
        Map<String, Object> orgInfo = (Map<String, Object>) currentUserInfo.get("organization");
        user.setOrganizationId((int) orgInfo.get("id"));
        user.setIsAdmin(false);
        //新增账户的过期时间
        //所修改账户的过期时间
        Date userExpireTime = user.getExpireTime();
        //当前账户的过期时间
        Date currentUserExpireTime = (Date) currentUserInfo.get("expireTime");
        if (userExpireTime == null || userExpireTime.getTime() > currentUserExpireTime.getTime()) {
            user.setExpireTime(currentUserExpireTime);
        //当前组织的过期时间
        Date orgExpireTime = DateUtils.getDate((String) orgInfo.get("expireTime"), DateUtils.yyyy_MM_dd_HH_mm_ss_EN);
        if (userExpireTime != null) {
            if (orgExpireTime != null && userExpireTime.getTime() > orgExpireTime.getTime()) {
                result.put("code", ResponseCodeEnum.EXPIRE_BEYOND_ADMIN.getCode());
                result.put("msg", ResponseCodeEnum.EXPIRE_BEYOND_ADMIN.getMsg());
                return result;
            }
        }
        //更新redis
        String userId = user.getId().toString();
        if (TokenUtils.hHasKey(userId)) {
            String deleteToken = TokenUtils.hget(userId).toString();
            TokenUtils.destoryToken(userId, deleteToken);
        }
        userMapper.updateById(user);
        //日志
        String account = userMapper.selectById(userId).getAccount();
        StringBuilder content = new StringBuilder("修改了用户:" + account + "->");
        for (String key : update.keySet()) {
            Object afterValue = update.get(key);
            if (!key.equals("id") && afterValue != null) {
                //修改前属性值
                Object beforeValue = before.get(key);
                content.append(key).append(":").append(beforeValue).append("=>").append(afterValue).append(";");
            }
        }
        operationLogUtils.insertLog(content.toString(), Constants.UPDATE_OPERATE_TYPE);
        return result;
    }
    @Override
    public Page<User> selectUsers(Map<String, Object> parameters) {
        Map<String, Object> currentUserInfo = (Map<String, Object>) TokenUtils.getUserInfoByToken(parameters.get("token").toString());
        Object organizationId = currentUserInfo.get("organizationId");
        Map<String, Object> currentUserInfo = (Map<String, Object>) TokenUtils.getUserInfo();
        Map<String, Object> orgInfo = (Map<String, Object>) currentUserInfo.get("organization");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("organization_id", organizationId)
                .eq("is_delete", Constants.NOT_DELETE);
        queryWrapper.eq("organization_id", orgInfo.get("id"))
                .eq("is_delete", Constants.NOT_DELETE)
                .eq("is_admin", false);
        Object order = parameters.get("order");
        Object orderType = parameters.get("orderType");
        Object account = parameters.get("account");
        Object userName = parameters.get("userName");
        Object mobile = parameters.get("mobile");
@@ -342,26 +685,22 @@
        if (wechat != null) {
            queryWrapper.like("wechat", wechat);
        }
        //分页参数
        if (!parameters.containsKey("page")) {
            parameters.put("page", 0);
        }
        if (!parameters.containsKey("size")) {
            parameters.put("size", 10);
        }
        int page = Integer.parseInt(parameters.get("page").toString());
        int size = Integer.parseInt(parameters.get("size").toString());
        Page<User> pageData = new Page<>(page, size);
        //排序参数,默认id升序
        if (order == null) {
            queryWrapper.orderByAsc("id");
        //排序参数,默认create_time降序
        if (order != null && orderType != null) {
            if (Constants.ORDER_ASC.equals(orderType)) {
                queryWrapper.orderByAsc(ConvertUtils.toLine(order.toString()));
            } else {
                queryWrapper.orderByDesc(ConvertUtils.toLine(order.toString()));
            }
        } else {
            queryWrapper.orderByAsc(order.toString(), "id");
            queryWrapper.orderByDesc("create_time");
        }
        Page<User> userPage = userMapper.selectPage(pageData, queryWrapper);
        pageData.setRecords(userPage.getRecords());
        return userPage;
        userMapper.selectPage(pageData, queryWrapper);
        return pageData;
    }
}