package com.pqs9900.controller.user;

import com.njcn.enums.CookieKeyEnum;
import com.njcn.enums.LogTypeEnum;
import com.njcn.enums.ProjectEnum;
import com.njcn.mapper.configuration.SysMapper;
import com.njcn.mapper.user.AppUserMapper;
import com.njcn.mapper.user.ManageListMapper;
import com.njcn.mapper.user.UserMapper;
import com.njcn.mapper.user.UserSetMapper;
import com.njcn.pojo.commons.AreaInfo;
import com.njcn.pojo.commons.HttpResult;
import com.njcn.pojo.commons.RedisDB;
import com.njcn.pojo.configuration.SysSet;
import com.njcn.pojo.user.AppUser;
import com.njcn.pojo.user.SecretKey;
import com.njcn.shiro.filter.KickoutSessionFilter;
import com.njcn.shiro.session.impl.JedisShiroSessionRepository;
import com.njcn.sso.pojo.user.User;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.service.log.UserLoginService;
import com.njcn.service.user.SecretKeyService;
import com.njcn.service.user.UserService;
import com.njcn.shiro.pojo.UserOnlineBo;
import com.njcn.shiro.session.UserShiroSessionRepository;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.*;
import com.njcn.utils.redis.JedisManager;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.security.auth.login.AccountException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.*;

import static com.njcn.shiro.token.TokenManager.userSessionManager;

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;
    // 日志记录
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    UserLogDetailService userLogservice;

    @Autowired
    UserLoginService userLoginService;

    @Autowired
    UserShiroSessionRepository userShiroSessionRepository;


    @Autowired
    ManageListMapper alm;

    @Autowired
    UserMapper userMapper;
    @Autowired
    SysMapper sm;


    @Autowired
    private UserService us;

    @Autowired
    private SecretKeyService sk;

    @Autowired
    UserUtil userUtil;

    @Autowired
    UserSetMapper usm;

    @Autowired
    UserMapper um;

    @Autowired
    AppUserMapper appUserMapper;

    @Autowired
    AppConfig appConfig;

    @Autowired
    JedisManager jedisManager;

    /************************
     * RSA
     * 根据用户名生成秘钥对
     * @param username 用户名
     *************************/
    @PostMapping("generateRSAKey")
    @ResponseBody
    public HttpResult generateRSAKey(String username, HttpServletRequest request) {
        HttpResult result;
        try {
            username = DesUtils.aesDecrypt(username);
            // 获取公钥和私钥
            HashMap<String, Object> keys = RSAUtils.getKeys();
            RSAPublicKey publicKey = (RSAPublicKey) keys.get("public");
            RSAPrivateKey privateKey = (RSAPrivateKey) keys.get("private");
            String ip = StringUtils.isBlank(PubUtils.getIpAddr(request)) ? "127.0.0.1" : PubUtils.getIpAddr(request);
            //秘钥先删除再添加
            jedisManager.deleteByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(username + ip));
            // 保存私钥到 redis，也可以保存到数据库
            jedisManager.saveValueByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(username + ip), SerializeUtil.serialize(privateKey), -1);
            // 将公钥传到前端
            Map<String, String> map = new HashMap<String, String>();
            // 注意返回modulus和exponent以16为基数的BigInteger的字符串表示形式
            map.put("modulus", publicKey.getModulus().toString(16));
            map.put("exponent", publicKey.getPublicExponent().toString(16));
            result = PubUtils.assignmentResult(map, 200, "生成秘钥对成功！");
        } catch (Exception u) {
            result = PubUtils.assignmentResult(null, 500, u.getMessage());
        }
        return result;
    }

    /************************
     * SM2
     * 根据用户名生成秘钥对
     * @param username 用户名
     *************************/
    @PostMapping("generateSM2Key")
    @ResponseBody
    public HttpResult generateSM2Key(String username, HttpServletRequest request) {
        HttpResult result;
        try {
            if (PubUtils.isBlank(username)) {
                result = PubUtils.assignmentResult(null, 500, "用户名非法！");
                return result;
            }
            username = DesUtils.aesDecrypt(username);
            // 获取公钥和私钥
            Map<String, String> keyMap =PubUtils.getSM2CipHer();
            String publicKey = keyMap.get("publicKey");  //加密密钥
            String privateKey = keyMap.get("privateKey"); //解密密钥
            String ip = PubUtils.isBlank(PubUtils.getIpAddr(request)) ? "127.0.0.1" : PubUtils.getIpAddr(request);
            //秘钥先删除再添加
            jedisManager.deleteByKey(RedisDB.SHORT_TIME_QUERY, username + ip);
            // 保存私钥到 redis，也可以保存到数据库
            jedisManager.saveValueByKey(RedisDB.SHORT_TIME_QUERY, username + ip, privateKey, -1);
            // 将公钥传到前端
            result = PubUtils.assignmentResult(publicKey, 200, "生成秘钥对成功！");
        } catch (Exception u) {
            result = PubUtils.assignmentResult(null, 500, u.getMessage());
        }
        return result;
    }

    /**
     * 根据当前用户获取区域选择tree
     */
    @PostMapping("getAreasInfo")
    @ResponseBody
    public List<AreaInfo> getAreasInfo() {
        List<AreaInfo> areaInfos;
        try {
            areaInfos = us.getAreasByUser();
            if (CollectionUtils.isEmpty(areaInfos)) {
                areaInfos = null;
            }
        } catch (Exception e) {
            areaInfos = null;
        }
        return areaInfos;
    }

    /**
     * 用户注销，统一重定向到sso中心，在sso中心查询该用户所有对应的sessionID，进行缓存清理，以达到子系统全部注销
     */
    @GetMapping("loginout")
    public void loginOut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        boolean flag = appConfig.isOneContainer();
        String url;
        if (flag) {
            String baseUrl = request.getRequestURL().toString();
            url = baseUrl.substring(0, baseUrl.indexOf("pqs9900")) + "sso/user/loginout?item=pqs9900";
        } else {
            url = appConfig.getSsoUrl() + "/loginout?item=pqs9000";
        }
        WebUtils.issueRedirect(request, response, url);
    }


    /**
     * sso认证完成后，访问子系统，任然需要注册子系统，包括当前用户在子系统下的权限
     */
    @GetMapping("ssoRegister")
    public void ssoRegister(HttpServletRequest request, HttpServletResponse response,String token,String subItem) throws IOException {
        if (StringUtils.isBlank(token)) {
            redirectSso(request, response);
        } else {
            //首先根据token去redis中查询有没有对应的session
            Session session = userShiroSessionRepository.getSession(token);
            //没有需要的共享会话，则重定向回登录中心
            if (null == session) {
                redirectSso(request, response);
            } else {
                //判断认证中心的会话是否被T，被T，子系统时不允许注册的，返回认证中心登录页面
                Boolean marker = (Boolean) session.getAttribute(KickoutSessionFilter.KICKOUT_STATUS);
                if (null != marker && marker) {
                    redirectSso(request, response);
                }
                //获取session登录信息。
                Object obj = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
                if (null == obj) {
                    //没有用户信息，则重定向回登录中心
                    redirectSso(request, response);
                } else {
                    SimplePrincipalCollection spc = (SimplePrincipalCollection) obj;
                    obj = spc.getPrimaryPrincipal();
                    if (null == obj) {
                        //没有用户信息，则重定向回登录中心
                        redirectSso(request, response);
                    } else {
                        User ssoUser = (User) obj;
                        //获取出共享会话中的用户信息，进行再次认证和授权处理
                        try {
                            TokenManager.login(ssoUser.getLoginName(), "", ssoUser.getPassword(), PubUtils.getIpAddr(request), ProjectEnum.PQS9900.getItem());
                            try {
                                userLoginService.insertLogin(ssoUser.getLoginName(), ProjectEnum.PQS9900.getItem());
                            } catch (Exception e) {
                                logger.error("用户登录成功后，保存记录出错。原因：" + e.toString());
                            }
                            //进行sessionID存储到redis
                            TokenManager.getSession().setAttribute(CookieKeyEnum.SSOLOGIN.getCookieKey(), token);
                            saveSessionByUser(session, token, TokenManager.getUserId(), TokenManager.getSession().getId().toString());
                            //登陆成功后激活父会话并保存
                            userShiroSessionRepository.activeSession(session);
                            //认证成功重定向到业务主界面,还需要判断
                            if (StringUtils.isBlank(subItem)) {
                                WebUtils.issueRedirect(request, response, "/business/voltageMain?subItem=pqs9200");
                            } else {
                                if (subItem.equalsIgnoreCase(ProjectEnum.PQS9000.getItem())) {
                                    WebUtils.issueRedirect(request, response, "/business/powerMain?subItem=pqs9000");
                                } else {
                                    WebUtils.issueRedirect(request, response, "/business/voltageMain?subItem=pqs9200");
                                }
                            }
                            userUtil.saveRandomToken();
                        } catch (Exception u) {
                            logger.error("子系统pqs9900注册时异常，异常为：" + u.getMessage());
                        }
                    }
                }
            }
        }
    }

    /**
     * 重定向到sso认证中心，判断用户是否已经登录过
     */
    private void redirectSso(HttpServletRequest request, HttpServletResponse response) throws IOException {
        boolean flag = appConfig.isOneContainer();
        String url;
        if (flag) {
            String baseUrl = request.getRequestURL().toString();
            url = baseUrl.substring(0, baseUrl.indexOf("pqs9900")) + "sso/user/judgeLogin?item=pqs9900";
        } else {
            url = appConfig.getSsoJudge();
        }
        WebUtils.issueRedirect(request, response, url);
    }

    /**
     * 根据用户索引，保存当前系统的sessionID，以便注销系统时删除会话信息
     *
     * @param token
     * @param userId    用户索引
     * @param sessionId 会话ID
     */
    private void saveSessionByUser(Session session, String token, String userId, String sessionId) {
        String key = token + userId;
        List<String> infoMap = (List<String>) session.getAttribute(key);
        //如果不存在，创建一个新的
        infoMap = null == infoMap ? new ArrayList<>() : infoMap;
        infoMap.add(JedisShiroSessionRepository.REDIS_SHIRO_SESSION + sessionId);
        session.setAttribute(key, infoMap);
    }

    /**
     * NuserC
     * 获取所有用户信息
     */
    @RequestMapping(value = "getAllUserList", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getAllUserList(HttpServletRequest request) {
        HttpResult result = new HttpResult();
        List<List> users = us.selectAllUsers();
        try {
            if (users.isEmpty()) {
                result.setCode(500);
                result.setMessage("没有获取到用户信息列表");
                userLogservice.getLog("查询审核用户", "成功，且暂无审核用户", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
                logger.error("获取用户信息成功");
            } else {
                result.setCode(200);
                result.setBody(users);
                result.setMessage("获取用户信息列表成功");
                userLogservice.getLog("查询审核用户", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
                logger.info("获取用户信息成功");
            }
        }catch (Exception e){
            result.setCode(500);
            result.setMessage("没有获取到用户信息列表");
            userLogservice.getLog("查询审核用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
            logger.error("获取用户信息失败");
        }
        return result;
    }


    /**
     * 获取所有用户信息
     */
    @PostMapping(value = "selectAllUser")
    @ResponseBody
    public HttpResult getAllUser(HttpServletRequest request, String userState, String careUser, int resultNum) {
        HttpResult result;
        List<User> users;
        try {
            users = us.selectAllUser(userState, careUser, resultNum);
            if (users.isEmpty()) {
                result = PubUtils.assignmentResult(null, 500, "没有获取到用户信息列表");
                logger.error("获取用户信息失败");
                userLogservice.getLog("查询用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
            } else {
                result = PubUtils.assignmentResult(users, 200, "获取用户信息列表成功");
                logger.info("获取用户信息成功");
                userLogservice.getLog("查询用户", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
            }
        } catch (Exception e) {
            logger.error("获取用户信息异常，异常为" + e.toString());
            result = PubUtils.assignmentResult(null, 500, "获取用户信息失败");
        }
        return result;
    }

    /**
     * 审核用户
     */
    @RequestMapping(value = "updateExaminer", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult updateExaminer(HttpServletRequest request, String userIndex, @Param(value = "roleGpIndex") String roleGpIndex,
                                     @Param(value = "state") Integer state) {
        HttpResult result = new HttpResult();
        try {
            int message = us.updateExaminer(userIndex);
            if (message == 1) {
                result.setCode(200);
                result.setBody("success");
                logger.info("审核用户成功");
                userLogservice.getLog("用户审核", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else {
                result.setCode(500);
                logger.error("审核用户失败");
                userLogservice.getLog("用户审核", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }
        } catch (Exception e) {
            logger.error("审核用户异常，异常为" + e.toString());
            result = PubUtils.assignmentResult(null, 500, "审核失败");
        }
        return result;
    }

    /**
     * 新增用户
     */
    @RequestMapping(value = "saveAppUser", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult saveAppUser(String name, String loginName, String deptsIndex,
                                  String password, String phone, String email,
                                  String ip, String ipEnd, String time,
                                  Integer mark, String usertype, String isnotice,String token,
                                  String referralCode,
                                  String semName, String semPhone, HttpServletRequest request) {
        HttpResult result = new HttpResult();
        String sessionToken = (String) TokenManager.getSession().getAttribute("token");
        if (!token.equalsIgnoreCase(sessionToken)) {
            result = PubUtils.assignmentResult(null, 500, "非法访问");
            return result;
        }
        //后台Xss攻击处理、包括html/js/sql
        name = XssFilterUtil.dealString(name);
        loginName = XssFilterUtil.dealString(loginName);
        loginName = DesUtils.aesDecrypt(loginName);//解密操作
        deptsIndex = XssFilterUtil.dealString(deptsIndex);
        password = XssFilterUtil.dealString(password);
        phone = XssFilterUtil.dealString(phone);
        email = XssFilterUtil.dealString(email);
        ip = XssFilterUtil.dealString(ip);
        ipEnd = XssFilterUtil.dealString(ipEnd);
        time = XssFilterUtil.dealString(time);
        usertype = XssFilterUtil.dealString(usertype);
        isnotice = XssFilterUtil.dealString(isnotice);
        semName = XssFilterUtil.dealString(semName);
        semPhone = XssFilterUtil.dealString(semPhone);
        String tmpip = StringUtils.isBlank(PubUtils.getIpAddr(request)) ? "127.0.0.1" : PubUtils.getIpAddr(request);
        try {
//            byte[] value = jedisManager.getValueByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(loginName + tmpip));
//            RSAPrivateKey privateKey = SerializeUtil.deserialize(value, RSAPrivateKey.class);
//            //秘钥用完即删
//            jedisManager.deleteByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(loginName + tmpip));
//            password = PubUtils.getPasswordRSAVerify(privateKey, password);
//            if (password == null && password.length() == 0) {
//                result = PubUtils.assignmentResult(null, 500, "密码传输完整性被破坏");
//                return result;
//            }

            String privateKey = jedisManager.getValueByKey(RedisDB.SHORT_TIME_QUERY, loginName + tmpip);
            //秘钥用完即删
            jedisManager.deleteByKey(RedisDB.SHORT_TIME_QUERY, loginName + tmpip);
            //对SM2解密面进行验证
            password = PubUtils.getPasswordSM2Verify(privateKey, password);
            if (password == null || password.length() == 0) {
                result = PubUtils.assignmentResult(null, 500, "密码传输完整性被破坏");
                return result;
            }


            if (password.indexOf(loginName) > -1) {
                result = PubUtils.assignmentResult(null, 302, "用户密码包含用户名");
                logger.error("新增用户失败");
                userLogservice.getLog("用户审核", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);

                return result;
            }

            String message = us.saveAppUser(name, loginName, deptsIndex, password, phone, email, ip, ipEnd, time, mark, usertype,isnotice, referralCode, semName, semPhone);
            if (message.equalsIgnoreCase("新增用户成功！")) {
                result = PubUtils.assignmentResult("success", 200, message);
                logger.info("新增用户成功");
                userLogservice.getLog("新增用户", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("登录名已存在")) {
                result = PubUtils.assignmentResult(null, 300, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("名称已存在")) {
                result = PubUtils.assignmentResult(null, 500, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("该手机号已被注册")) {
                result = PubUtils.assignmentResult(null, 301, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("名称不可为空")) {
                result = PubUtils.assignmentResult(null, 302, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("登录名不可为空")) {
                result = PubUtils.assignmentResult(null, 303, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("密码不可为空")) {
                result = PubUtils.assignmentResult(null, 304, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("手机号不可为空")) {
                result = PubUtils.assignmentResult(null, 305, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("邮箱不可为空")) {
                result = PubUtils.assignmentResult(null, 306, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("起始ip不可为空")) {
                result = PubUtils.assignmentResult(null, 307, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("结束ip不可为空")) {
                result = PubUtils.assignmentResult(null, 308, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("名称只由中文组成，长度为1-20")) {
                result = PubUtils.assignmentResult(null, 309, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("登录名只能由3-16的字母和数字组成")) {
                result = PubUtils.assignmentResult(null, 310, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("密码格式不正确,需要包含特殊字符字母数字，长度为8-16")) {
                result = PubUtils.assignmentResult(null, 311, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("邮箱格式不正确，应含有@ .在@后，以.com、.con结尾（qq,163等）")) {
                result = PubUtils.assignmentResult(null, 312, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("手机号格式不正确，必须有11位，并且为数字，是正常的手机号码开头")) {
                result = PubUtils.assignmentResult(null, 313, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("起始ip地址格式不正确")) {
                result = PubUtils.assignmentResult(null, 314, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("结束ip地址格式不正确")) {
                result = PubUtils.assignmentResult(null, 315, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }
        } catch (Exception e) {
            logger.error("新增用户异常，异常为" + e.toString());
            result = PubUtils.assignmentResult(null, 500, "新增用户失败");
        }
        return result;
    }

    /**
     * 新增用户
     */
    @RequestMapping(value = "saveUser", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult saveUser(String name, String loginName, String deptsIndex,
                               String password, String phone, String email,
                               String ip, String ipEnd, String time,
                               Integer mark, String usertype, String isnotice, String token,HttpServletRequest request) {
        HttpResult result = new HttpResult();
        String sessionToken = (String) TokenManager.getSession().getAttribute("token");
        if (!token.equalsIgnoreCase(sessionToken)) {
            result = PubUtils.assignmentResult(null, 500, "非法访问");
            return result;
        }
        //后台Xss攻击处理、包括html/js/sql
        name = XssFilterUtil.dealString(name);
        loginName = XssFilterUtil.dealString(loginName);
        loginName = DesUtils.aesDecrypt(loginName);//解密操作
        deptsIndex = XssFilterUtil.dealString(deptsIndex);
        password = XssFilterUtil.dealString(password);
        phone = XssFilterUtil.dealString(phone);
        email = XssFilterUtil.dealString(email);
        ip = XssFilterUtil.dealString(ip);
        ipEnd = XssFilterUtil.dealString(ipEnd);
        time = XssFilterUtil.dealString(time);
        usertype = XssFilterUtil.dealString(usertype);
        isnotice = XssFilterUtil.dealString(isnotice);
        String tmpip = StringUtils.isBlank(PubUtils.getIpAddr(request)) ? "127.0.0.1" : PubUtils.getIpAddr(request);
        try {
//            byte[] value = jedisManager.getValueByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(loginName + tmpip));
//            RSAPrivateKey privateKey = SerializeUtil.deserialize(value, RSAPrivateKey.class);
//            //秘钥用完即删
//            jedisManager.deleteByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(loginName + tmpip));
//            password = PubUtils.getPasswordRSAVerify(privateKey, password);
            //密码处理
            String privateKey = jedisManager.getValueByKey(RedisDB.SHORT_TIME_QUERY, loginName + tmpip);
            //秘钥用完即删
            jedisManager.deleteByKey(RedisDB.SHORT_TIME_QUERY, loginName + tmpip);
            //对SM2解密面进行验证
            password = PubUtils.getPasswordSM2Verify(privateKey, password);
            if (password == null || password.length() == 0) {
                result = PubUtils.assignmentResult(null, 500, "密码传输完整性被破坏");
                return result;
            }

            if (password.indexOf(loginName) > -1) {
                result = PubUtils.assignmentResult(null, 302, "用户密码包含用户名");
                logger.error("新增用户失败");
                userLogservice.getLog("用户审核", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                return result;
            }

            String message = us.saveUser(name, loginName, deptsIndex, password, phone, email, ip, ipEnd, time, mark, usertype,isnotice);
            if (message.equalsIgnoreCase("新增用户成功！")) {
                result = PubUtils.assignmentResult("success", 200, message);
                logger.info("新增用户成功");
                userLogservice.getLog("新增用户", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("登录名已存在")) {
                result = PubUtils.assignmentResult(null, 300, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("名称已存在")) {
                result = PubUtils.assignmentResult(null, 500, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("该手机号已被注册")) {
                result = PubUtils.assignmentResult(null, 301, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("名称不可为空")) {
                result = PubUtils.assignmentResult(null, 302, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("登录名不可为空")) {
                result = PubUtils.assignmentResult(null, 303, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("密码不可为空")) {
                result = PubUtils.assignmentResult(null, 304, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("手机号不可为空")) {
                result = PubUtils.assignmentResult(null, 305, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("邮箱不可为空")) {
                result = PubUtils.assignmentResult(null, 306, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("起始ip不可为空")) {
                result = PubUtils.assignmentResult(null, 307, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("结束ip不可为空")) {
                result = PubUtils.assignmentResult(null, 308, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("名称只由中文组成，长度为1-20")) {
                result = PubUtils.assignmentResult(null, 309, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("登录名只能由3-16的字母和数字组成")) {
                result = PubUtils.assignmentResult(null, 310, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("密码格式不正确,需要包含特殊字符字母数字，长度为8-16")) {
                result = PubUtils.assignmentResult(null, 311, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("邮箱格式不正确，应含有@ .在@后，以.com、.con结尾（qq,163等）")) {
                result = PubUtils.assignmentResult(null, 312, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("手机号格式不正确，必须有11位，并且为数字，是正常的手机号码开头")) {
                result = PubUtils.assignmentResult(null, 313, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("起始ip地址格式不正确")) {
                result = PubUtils.assignmentResult(null, 314, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("结束ip地址格式不正确")) {
                result = PubUtils.assignmentResult(null, 315, message);
                logger.error("新增用户失败");
                userLogservice.getLog("新增用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }
        } catch (Exception e) {
            logger.error("新增用户异常，异常为" + e.toString());
            result = PubUtils.assignmentResult(null, 500, "新增用户失败");
        }
        return result;
    }

    /**
     * 根据用户索引获取用户信息回显，以便修改
     *
     * @param userIndex 用户索引
     */
    @ResponseBody
    @PostMapping(value = "selectId")
    public User selectId(String userIndex, int flag) {
        return us.selectId(userIndex, flag);
    }


    /**
     * 根据用户索引获取用户信息回显，以便修改
     *
     * @param userIndex 用户索引
     */
    @ResponseBody
    @PostMapping(value = "selectAppId")
    public AppUser selectAppId(String userIndex) {
        return us.selectAppId(userIndex);
    }

    /**
     * 根据用户索引删除用户
     */
    @RequestMapping(value = "deleteUserByIndex", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult deleteUserByIndex(HttpServletRequest request, String index, String token) {
        HttpResult result = new HttpResult();
        String sessionToken = (String) TokenManager.getSession().getAttribute("token");
        if (!token.equalsIgnoreCase(sessionToken)) {
            result = PubUtils.assignmentResult(null, 500, "非法访问");
            return result;
        }
        try {
            String ip = PubUtils.getIpAddr(request);
            String username = TokenManager.getToken().getLoginName();

            byte[] value = jedisManager.getValueByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(username + ip));
            String key = SerializeUtil.deserialize(value, String.class);
            if(key.equals("success")){
                String message = us.deleteUserByIndex(index);
                if (message.equalsIgnoreCase("注销用户成功！")) {
                    result = PubUtils.assignmentResult("success", 200, message);
                    userLogservice.getLog("注销用户", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                    logger.info("注销用户成功");
                } else {
                    result = PubUtils.assignmentResult(null, 500, message);
                    userLogservice.getLog("注销用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                    logger.error("注销用户失败");
                }
            }else{
            	result = PubUtils.assignmentResult(null, 400, "注销用户失败,密码验证失败!");
            }

            jedisManager.deleteByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(username + ip));
        } catch (Exception e) {
            logger.error("注销用户异常，异常为" + e.toString());
            result = PubUtils.assignmentResult(null, 500, "注销用户失败");
        }
        return result;
    }

    /**
     * 根据用户索引删除用户
     */
    @RequestMapping(value = "deleteAppUserByIndex", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult deleteAppUserByIndex(HttpServletRequest request, String index, String token) {
        HttpResult result;
        String sessionToken = (String) TokenManager.getSession().getAttribute("token");
        if (!token.equalsIgnoreCase(sessionToken)) {
            result = PubUtils.assignmentResult(null, 500, "非法访问");
            return result;
        }
        try {
            String message = us.deleteAppUserByIndex(index);
            if (message.equalsIgnoreCase("注销用户成功！")) {
                result = PubUtils.assignmentResult("success", 200, message);
                userLogservice.getLog("注销用户", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                logger.info("注销用户成功");
            } else {
                result = PubUtils.assignmentResult(null, 500, message);
                userLogservice.getLog("注销用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                logger.error("注销用户失败");
            }
        } catch (Exception e) {
            logger.error("注销用户异常，异常为" + e.toString());
            result = PubUtils.assignmentResult(null, 500, "注销用户失败");
        }
        return result;
    }

    //修改密码
    @ResponseBody
    @RequestMapping(value = "updatePassword", method = RequestMethod.POST)
    public HttpResult updatePassword(HttpServletRequest request, @Param(value = "username") String username,
                                     @Param(value = "passwordX") String passwordX,
                                     String token) {
        HttpResult result = new HttpResult();

        String sessionToken = (String) TokenManager.getSession().getAttribute("token");
        if (!token.equalsIgnoreCase(sessionToken)) {
            result = PubUtils.assignmentResult(null, 500, "非法访问");
            return result;
        }
        //username = XssFilterUtil.dealString(username);
        username = DesUtils.aesDecrypt(username);
        passwordX = XssFilterUtil.dealString(passwordX);

        String ip = StringUtils.isBlank(PubUtils.getIpAddr(request)) ? "127.0.0.1" : PubUtils.getIpAddr(request);
        try {
            //密码处理
            String privateKey = jedisManager.getValueByKey(RedisDB.SHORT_TIME_QUERY, username + ip);
            //秘钥用完即删
            jedisManager.deleteByKey(RedisDB.SHORT_TIME_QUERY, username + ip);
            //对SM2解密面进行验证
            passwordX = PubUtils.getPasswordSM2Verify(privateKey, passwordX);
            if (passwordX == null && passwordX.length() == 0) {
                result = PubUtils.assignmentResult(null, 500, "密码传输完整性被破坏");
                userLogservice.getLog("修改用户密码", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                return result;
            }

            //增加判断密码是否包含用户名
            if (passwordX.indexOf(username) > -1) {
                userLogservice.getLog("修改用户密码", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                return PubUtils.assignmentResult(null, 500, "用户密码包含登录名");
            }

            if (!(PubUtils.patternPassword(passwordX) || PubUtils.patternUsername(username))) {
                userLogservice.getLog("修改用户密码", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                result = PubUtils.assignmentResult(null, 500, "用户名、密码格式不正确");
                return result;
            }
            try {
                userService.modifyPassword(username, passwordX);
                userLogservice.getLog("修改用户密码", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                result = PubUtils.assignmentResult(null, 200, "修改密码成功");
                User user = new User();
                user.setLoginName(username);
                user = userMapper.selectOne(user);
                if (null != user) {
                    user.setState(1);
                    userMapper.updateByPrimaryKeyBySql(user);
                }
            } catch (Exception e) {
                userLogservice.getLog("修改用户密码", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                result = PubUtils.assignmentResult(null, 500, e.getMessage());
                logger.error("用户修改密码成功后，保存记录出错。原因：" + e.toString());
            }
        } catch (Exception e) {
            logger.error("更新密码出错，异常为：" + e.toString());
            String eMessage = e.getMessage();
            if (eMessage.length() > 20) {
                eMessage = "内部出错";
            }
            result = PubUtils.assignmentResult(null, 500, eMessage);
            try {
                userLogservice.getLog("修改用户密码", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } catch (Exception u) {
                logger.error("用户修改密码失败后，保存记录出错。原因：" + u.toString());
            }
        }
        return result;
    }

    //修改密码
    @ResponseBody
    @RequestMapping(value = "updateAppPassWord", method = RequestMethod.POST)
    public HttpResult updateAppPassword(HttpServletRequest request, @Param(value = "username") String username,
                                        @Param(value = "passwordX") String passwordX,
                                        String token) {
        HttpResult result = new HttpResult();

        String sessionToken = (String) TokenManager.getSession().getAttribute("token");
        if (!token.equalsIgnoreCase(sessionToken)) {
            result = PubUtils.assignmentResult(null, 500, "非法访问");
            return result;
        }
        //username = XssFilterUtil.dealString(username);
        username = DesUtils.aesDecrypt(username);
        passwordX = XssFilterUtil.dealString(passwordX);

        String ip = StringUtils.isBlank(PubUtils.getIpAddr(request)) ? "127.0.0.1" : PubUtils.getIpAddr(request);
        try {
            //密码处理
            String privateKey = jedisManager.getValueByKey(RedisDB.SHORT_TIME_QUERY, username + ip);
            //秘钥用完即删
            jedisManager.deleteByKey(RedisDB.SHORT_TIME_QUERY, username + ip);
            passwordX = PubUtils.getPasswordSM2Verify(privateKey, passwordX);
            if (passwordX == null || passwordX.length() == 0) {
                result = PubUtils.assignmentResult(null, 500, "密码传输完整性被破坏");
                userLogservice.getLog("修改用户密码", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                return result;
            }

            //增加判断密码是否包含用户名
            if (passwordX.indexOf(username) > -1) {
                userLogservice.getLog("修改用户密码", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                return PubUtils.assignmentResult(null, 500, "用户密码包含登录名");
            }

            if (!(PubUtils.patternPassword(passwordX) || PubUtils.patternUsername(username))) {
                userLogservice.getLog("修改用户密码", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                result = PubUtils.assignmentResult(null, 500, "用户名、密码格式不正确");
                return result;
            }
            try {
                userService.modifyAppPassword(username, passwordX);
                userLogservice.getLog("修改用户密码", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                result = PubUtils.assignmentResult(null, 200, "修改密码成功");
                User user = new User();
                user.setLoginName(username);
                user = userMapper.selectOne(user);
                if (null != user) {
                    user.setState(1);
                    userMapper.updateByPrimaryKeyBySql(user);
                }
            } catch (Exception e) {
                userLogservice.getLog("修改用户密码", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                result = PubUtils.assignmentResult(null, 500, e.getMessage());
                logger.error("用户修改密码成功后，保存记录出错。原因：" + e.toString());
            }
        } catch (Exception e) {
            logger.error("更新密码出错，异常为：" + e.toString());
            String eMessage = e.getMessage();
            if (eMessage.length() > 20) {
                eMessage = "内部出错";
            }
            result = PubUtils.assignmentResult(null, 500, eMessage);
            try {
                userLogservice.getLog("修改用户密码", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } catch (Exception u) {
                logger.error("用户修改密码失败后，保存记录出错。原因：" + u.toString());
            }
        }
        return result;
    }

    /***
     * 修改用户
     */
    @ResponseBody
    @RequestMapping(value = "updateUser", method = RequestMethod.POST)
    public int updateUser(HttpServletRequest request, String userIndex, String name, String loginName, String deptsIndex, String phone, String email, String ipGo, String ipE, String time, Integer mark, String usertype, String isnotice,String token) throws AccountException {

        //后台Xss攻击处理、包括html/js/sql
        String sessionToken = (String) TokenManager.getSession().getAttribute("token");
        if (!token.equalsIgnoreCase(sessionToken)) {
            return 2;
        }
        name = XssFilterUtil.dealString(name);
        loginName = XssFilterUtil.dealString(loginName);
        deptsIndex = XssFilterUtil.dealString(deptsIndex);
        phone = XssFilterUtil.dealString(phone);
        email = XssFilterUtil.dealString(email);
        ipGo = XssFilterUtil.dealString(ipGo);
        ipE = XssFilterUtil.dealString(ipE);
        time = XssFilterUtil.dealString(time);
        usertype = XssFilterUtil.dealString(usertype);
        isnotice = XssFilterUtil.dealString(isnotice);
        int flag = 2;
        List<User> list = us.selectName(name, userIndex);

        if (!CollectionUtils.isEmpty(list)) {
            flag = 0;
            userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            logger.error("修改用户失败，原因是该用户名已存在");
        }


        List<User> users = new ArrayList<>();
        users = um.getPhone(phone,0);
        for (User user1 : users) {
            if (!user1.getUserIndex().equals(userIndex)) {
                flag = 3;
                userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                logger.error("修改用户失败，原因是该手机号已被注册");
                break;
            }
        }

        if (flag != 0 && flag != 3) {
            try {
                if (!StringUtils.isBlank(name)) {
                    if (!StringUtils.isBlank(loginName)) {
                        if (!StringUtils.isBlank(email)) {
                            if (!StringUtils.isBlank(phone)) {
                                if (!StringUtils.isBlank(ipGo)) {
                                    if (!StringUtils.isBlank(ipE)) {
                                        //进行用户的所有正则
                                        if (PubUtils.patternName(name)) {
                                            if (PubUtils.patternUsername(loginName)) {
                                                if (PubUtils.patternEmail(email)) {
                                                    if (PubUtils.patternPhone(phone)) {
                                                        if (PubUtils.patternIp(ipGo)) {
                                                            if (PubUtils.patternIp(ipE)) {
                                                                us.updateUser(userIndex, name, loginName, deptsIndex, phone, email, ipGo, ipE, time, mark, usertype,isnotice);
                                                                flag = 1;
                                                                userLogservice.getLog("修改用户", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                                                                logger.info("修改用户成功");
                                                            } else {
                                                                flag = 4;
                                                                userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                                                                logger.error("结束ip地址格式不正确");
                                                            }
                                                        } else {
                                                            flag = 5;
                                                            userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                                                            logger.error("起始ip地址格式不正确");
                                                        }
                                                    } else {
                                                        flag = 6;
                                                        userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                                                        logger.error("手机号格式不正确，必须有11位，并且为数字，是正常的手机号码开头");
                                                    }
                                                } else {
                                                    flag = 7;
                                                    userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                                                    logger.error("邮箱格式不正确，应含有@ .在@后，以.com、.con结尾（qq,163等）");
                                                }
                                            } else {
                                                flag = 8;
                                                userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                                                logger.error("登录名只能由3-16的字母和数字组成");
                                            }
                                        } else {
                                            flag = 9;
                                            userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                                            logger.error("名称只由中文组成，长度为1-20");
                                        }
                                    } else {
                                        flag = 10;
                                        userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                                        logger.error("结束ip不可为空");
                                    }
                                } else {
                                    flag = 11;
                                    userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                                    logger.error("起始ip不可为空");
                                }
                            } else {
                                flag = 12;
                                userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                                logger.error("邮箱不可为空");
                            }
                        } else {
                            flag = 13;
                            userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                            logger.error("手机号不可为空");
                        }
                    } else {
                        flag = 14;
                        userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                        logger.error("登录名不可为空");
                    }
                } else {
                    flag = 15;
                    userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                    logger.error("名称不可为空");
                }
            } catch (Exception e) {
                flag = 2;
                userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                logger.error(e.toString());
            }
        } else {
            userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            logger.error("修改用户失败，原因是该用户名已存在");
        }
        return flag;
    }

    /***
     * 修改用户
     */
    @ResponseBody
    @RequestMapping(value = "updateAppUser", method = RequestMethod.POST)
    public int updateAppUser(HttpServletRequest request, String userIndex, String name, String loginName, String deptsIndex, String phone, String email, String ipGo, String ipE, String time, Integer mark, String usertype,String isnotice, String semName, String semPhone, String token) {

        //后台Xss攻击处理、包括html/js/sql
        String sessionToken = (String) TokenManager.getSession().getAttribute("token");
        if (!token.equalsIgnoreCase(sessionToken)) {
            return 2;
        }
        name = XssFilterUtil.dealString(name);
        loginName = XssFilterUtil.dealString(loginName);
        deptsIndex = XssFilterUtil.dealString(deptsIndex);
        phone = XssFilterUtil.dealString(phone);
        email = XssFilterUtil.dealString(email);
        ipGo = XssFilterUtil.dealString(ipGo);
        ipE = XssFilterUtil.dealString(ipE);
        time = XssFilterUtil.dealString(time);
        usertype = XssFilterUtil.dealString(usertype);
        isnotice = XssFilterUtil.dealString(isnotice);
        semName = XssFilterUtil.dealString(semName);
        semPhone = XssFilterUtil.dealString(semPhone);
        int flag = 2;
        List<User> list = us.selectName(name, userIndex);

        if (!CollectionUtils.isEmpty(list)) {
            flag = 0;
            userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            logger.error("修改用户失败，原因是该用户名已存在");
        }

        Example example = new Example(AppUser.class);
        example.createCriteria().andEqualTo("name", name).andNotEqualTo("userIndex", userIndex);
        List<AppUser> appList =appUserMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(appList)) {
            flag = 0;
            userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            logger.error("修改用户失败，原因是该用户名已存在");
        }
        List<User> users = new ArrayList<>();
        users = um.getPhone(phone,0);
        for (User user1 : users) {
            if (!user1.getUserIndex().equals(userIndex)) {
                flag = 3;
                userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                logger.error("修改用户失败，原因是该手机号已被注册");
                break;
            }
        }

        if (flag != 0 && flag != 3) {
            try {
                if (!StringUtils.isBlank(name)) {
                    if (!StringUtils.isBlank(loginName)) {
                        if (!StringUtils.isBlank(email)) {
                            if (!StringUtils.isBlank(phone)) {
                                if (!StringUtils.isBlank(ipGo)) {
                                    if (!StringUtils.isBlank(ipE)) {
                                        //进行用户的所有正则
                                        if (PubUtils.patternName(name)) {
                                            if (PubUtils.patternUsername(loginName)) {
                                                if (PubUtils.patternEmail(email)) {
                                                    if (PubUtils.patternPhone(phone)) {
                                                        if (PubUtils.patternIp(ipGo)) {
                                                            if (PubUtils.patternIp(ipE)) {
                                                                us.updateAppUser(userIndex, name, loginName, deptsIndex, phone, email, ipGo, ipE, time, mark, usertype, isnotice,semName, semPhone);
                                                                flag = 1;
                                                                userLogservice.getLog("修改用户", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                                                                logger.info("修改用户成功");
                                                            } else {
                                                                flag = 4;
                                                                userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                                                                logger.error("结束ip地址格式不正确");
                                                            }
                                                        } else {
                                                            flag = 5;
                                                            userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                                                            logger.error("起始ip地址格式不正确");
                                                        }
                                                    } else {
                                                        flag = 6;
                                                        userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                                                        logger.error("手机号格式不正确，必须有11位，并且为数字，是正常的手机号码开头");
                                                    }
                                                } else {
                                                    flag = 7;
                                                    userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                                                    logger.error("邮箱格式不正确，应含有@ .在@后，以.com、.con结尾（qq,163等）");
                                                }
                                            } else {
                                                flag = 8;
                                                userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                                                logger.error("登录名只能由3-16的字母和数字组成");
                                            }
                                        } else {
                                            flag = 9;
                                            userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                                            logger.error("名称只由中文组成，长度为1-20");
                                        }
                                    } else {
                                        flag = 10;
                                        userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                                        logger.error("结束ip不可为空");
                                    }
                                } else {
                                    flag = 11;
                                    userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                                    logger.error("起始ip不可为空");
                                }
                            } else {
                                flag = 12;
                                userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                                logger.error("邮箱不可为空");
                            }
                        } else {
                            flag = 13;
                            userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                            logger.error("手机号不可为空");
                        }
                    } else {
                        flag = 14;
                        userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                        logger.error("登录名不可为空");
                    }
                } else {
                    flag = 15;
                    userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                    logger.error("名称不可为空");
                }
            } catch (Exception e) {
                flag = 2;
                userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                logger.error(e.toString());
            }
        } else {
            userLogservice.getLog("修改用户", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            logger.error("修改用户失败，原因是该用户名已存在");
        }
        return flag;
    }


    /**
     * 在线用户
     */
    @RequestMapping(value = "getOnlineUsers", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getOnlineUsers(HttpServletRequest request) {
        HttpResult result = new HttpResult();
        List<List> lists = new ArrayList<>();
        //获取redis中缓存的用户列表信息
        try {
            List<UserOnlineBo> list = userSessionManager.getAllUser();
            if (!list.isEmpty()) {
                for (UserOnlineBo userOnlineBo : list) {
                    if (userOnlineBo.getItem().equalsIgnoreCase("被踢")) {
                        continue;
                    }
                    List<String> temp = new ArrayList<>();
                    temp.add(userOnlineBo.getName());
                    temp.add(userOnlineBo.getLoginName());
                    temp.add(userOnlineBo.getPhone());
                    temp.add(PubUtils.date2String(userOnlineBo.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
                    temp.add(PubUtils.date2String(userOnlineBo.getLastAccess(), "yyyy-MM-dd HH:mm:ss"));
                    temp.add(userOnlineBo.isSessionStatus() ? "在线" : "离线");
                    lists.add(temp);
                }
            } else {
                result.setCode(500);
            }
        } catch (Exception e) {
            logger.error("获取在线用户发生异常，异常是"+e.getMessage());
        }
        result.setBody(lists);
        result.setCode(200);
        return result;
    }


    /**
     * 解锁用户
     */
    @PostMapping("unlockUser")
    @ResponseBody
    public HttpResult unlockUser(String userIndex, String token, HttpServletRequest request) {
        HttpResult result = PubUtils.initResult(TokenManager.getToken().getLoginName(), request, LogTypeEnum.SYSTEM.toString(), 1);
        String sessionToken = (String) TokenManager.getSession().getAttribute("token");
        if (!token.equalsIgnoreCase(sessionToken)) {
            return PubUtils.assignmentResultLog(null, 500, "非法访问", "解锁用户", "失败", result);
        }
        try {
            String ip = PubUtils.getIpAddr(request);
            String username = TokenManager.getToken().getLoginName();


                userService.dealUserUnlock(userIndex);
                result = PubUtils.assignmentResultLog(null, 200, "解锁用户成功", "解锁用户", "成功", result);


            jedisManager.deleteByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(username + ip));
        } catch (Exception e) {
            logger.error("解锁用户异常，异常为：" + e.toString());
            result = PubUtils.assignmentResultLog(null, 500, "解锁用户异常", "解锁用户", "失败", result);
        }
        return result;
    }

    /**
     * 激活用户
     */
    @PostMapping("activeUser")
    @ResponseBody
    public HttpResult activeUser(String userIndex, String token, HttpServletRequest request) {
        HttpResult result = PubUtils.initResult(TokenManager.getToken().getLoginName(), request, LogTypeEnum.SYSTEM.toString(), 1);
        String sessionToken = (String) TokenManager.getSession().getAttribute("token");
        if (!token.equalsIgnoreCase(sessionToken)) {
            return PubUtils.assignmentResultLog(null, 500, "非法访问", "激活用户", "失败", result);
        }
        try {
            String ip = PubUtils.getIpAddr(request);
            String username = TokenManager.getToken().getLoginName();

            byte[] value = jedisManager.getValueByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(username + ip));
            String key = SerializeUtil.deserialize(value, String.class);
            if(key.equals("success")){
                userService.dealUserActive(userIndex);
                result = PubUtils.assignmentResultLog(null, 200, "激活用户成功", "激活用户", "成功", result);
            }else{
            	result = PubUtils.assignmentResultLog(null, 400, "激活用户失败,密码验证失败!", "激活用户", "失败", result);
            }

            jedisManager.deleteByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(username + ip));
        } catch (Exception e) {
            logger.error("激活用户异常，异常为：" + e.toString());
            result = PubUtils.assignmentResultLog(null, 500, "激活用户异常", "激活用户", "失败", result);
        }
        return result;
    }

    /**
     * 确认密码
     */
    @PostMapping(value = "confirmPwd")
    @ResponseBody
    public HttpResult confirmPwd(String password, HttpServletRequest request, HttpServletResponse response) {
        String ip = PubUtils.getIpAddr(request);
        String username = TokenManager.getToken().getLoginName();
        password = XssFilterUtil.dealString(password);
        HttpResult result = PubUtils.initResult(TokenManager.getToken().getLoginName(), request, LogTypeEnum.SYSTEM.toString(), 2);
        try {
            //密码处理
            String privateKey = jedisManager.getValueByKey(RedisDB.SHORT_TIME_QUERY, username + ip);
            //秘钥用完即删
            jedisManager.deleteByKey(RedisDB.SHORT_TIME_QUERY, username + ip);
            //对SM2解密面进行验证
            password = PubUtils.getPasswordSM2Verify(privateKey, password);
            if (password == null && password.length() == 0) {
                return PubUtils.assignmentResultLog(null, 500, "密码传输完整性被破坏", "密码确认", "失败", result);
            }
            us.judgeUsernameAndPwd(username, password);
            response.setStatus(203);
            result = PubUtils.assignmentResultLog(null, 200, "密码正确", "密码确认", "成功", result);
            //缓存验证结果
            jedisManager.saveValueByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(username + ip), SerializeUtil.serialize("success"), -1);
        } catch (Exception e) {
            if(e.getMessage().length()>12){
                result = PubUtils.assignmentResultLog(null, 500, "密码确认异常","密码确认","失败",result);
            }else{
                result = PubUtils.assignmentResultLog(null, 500, e.getMessage(),"密码确认","失败",result);
            }
            //缓存验证结果
            jedisManager.saveValueByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(username + ip), SerializeUtil.serialize("fail"), -1);
        }
        return result;
    }

    @PostMapping(value = "confirmUserPwdIndentity")
    @ResponseBody
    public HttpResult confirmUserPwdIndentity(String password, HttpServletRequest request, HttpServletResponse response) {
        String ip = PubUtils.getIpAddr(request);
        String username = TokenManager.getToken().getLoginName();
        password = XssFilterUtil.dealString(password);
        HttpResult result = PubUtils.initResult(TokenManager.getToken().getLoginName(), request, LogTypeEnum.SYSTEM.toString(), 2);
        try {
            //密码处理
            String privateKey = jedisManager.getValueByKey(RedisDB.SHORT_TIME_QUERY, username + ip);
            //秘钥用完即删
            jedisManager.deleteByKey(RedisDB.SHORT_TIME_QUERY, username + ip);
            //对SM2解密面进行验证
            password = PubUtils.getPasswordSM2Verify(privateKey, password);
            if (password == null && password.length() == 0) {
                return PubUtils.assignmentResultLog(null, 500, "密码传输完整性被破坏", "密码确认", "失败", result);
            }
            //us.judgeUsernameAndPwd(username, password);
            //缓存验证结果
            if(password.equals("njcnpqs")){
                response.setStatus(203);
                result = PubUtils.assignmentResultLog(null, 200, "密码正确", "密码确认", "成功", result);
                //缓存验证结果
                jedisManager.saveValueByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(username + ip), SerializeUtil.serialize("success"), -1);
            }else {
                result = PubUtils.assignmentResultLog(null, 500, "密码确认异常","密码确认","失败",result);
                //缓存验证结果
                jedisManager.saveValueByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(username + ip), SerializeUtil.serialize("fail"), -1);
            }
        } catch (Exception e) {
            if(e.getMessage().length()>12){
                result = PubUtils.assignmentResultLog(null, 500, "密码确认异常","密码确认","失败",result);
            }else{
                result = PubUtils.assignmentResultLog(null, 500, e.getMessage(),"密码确认","失败",result);
            }
            //缓存验证结果
            jedisManager.saveValueByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(username + ip), SerializeUtil.serialize("fail"), -1);
        }
        return result;
    }

    /**
     * 确认密码
     */
    @PostMapping(value = "confirmIndentity")
    @ResponseBody
    public HttpResult confirmIndentity(String password, HttpServletRequest request, HttpServletResponse response) {
        String ip = PubUtils.getIpAddr(request);
        String username = TokenManager.getToken().getLoginName();
        password = XssFilterUtil.dealString(password);
        HttpResult result = PubUtils.initResult(TokenManager.getToken().getLoginName(), request, LogTypeEnum.SYSTEM.toString(), 2);
        try {
            //密码处理
            String privateKey = jedisManager.getValueByKey(RedisDB.SHORT_TIME_QUERY, username + ip);
            //秘钥用完即删
            jedisManager.deleteByKey(RedisDB.SHORT_TIME_QUERY, username + ip);
            //对SM2解密面进行验证
            password = PubUtils.getPasswordSM2Verify(privateKey, password);
            if (password == null && password.length() == 0) {
                return PubUtils.assignmentResultLog(null, 500, "密码传输完整性被破坏", "密码确认", "失败", result);
            }
            String resetPassword = PubUtils.getConfirmIndentity();
            //缓存验证结果
            if(password.equals(resetPassword)){
                response.setStatus(203);
                result = PubUtils.assignmentResultLog(null, 200, "密码正确", "密码确认", "成功", result);
                //缓存验证结果
                jedisManager.saveValueByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(username + ip), SerializeUtil.serialize("success"), -1);
            }else {
                result = PubUtils.assignmentResultLog(null, 500, "密码确认异常","密码确认","失败",result);
                //缓存验证结果
                jedisManager.saveValueByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(username + ip), SerializeUtil.serialize("fail"), -1);
            }
        } catch (Exception e) {
            if(e.getMessage().length()>12){
                result = PubUtils.assignmentResultLog(null, 500, "密码确认异常","密码确认","失败",result);
            }else{
                result = PubUtils.assignmentResultLog(null, 500, e.getMessage(),"密码确认","失败",result);
            }
            //缓存验证结果
            jedisManager.saveValueByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(username + ip), SerializeUtil.serialize("fail"), -1);
        }
        return result;
    }

    @PostMapping("judgeuserstate")
    @ResponseBody
    public String translateUser() {
        List<User> list = userMapper.getAllUser();
        List<SysSet> sysset = sm.selectAll();

        if (sysset == null || sysset.size() == 0) {
            return "success";
        }

        String lostName = "";
        int limitidle = sysset.get(0).getLimitIdle().intValue();
        int limitlogout = sysset.get(0).getLimitLogout().intValue();
        int casualusertime = sysset.get(0).getCasualUserTime().intValue();
        int logouttime = sysset.get(0).getLogOutTime().intValue();

        for (User user : list) {
            if (user.getCasualUser().intValue() == 0) {
                Calendar calendar2 = Calendar.getInstance();
                calendar2.setTime(user.getLoginTime());
                calendar2.add(Calendar.MONTH, limitidle + limitlogout);
                Calendar now = Calendar.getInstance();
                Calendar calendar3 = Calendar.getInstance();
                calendar3.setTime(calendar2.getTime());
                calendar3.add(Calendar.DAY_OF_MONTH, -2);

                //增加告警机制，在注销的前两天进行弹窗告警提示
                if (now.after(calendar3) && now.before(calendar2) && user.getState().intValue() == 4) {
                    lostName += user.getName() + "\n";
                }
            } else {
                Calendar calendar1 = Calendar.getInstance();
                calendar1.setTime(user.getRegisterTime());
                calendar1.add(Calendar.MONTH, casualusertime + logouttime); //休眠后检测是否需要激活，如果超过期限未激活则注销该账号*/
                Calendar calendar2 = Calendar.getInstance();
                calendar2.setTime(calendar1.getTime());
                calendar2.add(Calendar.DAY_OF_MONTH, -2);
                Calendar now = Calendar.getInstance();

                //增加告警机制，在注销的前两天进行弹窗告警提示
                if (user.getState().intValue() == 4 && now.after(calendar2) && now.before(calendar1)) {
                    lostName += user.getName() + "\n";
                }
            }
        }

        if (lostName.equals("")) {
            return "success";
        }

        lostName += "用户即将到达休眠期限，请及时处理！";
        return lostName;
    }

}
