package com.njcn.serviceimpl.user;

import com.njcn.enums.RoleEnum;
import com.njcn.enums.RoleGroupEnum;
import com.njcn.enums.TerminalLogsEnum;
import com.njcn.enums.UserStatusEnum;
import com.njcn.enums.app.UserLevelEnum;
import com.njcn.mapper.app.AppInfoSetMapper;
import com.njcn.mapper.configuration.SysMapper;
import com.njcn.mapper.configuration.TerminalLogsMapper;
import com.njcn.mapper.user.*;
import com.njcn.pojo.app.AppInfoSet;
import com.njcn.pojo.commons.AreaInfo;
import com.njcn.pojo.configuration.TerminalLogs;
import com.njcn.pojo.user.*;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.service.user.SecretKeyService;
import com.njcn.service.user.UserService;
import com.njcn.shiro.realm.DataRealm;
import com.njcn.shiro.token.TokenManager;
import com.njcn.sso.pojo.user.User;
import com.njcn.utils.*;
import com.njcn.utils.SM.SM4Utils;
import com.njcn.utils.redis.RedisCacheUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;

@Service
public class UserServiceImpl implements UserService {
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Resource
    UserMapper um;
    @Resource
    SecretKeyMapper secretKeyMapper;
    @Autowired
    SecretKeyService secretKeyService;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    DeptsMapper deptsMapper;
    @Autowired
    RoleGroupMapper rolegroupMapper;
    @Autowired
    private UserUtil userUtil;
    @Autowired
    UserLogDetailService userLogservice;
    @Autowired
    private RedisCacheUtil redisCacheUtil;
    @Autowired
    private UserSetMapper usm;
    @Autowired
    private RoleGPAssMapper roleGPAssMapper;
    @Autowired
    private UserSetMapper userSetMapper;
    @Autowired
    private AppConfig appConfig;

    @Autowired
    private SysMapper sysSetMapper;

    @Autowired
    private AppUserMapper appUserMapper;

    @Autowired
    private AppInfoSetMapper appInfoSetMapper;

    @Autowired
    private TerminalLogsMapper terminalLogsMapper;

    /**
     * 根据系统类型查询所有角色组
     */
    @Override
    public List<Role> selectAll() {
        String sysType = TokenManager.getSysType();
        List<String> roleDescription = new ArrayList<>();
        roleDescription.add(RoleEnum.AUDIT.getEname());
        roleDescription.add(RoleEnum.BUSINESS.getEname());
        roleDescription.add(RoleEnum.CHECK.getEname());
        roleDescription.add(RoleEnum.ROOT.getEname());
        roleDescription.add(RoleEnum.SYSTEM.getEname());
        List<Role> roleGroups = roleMapper.selectAlls(roleDescription);
        if (roleGroups.isEmpty()) {
            roleGroups = null;
        }
        return roleGroups;
    }

    /**
     * 更新用户信息
     */
    @Override
    public void updateUser(String userIndex, String name, String loginName, String deptsIndex, String phone, String email, String ipGo, String ipE, String time, Integer mark, String usertype,String isnotice) {
        User user = new User();
        user.setUserIndex(userIndex);
        user = um.selectOne(user);
        user.setUserIndex(userIndex);
        user.setName(name);
        user.setLoginName(loginName);
        Date loginTime = new Date();
        user.setLoginTime(loginTime);
        user.setPhone(phone);
        user.setEmail(email);
        user.setMark(mark);
        user.setState(3);
        user.setLimitIpStart(ipGo);
        user.setLimitIpEnd(ipE);
        user.setLimitTime(time);

        if (usertype.equals("1")) {
            user.setCasualUser(1);
        } else {
            user.setCasualUser(0);
        }

        um.updateByPrimaryKeyBySql(user);
        UserSet userSet = new UserSet();
        userSet.setUserIndex(userIndex);
        userSet = usm.selectOne(userSet);
        String roleIndex = userSet.getRoleGpIndex();
        if (null == userSet) {
            //说明是第一次插入，之前没有用户配置信息
            userSet = new UserSet();
            userSet.setUserSetIndex(UUID.randomUUID().toString());
            userSet.setUserIndex(userIndex);//user关系Guid
            if (isnotice.equals("1")) {
                userSet.setIsNotice(1);
            } else {
                userSet.setIsNotice(0);
            }
            userSet.setRoleGpIndex(roleIndex);
            userSet.setDeptsIndex(deptsIndex);
            usm.insert(userSet);
        } else {
            userSet.setUserIndex(userIndex);
            userSet.setDeptsIndex(deptsIndex);
            userSet.setRoleGpIndex(roleIndex);
            if (isnotice.equals("1")) {
                userSet.setIsNotice(1);
            } else {
                userSet.setIsNotice(0);
            }
            String sysType = TokenManager.getSysType();
            usm.updateByPrimaryKey(userSet);
        }
    }

    @Override
    public void updateAppUser(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) {
        User user = new User();
        user.setUserIndex(userIndex);
        user = um.selectOne(user);
        user.setUserIndex(userIndex);
        user.setName(name);
        user.setLoginName(loginName);
        Date loginTime = new Date();
        user.setLoginTime(loginTime);
        user.setPhone(phone);
        user.setEmail(email);
        user.setMark(mark);
        user.setState(3);
        user.setLimitIpStart(ipGo);
        user.setLimitIpEnd(ipE);
        user.setLimitTime(time);

        if (usertype.equals("1")) {
            user.setCasualUser(1);
        } else {
            user.setCasualUser(0);
        }

        AppUser appUser = new AppUser();
        appUser.setUserIndex(userIndex);
        appUser.setName(name);
        appUser.setLoginName(loginName);
        appUser.setLoginTime(new Date());
        appUser.setPhone(phone);
        appUser.setEmail(email);
        appUser.setSemName(semName);
        appUser.setSemPhone(semPhone);
        appUserMapper.updateAppByPrimaryKeyBySql(appUser);

        um.updateByPrimaryKeyBySql(user);
        UserSet userSet = new UserSet();
        userSet.setUserIndex(userIndex);
        userSet = usm.selectOne(userSet);
        String roleIndex = userSet.getRoleGpIndex();
        if (null == userSet) {
            //说明是第一次插入，之前没有用户配置信息
            userSet = new UserSet();
            userSet.setUserSetIndex(UUID.randomUUID().toString());
            userSet.setUserIndex(userIndex);//user关系Guid
            if (isnotice.equals("1")) {
                userSet.setIsNotice(1);
            } else {
                userSet.setIsNotice(0);
            }
            userSet.setRoleGpIndex(roleIndex);
            userSet.setDeptsIndex(deptsIndex);
            usm.insert(userSet);
        } else {
            userSet.setUserIndex(userIndex);
            userSet.setDeptsIndex(deptsIndex);
            userSet.setRoleGpIndex(roleIndex);
            if (isnotice.equals("1")) {
                userSet.setIsNotice(1);
            } else {
                userSet.setIsNotice(0);
            }
            String sysType = TokenManager.getSysType();
            usm.updateByPrimaryKey(userSet);
        }

    }

    /**
     * 通过用户ID获取用户的信息回显，以便修改
     *
     * @param userIndex 用户索引
     */
    @Override
    public User selectId(String userIndex, int flag) {
        //获取用户信息
        User user = um.selectId(userIndex);
        //获取用户配置信息
        UserSet userSet = userUtil.getUserSet(userIndex);
        if (null == user) {
            return null;
        }
        if (null == userSet) {
            user.setDeptsName("暂无部门");
            user.setRoleGPIndex("暂无角色");
        } else if (flag == 1) {
            if (getRoleNames(userSet.getRoleGpIndex()).equals("系统管理员") || getRoleNames(userSet.getRoleGpIndex()).equals("审核管理员") ||
                    getRoleNames(userSet.getRoleGpIndex()).equals("审计管理员") || getRoleNames(userSet.getRoleGpIndex()).equals("业务管理员")) {
                //标识只有修改密码功能
                return null;
            } else {
                user.setDeptsName(userSet.getDeptsIndex());
                user.setRoleGPIndex(userSet.getRoleGpIndex());
            }
        }
        user.setPassword("");
        //获取当前系统type下的所有部门信息
//        List<Depts> deptsList = userUtil.getDeptsBySysType(TokenManager.getSysType());
        List<Depts> deptsList = userUtil.getDepts();
        user.setDeptsList(deptsList);
        //获取当前系统下的所有角色组信息
        List<String> roleDescription = new ArrayList<>();
        roleDescription.add(RoleEnum.AUDIT.getEname());
        roleDescription.add(RoleEnum.BUSINESS.getEname());
        roleDescription.add(RoleEnum.CHECK.getEname());
        roleDescription.add(RoleEnum.ROOT.getEname());
        roleDescription.add(RoleEnum.SYSTEM.getEname());
        List<Role> roleGroups = roleMapper.selectAlls(roleDescription);
        user.setRoleGroups(roleGroups);
        user.setIsnotice(userSet.getIsNotice());
        return user;
    }

    @Override
    public List<List> selectAllUsers() {
        List<List> lists = new ArrayList<>();
        Example example = new Example(UserSet.class);
        List<UserSet> userSets = usm.selectByExample(example);
        if (!userSets.isEmpty()) {
            for (UserSet userSet : userSets) {
                List<String> str = new ArrayList<>();
                String userIndex = userSet.getUserIndex();
                Example example1 = new Example(User.class);
                Example.Criteria criteria1 = example1.createCriteria();
                criteria1.andEqualTo("userIndex", userIndex);
                criteria1.andEqualTo("state", 3);
                List<User> users = um.selectByExample(example1);
                if (!users.isEmpty()) {
                    for (User user : users) {
                        str.add(user.getUserIndex());
                        str.add(user.getName());
                        str.add(user.getLoginName());
                        if (!StringUtils.isBlank(userSet.getRoleGpIndex())) {
                            str.add(getRoleGPNames(userSet.getRoleGpIndex()));
                        } else {
                            str.add("暂无角色");
                        }
                        Depts depts = userUtil.getDeptsByIndex(userSet.getDeptsIndex());
                        if (depts != null) {
                            str.add(depts.getDeptsName());
                        } else {
                            str.add("暂无部门");
                        }
                        if (user.getState() == 0) {
                            str.add("注销");
                        } else if (user.getState() == 1) {
                            str.add("正常");
                        } else if (user.getState() == 2) {
                            str.add("锁定");
                        } else if (user.getState() == 3) {
                            str.add("待审核");
                        } else if (user.getState() == 4) {
                            str.add("休眠");
                        } else if (user.getState() == 5) {
                            str.add("密码过期");
                        } else {
                            str.add("未知");
                        }
                        lists.add(str);
                    }
                }
            }
        }
        return lists;
    }

    /**
     * 获取所有管理员信息
     *
     * @param userState 用户状态
     */
    @Override
    public List<User> getAllManagers(String userState) {
        List<Integer> userSta = new ArrayList<>();
        List<String> roleGroupNames = new ArrayList<>();
        //将审计、审核、业务、系统的全部查出来
        roleGroupNames.add(RoleGroupEnum.AUDIT.getEname());
        roleGroupNames.add(RoleGroupEnum.CHECK.getEname());
        roleGroupNames.add(RoleGroupEnum.BUSINESS.getEname());
        roleGroupNames.add(RoleGroupEnum.SYSTEM.getEname());
        List<User> users;
        if (StringUtils.isEmpty(userState)) {
            userSta.add(0);//注销
            userSta.add(1);//正常
            userSta.add(2);//锁定
            userSta.add(3);//未审核
            userSta.add(4);//休眠
            userSta.add(5);//修改密码
        } else {
            userSta.add(Integer.parseInt(userState));
        }
        Map<String, Object> optionMap = new HashMap<>(8);
        optionMap.put("userState", userSta);
        optionMap.put("roleGroupNames", roleGroupNames);
        users = um.selectAllManagers(optionMap);
        if (!users.isEmpty()) {
            for (User user : users) {
                RoleGroup roleGroup = userUtil.getRolesSys(user.getUserIndex());
                //角色名
                user.setRoleGPIndex(getManagerName(roleGroup.getRoleGpIndex()));
                user.setPassword("");
            }
        }
        return users;
    }

    @Override
    public AppUser selectAppId(String userIndex) {
        AppUser appUser = new AppUser();
        appUser.setUserIndex(userIndex);
        appUser = appUserMapper.selectByPrimaryKey(appUser);
        return appUser;
    }


    /**
     * 根据角色组获取下属角色名
     *
     * @param roleGPIndex 角色组索引
     */
    private String getManagerName(String roleGPIndex) {
        RoleGPAss roleGPAss = new RoleGPAss();
        roleGPAss.setRoleGpIndex(roleGPIndex);
        roleGPAss.setSysType(appConfig.getSysType());
        List<RoleGPAss> roleGPAsses = roleGPAssMapper.select(roleGPAss);
        String roleName = "";
        if (roleGPAsses.equals(null) || roleGPAsses.isEmpty()) {
            return "暂无角色";
        } else {
            for (int i = 0; i < roleGPAsses.size(); i++) {
                Role role = new Role();
                role.setRoleIndex(roleGPAsses.get(i).getRoleIndex());
                role = roleMapper.selectOne(role);
                roleName = roleName + role.getRoleDescription() + ",";
            }
            roleName = roleName.substring(0, roleName.lastIndexOf(","));
        }
        return roleName;
    }


    /**
     * 获取所有用户
     */
    @Override
    public List<User> selectAllUser(String userState, String careUser, int resultNum) {
        //获取当前登录的用户
        List<Role> roGP = userUtil.getRoles(TokenManager.getUserId());
        String rolrN = getRole(roGP);
        List<Integer> userSta = new ArrayList<>();
        List<Integer> carUser = new ArrayList<>();
        List<User> users = new ArrayList<>();
        List<String> roleName = new ArrayList<>();
        if (userState.equals("")) {
            userSta.add(0);//注销
            userSta.add(1);//正常
            userSta.add(2);//锁定
            userSta.add(3);//未审核
            userSta.add(4);//休眠
            userSta.add(5);//修改密码
        } else {
            userSta.add(Integer.parseInt(userState));
        }
        if (careUser.equals("")) {
            carUser.add(0);
            carUser.add(1);
        } else {
            carUser.add(Integer.parseInt(careUser));
        }
        Map<String, Object> optionMap = new HashMap<>();
        optionMap.put("userState", userSta);
        optionMap.put("careUser", carUser);
        if (rolrN.equals("系统管理员")) {

            List<RoleGroup> roleGroups = new ArrayList<>();
            roleGroups = rolegroupMapper.selectAll();
            for (RoleGroup roleGroup : roleGroups) {
                if (!roleGroup.getRoleGpName().equals(RoleGroupEnum.SYSTEM.getEname()) && !roleGroup.getRoleGpName().equals(RoleGroupEnum.ROOT.getEname())
                        && !roleGroup.getRoleGpName().equals(RoleGroupEnum.BUSINESS.getEname()) && !roleGroup.getRoleGpName().equals(RoleGroupEnum.CHECK.getEname()) &&
                        !roleGroup.getRoleGpName().equals(RoleGroupEnum.AUDIT.getEname())) {
                    roleName.add(roleGroup.getRoleGpName());
                }
            }

        } else {
            roleName.add(RoleGroupEnum.SYSTEM.getEname());
        }
        optionMap.put("roleName", roleName);
        if (resultNum == 0) {
            users = um.selectNormalAndCasualUser(optionMap);
        } else {
            users = um.selectNormalAndCasualUsers(optionMap);
        }
//        Example example = new Example(User.class);
//        Example.Criteria criteria = example.createCriteria();
//        Vector vector = new Vector(2);
//        Vector vectoCare = new Vector(2);
//        if (userState.equals("")) {
//            vector.add(0);//注销
//            vector.add(1);//正常
//            vector.add(2);//锁定
//            vector.add(3);//未审核
//            vector.add(4);//休眠
//            vector.add(5);//修改密码
//        } else {
//            vector.add(Integer.parseInt(userState));
//        }
//        if (careUser.equals("")) {
//            vectoCare.add(0);
//            vectoCare.add(1);
//        } else {
//            vectoCare.add(Integer.parseInt(careUser));
//        }
//        criteria.andIn("state", vector);
//        criteria.andIn("casualUser", vectoCare);
//        example.setOrderByClause("LOGINTIME  desc");
//        List<User> users = um.selectByExample(example);
        if (!users.isEmpty()) {
            for (User user : users) {
                RoleGroup role = userUtil.getRolesSys(user.getUserIndex());

                //角色名
                user.setRoleGPIndex(getRoleGPNames(role.getRoleGpIndex()));
                Depts depts = userUtil.getDeptsByUser(user);
                if (depts != null) {
                    user.setDeptsName(depts.getDeptsName());
                } else {
                    user.setDeptsName("暂无部门");
                }
                if (role.getRolegpDescription().equals("管理员组")) {
                    //标识只有修改密码功能
                    user.setItem("system");
                }
                user.setPassword("");
//                else {
//                    str.add("<button type='button' class='btn  btn-primary  mr10'  onclick='updateUserPassWordByIndex(\"" + user.getUserIndex() + "\")' ><i class='fa fa-vcard-o'></i>修改密码</button>"
//                            + "<button type='button' class='btn  btn-primary mr10'  onclick='updateUserByIndex(\"" + user.getUserIndex() + "\")' ><i class='fa fa-edit'></i>修改</button>"
//                            + "<button type='button' class='btn  btn-danger  mr10'  onclick='deleteUserByIndex(\"" + user.getUserIndex() + "\")' ><i class='fa fa-trash'></i>注销</button>"
//                    );
//                }
            }
        }
        return users;
    }


    /**
     * 获取用户当前的状态
     *
     * @param state 用户状态
     */
    private String getUserState(int state) {
        String status;
        switch (state) {
            case 0:
                status = "注销";
                break;
            case 1:
                status = "正常";
                break;
            case 2:
                status = "锁定";
                break;
            case 3:
                status = "待审核";
                break;
            case 4:
                status = "休眠";
                break;
            case 5:
                status = "密码过期";
                break;
            default:
                status = "未知";
                break;
        }
        return status;
    }

    /**
     * 根据角色组获取下属角色名
     *
     * @param roleGPIndex 角色组索引
     */
    private String getRoleNames(String roleGPIndex) {
        List<String> roles = roleMapper.getRoles(roleGPIndex);
        if (roles.isEmpty()) {
            return "暂无角色";
        }
        String roleName = "";
        for (String string : roles) {
            roleName = roleName + string + ",";
        }
        roleName = roleName.substring(0, roleName.lastIndexOf(","));
        return roleName;
    }

    /**
     * 根据角色组获取下属角色名
     *
     * @param roleGPIndex 角色组索引
     */
    private String getRoleGPNames(String roleGPIndex) {
        RoleGPAss roleGPAss = new RoleGPAss();
        roleGPAss.setRoleGpIndex(roleGPIndex);
        roleGPAss.setSysType(TokenManager.getSysType());
        List<RoleGPAss> roleGPAsses = roleGPAssMapper.select(roleGPAss);
        String roleName = "";
        if (roleGPAsses.equals(null) || roleGPAsses.isEmpty()) {
            return "暂无角色";
        } else {
            for (int i = 0; i < roleGPAsses.size(); i++) {
                Role role = new Role();
                role.setRoleIndex(roleGPAsses.get(i).getRoleIndex());
                role = roleMapper.selectOne(role);
                roleName = roleName + role.getRoleDescription() + ",";
            }
            roleName = roleName.substring(0, roleName.lastIndexOf(","));
        }
        return roleName;
    }


    /***
     * 获取所有的角色信息
     */
    private String getRole(List<Role> roles) {
        if (roles.isEmpty()) {
            return "暂无角色";
        }
        String roleName = "";
        for (Role role : roles) {
            roleName = roleName + role.getRoleDescription() + ",";
        }
        roleName = roleName.substring(0, roleName.lastIndexOf(","));
        return roleName;
    }

    /**
     * 天溯新增用户
     */
    @Override
    public void saveUser(JSONArray userList) {
        logger.error("循环前保存用户信息，用户信息为" + userList.toString());
        for (int i = 0; i < userList.size(); i++) {
            JSONObject jsonObject = userList.getJSONObject(i);
            logger.error("循环保存用户信息，用户信息为" + jsonObject.toString());
            User user = new User();
            user.setName(jsonObject.getString("name"));
            user.setUserIndex(jsonObject.getString("id"));
            user.setLoginName("TS" + jsonObject.getString("userid"));
            String strmd5 = MD5.twiceMD5("@#001njcnpqs");//两次md5加密
            String secretkey = PubUtils.GetSecretKey();//随机产生工作秘钥
            String strpwd = ThreeDes.encryptThreeDes_64(strmd5 + secretkey);//3des加密
            user.setPassword(strpwd);
            user.setPhone("15151002796");
            user.setEmail("83944980@qq.com");
            user.setRegisterTime(new Date());
            user.setPsdvalidity(new Date());
            user.setLoginTime(new Date());
            user.setMark(1);
            user.setLimitIpStart("127.0.0.1");
            user.setLimitIpEnd("255.255.255.255");
            user.setLimitTime("0-24");
            user.setLoginErrorTimes(0);
            //新插入的用户，用户状态为1
            user.setState(1);
            um.insert(user);
            //保存用户配置信息
            UserSet userSet = new UserSet();
            userSet.setUserSetIndex(UUID.randomUUID().toString());//用户配置表Guid
            userSet.setUserIndex(jsonObject.getString("id"));//user关系Guid
            userSet.setIsNotice(0);
            userSet.setRoleGpIndex("a3f6736b-5ea4-4aee-8ef5-6a117a490a0e");
            userSet.setDeptsIndex("10013");
            usm.insert(userSet);
            //保存用户密码加密信息
            SecretKey secretKey1 = new SecretKey();
            secretKey1.setSecretKeyIndex(UUID.randomUUID().toString());
            secretKey1.setUserIndex(jsonObject.getString("id"));
            secretKey1.setSecretKey(secretkey);
            secretKey1.setStandBy(strmd5);
            secretKeyMapper.insert(secretKey1);
            logger.error("循环前保存用户信息完毕，用户信息为" + user.toString());
        }
    }

    /**
     * 处理天溯用户信息增量变化
     *
     * @param changData 增量体
     */
    @Override
    public void doChangeData(JSONObject changData) {
        JSONArray add = changData.getJSONArray("add");
        JSONArray update = changData.getJSONArray("update");
        JSONArray delete = changData.getJSONArray("delete");
        if (!(null == add || add.isEmpty())) {
            //执行新增
            saveUser(add);
        }
        if (!(null == update || update.isEmpty())) {
            //执行更新，目前就3个参数，不知道更新什么，暂时不管
        }
        if (!(null == delete || delete.isEmpty())) {
            //执行注销
            deleteUser(delete);
        }
    }


    /**
     * 天溯接口中存在需要注销的用户信息
     *
     * @param delete 需要注销的用户信息
     */
    public void deleteUser(JSONArray delete) {
        for (int i = 0; i < delete.size(); i++) {
            JSONObject tsUser = delete.getJSONObject(i);
            String userId = tsUser.getString("id");
            //暂时我做物理注销
            Example example = new Example(User.class);
            example.createCriteria().andEqualTo("userIndex", userId);
            um.deleteByExample(example);
            Example example1 = new Example(UserSet.class);
            example1.createCriteria().andEqualTo("userIndex", userId);
            usm.deleteByExample(example1);
            Example example2 = new Example(SecretKey.class);
            example2.createCriteria().andEqualTo("userIndex", userId);
            secretKeyMapper.deleteByExample(example2);
        }
    }


    /**
     * 根据用户名重置用户密码
     *
     * @param username 用户名
     * @param password 新密码
     */
    @Override
    public void modifyPassword(String username, String password) {
        User user = new User();
        user.setLoginName(username);
        user = um.selectOne(user);
        if (user == null) {
            throw new AccountException("登录名无效");
        }
        /*String strmd5 = MD5.twiceMD5(password);//两次md5加密
        String secretkey = PubUtils.GetSecretKey();//随机产生工作秘钥
        String strpwd = ThreeDes.encryptThreeDes_64(strmd5 + secretkey);//3des加密
        if (strpwd.equalsIgnoreCase(user.getPassword())) {
            throw new AccountException("密码不可与上次相同");
        }*/
        SecretKey secretKey1 = new SecretKey();
        secretKey1.setUserIndex(user.getUserIndex());
        secretKey1 = secretKeyMapper.selectOne(secretKey1);
        if (secretKey1 == null) {
            throw new AccountException("缺少用户配置文件");
        }

        String secretkey = "";//随机产生工作秘钥
        String strsm4 = "";//SM4加密密码
        String strpwd = "";//SM4加密(密码+工作秘钥）
        String stroldpwd = "";//老密码
        try {
            secretkey = PubUtils.GetSecretKey();//随机产生工作秘钥
            SM4Utils sm4 = new SM4Utils(secretkey);
            strsm4 = sm4.encryptData_ECB(password);//SM4加密密码
            strpwd = sm4.encryptData_ECB(strsm4 + secretkey);//SM4加密(密码+工作秘钥）

            //用老的工作秘钥去加密新的密码（假如两个一样则密码重复）
            sm4.setSecretKey(secretKey1.getSecretKey());
            stroldpwd = sm4.encryptData_ECB(sm4.encryptData_ECB(password) + secretKey1.getSecretKey());//SM4加密(密码+工作秘钥）
        } catch (Exception ex) {
            throw new AccountException("用户密码国密加密失败");
        }
        if (stroldpwd.equalsIgnoreCase(user.getPassword())) {
            throw new AccountException("密码不可与上次相同");
        }
        user.setPassword(strpwd);
        user.setPsdvalidity(new Date());
        user.setLoginTime(user.getPsdvalidity());
        user.setState(1);
        secretKey1.setSecretKey(secretkey);
        secretKey1.setStandBy(strsm4);
        //更新用户
        um.updateByPrimaryKeyBySql(user);
        secretKeyMapper.updateByPrimaryKey(secretKey1);
    }

    @Override
    public void modifyAppPassword(String username, String password) {
        User user = new User();
        user.setLoginName(username);
        user = um.selectOne(user);
        if (user == null) {
            throw new AccountException("登录名无效");
        }
        /*String strmd5 = MD5.twiceMD5(password);//两次md5加密
        String secretkey = PubUtils.GetSecretKey();//随机产生工作秘钥
        String strpwd = ThreeDes.encryptThreeDes_64(strmd5 + secretkey);//3des加密
        if (strpwd.equalsIgnoreCase(user.getPassword())) {
            throw new AccountException("密码不可与上次相同");
        }*/
        SecretKey secretKey1 = new SecretKey();
        secretKey1.setUserIndex(user.getUserIndex());
        secretKey1 = secretKeyMapper.selectOne(secretKey1);
        if (secretKey1 == null) {
            throw new AccountException("缺少用户配置文件");
        }

        String secretkey = "";//随机产生工作秘钥
        String strsm4 = "";//SM4加密密码
        String strpwd = "";//SM4加密(密码+工作秘钥）
        String stroldpwd = "";//老密码
        String pwd = "";//app密码
        try {
            secretkey = PubUtils.GetSecretKey();//随机产生工作秘钥
            SM4Utils sm4 = new SM4Utils(secretkey);
            strsm4 = sm4.encryptData_ECB(password);//SM4加密密码
            strpwd = sm4.encryptData_ECB(strsm4 + secretkey);//SM4加密(密码+工作秘钥）

            //用老的工作秘钥去加密新的密码（假如两个一样则密码重复）
            sm4.setSecretKey(secretKey1.getSecretKey());
            stroldpwd = sm4.encryptData_ECB(sm4.encryptData_ECB(password) + secretKey1.getSecretKey());//SM4加密(密码+工作秘钥）

            //app密码
            pwd = AESUtil.aesPKCS5PaddingEncrypt(password);
        } catch (Exception ex) {
            throw new AccountException("用户密码国密加密失败");
        }
        if (stroldpwd.equalsIgnoreCase(user.getPassword())) {
            throw new AccountException("密码不可与上次相同");
        }
        user.setPassword(strpwd);
        user.setPsdvalidity(new Date());
        user.setLoginTime(user.getPsdvalidity());
        user.setState(1);
        secretKey1.setSecretKey(secretkey);
        secretKey1.setStandBy(strsm4);
        //更新用户
        um.updateByPrimaryKeyBySql(user);
        secretKeyMapper.updateByPrimaryKey(secretKey1);
        AppUser appUser = new AppUser();
        appUser.setLoginName(username);
        appUser.setPassword(pwd);
        appUserMapper.updateAppByPrimaryKeyBySql(appUser);
    }


    /**
     * 新增用户
     */
    @Override
    public String 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) throws Exception {
        //正则表达
        if (!StringUtils.isBlank(name)) {
            if (!StringUtils.isBlank(loginName)) {
                if (!StringUtils.isBlank(password)) {
                    if (!StringUtils.isBlank(email)) {
                        if (!StringUtils.isBlank(phone)) {
                            if (!StringUtils.isBlank(ip)) {
                                if (!StringUtils.isBlank(ipEnd)) {
                                    //进行用户的所有正则
                                    if (PubUtils.patternName(name)) {
                                        if (PubUtils.patternUsername(loginName)) {
                                            if (PubUtils.patternPassword(password)) {
                                                if (PubUtils.patternEmail(email)) {
                                                    if (PubUtils.patternPhone(phone)) {
                                                        if (PubUtils.patternIp(ip)) {
                                                            if (PubUtils.patternIp(ipEnd)) {
                                                                List<User> users = new ArrayList<>();
                                                                users = um.getPhone(phone, 0);
                                                                //名称不能重复
                                                                if (users.size() > 0) {
                                                                    return "该手机号已被注册";
                                                                }
                                                                User user = new User();
                                                                user.setName(name);
                                                                user = um.selectOne(user);


                                                                if (null == user) {
                                                                    //登录名不能重复
                                                                    user = new User();
                                                                    user.setLoginName(loginName);
                                                                    user = um.selectOne(user);
                                                                    if (null == user) {
                                                                        //保存用户基本信息
                                                                        User temp = new User();
                                                                        String userIndex = UUID.randomUUID().toString();
                                                                        temp.setUserIndex(userIndex);
                                                                        temp.setName(name);
                                                                        temp.setLoginName(loginName);

                                                                        if (usertype.equals("1")) {
                                                                            temp.setCasualUser(1); //临时用户
                                                                        } else {
                                                                            temp.setCasualUser(0);
                                                                        }

                /*String strmd5 = MD5.twiceMD5(password);//两次md5加密
                String secretkey = PubUtils.GetSecretKey();//随机产生工作秘钥
                String strpwd = ThreeDes.encryptThreeDes_64(strmd5 + secretkey);//3des加密*/

                                                                        String secretkey = "";//随机产生工作秘钥
                                                                        String strsm4 = "";//SM4加密密码
                                                                        String strpwd = "";//SM4加密(密码+工作秘钥）
                                                                        try {
                                                                            secretkey = PubUtils.GetSecretKey();//随机产生工作秘钥
                                                                            SM4Utils sm4 = new SM4Utils(secretkey);
                                                                            strsm4 = sm4.encryptData_ECB(password);//SM4加密密码
                                                                            strpwd = sm4.encryptData_ECB(strsm4 + secretkey);//SM4加密(密码+工作秘钥）
                                                                        } catch (Exception ex) {
                                                                            return "用户密码国密加密失败";
                                                                        }

                                                                        temp.setPassword(strpwd);
                                                                        temp.setPhone(phone);
                                                                        temp.setEmail(email);
                                                                        temp.setRegisterTime(new Date());
                                                                        temp.setPsdvalidity(new Date());
                                                                        temp.setLoginTime(new Date());
                                                                        temp.setMark(mark);
                                                                        temp.setLimitIpStart(ip);
                                                                        temp.setLimitIpEnd(ipEnd);
                                                                        temp.setLimitTime(time);
                                                                        temp.setLoginErrorTimes(0);
                                                                        //新插入的用户，用户状态为3 待审核
                                                                        temp.setState(3);
                                                                        //保存用户密码加密信息
                                                                        SecretKey secretKey1 = new SecretKey();
                                                                        secretKey1.setSecretKeyIndex(UUID.randomUUID().toString());
                                                                        secretKey1.setUserIndex(userIndex);
                                                                        secretKey1.setSecretKey(secretkey);
                                                                        secretKey1.setStandBy(strsm4);
                                                                        //用户角色组的绑定（默认为非正式组）
                                                                        RoleGroup roleGroup = new RoleGroup();
                                                                        roleGroup.setRoleGpName(RoleGroupEnum.CASUAL.getEname());
                                                                        roleGroup = rolegroupMapper.selectOne(roleGroup);
                                                                        int isno = 0;

                                                                        if (isnotice.equals("1")) {
                                                                            isno = 1;
                                                                        } else {
                                                                            isno = 0;
                                                                        }
                                                                        //保存用户配置信息
                                                                        UserSet userSet = new UserSet();
                                                                        userSet.setUserSetIndex(UUID.randomUUID().toString());//用户配置表Guid
                                                                        userSet.setUserIndex(userIndex);//user关系Guid
                                                                        userSet.setIsNotice(isno);
                                                                        userSet.setRoleGpIndex(roleGroup.getRoleGpIndex());
                                                                        userSet.setDeptsIndex(deptsIndex);


                                                                        try {
                                                                            um.insert(temp);
                                                                            secretKeyMapper.insert(secretKey1);
                                                                            usm.insert(userSet);
                                                                            TerminalLogs terminalLogs = new TerminalLogs();
                                                                            terminalLogs.setLogsIndex(UUID.randomUUID().toString());
                                                                            terminalLogs.setObjIndex(userIndex);
                                                                            terminalLogs.setTerminalType(TerminalLogsEnum.webUser.getTerminalIndex());
                                                                            terminalLogs.setUserIndex(TokenManager.getUserId());
                                                                            terminalLogs.setTerminalDescribe(TokenManager.getNickname()+"新增了"+name+"用户");
                                                                            terminalLogs.setUpdateTime(new Date());
                                                                            terminalLogsMapper.insert(terminalLogs);
                                                                            return "新增用户成功！";
                                                                        } catch (Exception e) {
                                                                            return "新增用户失败，请稍后再试。";
                                                                        }
                                                                    } else {
                                                                        return "登录名已存在";
                                                                    }
                                                                } else {
                                                                    return "名称已存在";
                                                                }
                                                            } else {
                                                                return "结束ip地址格式不正确";
                                                            }
                                                        } else {
                                                            return "起始ip地址格式不正确";
                                                        }
                                                    } else {
                                                        return "手机号格式不正确，必须有11位，并且为数字，是正常的手机号码开头";
                                                    }
                                                } else {
                                                    return "邮箱格式不正确，应含有@ .在@后，以.com、.con结尾（qq,163等）";
                                                }
                                            } else {
                                                return "密码格式不正确,需要包含特殊字符字母数字，长度为8-16";
                                            }
                                        } else {
                                            return "登录名只能由3-16的字母和数字组成";
                                        }
                                    } else {
                                        return "名称只由中文组成，长度为1-20";
                                    }
                                } else {
                                    return "结束ip不可为空";
                                }
                            } else {
                                return "起始ip不可为空";
                            }
                        } else {
                            return "邮箱不可为空";
                        }
                    } else {
                        return "手机号不可为空";
                    }
                } else {
                    return "密码不可为空";
                }
            } else {
                return "登录名不可为空";
            }
        } else {
            return "名称不可为空";
        }
    }

    /**
     * 新增用户
     */
    @Override
    public String 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 referralCode, String semName, String semPhone) throws Exception {
        //正则表达
        if (!StringUtils.isBlank(name)) {
            if (!StringUtils.isBlank(loginName)) {
                if (!StringUtils.isBlank(password)) {
                    if (!StringUtils.isBlank(email)) {
                        if (!StringUtils.isBlank(phone)) {
                            if (!StringUtils.isBlank(ip)) {
                                if (!StringUtils.isBlank(ipEnd)) {
                                    //进行用户的所有正则
                                    if (PubUtils.patternName(name)) {
                                        if (PubUtils.patternUsername(loginName)) {
                                            if (PubUtils.patternPassword(password)) {
                                                if (PubUtils.patternEmail(email)) {
                                                    if (PubUtils.patternPhone(phone)) {
                                                        if (PubUtils.patternIp(ip)) {
                                                            if (PubUtils.patternIp(ipEnd)) {
                                                                List<User> users = new ArrayList<>();
                                                                users = um.getPhone(phone, 0);
                                                                //名称不能重复
                                                                if (users.size() > 0) {
                                                                    return "该手机号已被注册";
                                                                }
                                                                User user = new User();
                                                                user.setName(name);
                                                                user = um.selectOne(user);

                                                                List<AppUser> appUserList = new ArrayList<>();
                                                                appUserList = appUserMapper.getAppPhone(phone, 0);
                                                                //名称不能重复
                                                                if (appUserList.size() > 0) {
                                                                    return "该手机号已被注册";
                                                                }

                                                                AppUser appUser = new AppUser();

                                                                appUser.setName(name);
                                                                appUser = appUserMapper.selectOne(appUser);

                                                                if (null == user && null == appUser) {
                                                                    //登录名不能重复
                                                                    user = new User();
                                                                    user.setLoginName(loginName);
                                                                    user = um.selectOne(user);

                                                                    appUser = new AppUser();
                                                                    appUser.setLoginName(loginName);
                                                                    appUser = appUserMapper.selectOne(appUser);
                                                                    if (null == user && null == appUser) {
                                                                        //保存用户基本信息
                                                                        User temp = new User();
                                                                        String userIndex = UUID.randomUUID().toString();
                                                                        temp.setUserIndex(userIndex);
                                                                        temp.setName(name);
                                                                        temp.setLoginName(loginName);

                                                                        if (usertype.equals("1")) {
                                                                            temp.setCasualUser(1); //临时用户
                                                                        } else {
                                                                            temp.setCasualUser(0);
                                                                        }

                                                                        String secretkey = "";//随机产生工作秘钥
                                                                        String strsm4 = "";//SM4加密密码
                                                                        String strpwd = "";//SM4加密(密码+工作秘钥）
                                                                        try {
                                                                            secretkey = PubUtils.GetSecretKey();//随机产生工作秘钥
                                                                            SM4Utils sm4 = new SM4Utils(secretkey);
                                                                            strsm4 = sm4.encryptData_ECB(password);//SM4加密密码
                                                                            strpwd = sm4.encryptData_ECB(strsm4 + secretkey);//SM4加密(密码+工作秘钥）
                                                                        } catch (Exception ex) {
                                                                            return "用户密码国密加密失败";
                                                                        }

                                                                        temp.setPassword(strpwd);
                                                                        temp.setPhone(phone);
                                                                        temp.setEmail(email);
                                                                        temp.setRegisterTime(new Date());
                                                                        temp.setPsdvalidity(new Date());
                                                                        temp.setLoginTime(new Date());
                                                                        temp.setMark(mark);
                                                                        temp.setLimitIpStart(ip);
                                                                        temp.setLimitIpEnd(ipEnd);
                                                                        temp.setLimitTime(time);
                                                                        temp.setLoginErrorTimes(0);
                                                                        temp.setReferralCode(referralCode);
                                                                        //新插入的用户，用户状态为3 待审核
                                                                        temp.setState(3);
                                                                        //保存用户密码加密信息
                                                                        SecretKey secretKey1 = new SecretKey();
                                                                        secretKey1.setSecretKeyIndex(UUID.randomUUID().toString());
                                                                        secretKey1.setUserIndex(userIndex);
                                                                        secretKey1.setSecretKey(secretkey);
                                                                        secretKey1.setStandBy(strsm4);
                                                                        //用户角色组的绑定（默认为非正式组）
                                                                        RoleGroup roleGroup = new RoleGroup();
                                                                        roleGroup.setRoleGpName(RoleGroupEnum.CASUAL.getEname());
                                                                        roleGroup = rolegroupMapper.selectOne(roleGroup);
                                                                        int isno = 0;
                                                                        if (isnotice.equals("1")) {
                                                                            isno = 1;
                                                                        } else {
                                                                            isno = 0;
                                                                        }
                                                                        //保存用户配置信息
                                                                        UserSet userSet = new UserSet();
                                                                        userSet.setUserSetIndex(UUID.randomUUID().toString());//用户配置表Guid
                                                                        userSet.setUserIndex(userIndex);//user关系Guid
                                                                        userSet.setIsNotice(isno);
                                                                        userSet.setRoleGpIndex(roleGroup.getRoleGpIndex());
                                                                        userSet.setDeptsIndex(deptsIndex);

                                                                        AppUser appUsers = new AppUser();
                                                                        appUsers.setUserIndex(userIndex);
                                                                        appUsers.setName(name);
                                                                        appUsers.setLoginName(loginName);
                                                                        String pwd = AESUtil.aesPKCS5PaddingEncrypt(password);
                                                                        appUsers.setPassword(pwd);
                                                                        appUsers.setPhone(phone);
                                                                        appUsers.setEmail(email);
                                                                        appUsers.setRegisterTime(new Date());
                                                                        appUsers.setPsdValidity(new Date());
                                                                        appUsers.setLoginTime(new Date());
                                                                        appUsers.setState(1);
                                                                        appUsers.setLoginErrorTimes(0);
                                                                        appUsers.setUserLevel(UserLevelEnum.HOST_USER.getCode());
                                                                        appUsers.setSemName(semName);
                                                                        appUsers.setSemPhone(semPhone);
                                                                        appUsers.setReferralCode(referralCode);
                                                                        appUsers.setUserType("0");

                                                                        AppInfoSet appInfoSet = new AppInfoSet();
                                                                        appInfoSet.setUserIndex(userIndex);
                                                                        appInfoSet.setDeviceInfo(1);
                                                                        appInfoSet.setEventInfo(1);
                                                                        appInfoSet.setSystemInfo(1);
                                                                        appInfoSet.setTargetInfo(1);

                                                                        try {
                                                                            um.insert(temp);
                                                                            appUserMapper.insert(appUsers);//新增app用户
                                                                            appInfoSetMapper.insert(appInfoSet);
                                                                            secretKeyMapper.insert(secretKey1);
                                                                            usm.insert(userSet);
                                                                            TerminalLogs terminalLogs = new TerminalLogs();
                                                                            terminalLogs.setLogsIndex(UUID.randomUUID().toString());
                                                                            terminalLogs.setObjIndex(userIndex);
                                                                            terminalLogs.setTerminalType(TerminalLogsEnum.appUser.getTerminalIndex());
                                                                            terminalLogs.setUserIndex(TokenManager.getUserId());
                                                                            terminalLogs.setTerminalDescribe(TokenManager.getNickname()+"为营销人员："+semName+"新增了"+name+"用户");
                                                                            terminalLogs.setUpdateTime(new Date());
                                                                            terminalLogsMapper.insert(terminalLogs);
                                                                            return "新增用户成功！";
                                                                        } catch (Exception e) {
                                                                            return "新增用户失败，请稍后再试。";
                                                                        }
                                                                    } else {
                                                                        return "登录名已存在";
                                                                    }
                                                                } else {
                                                                    return "名称已存在";
                                                                }
                                                            } else {
                                                                return "结束ip地址格式不正确";
                                                            }
                                                        } else {
                                                            return "起始ip地址格式不正确";
                                                        }
                                                    } else {
                                                        return "手机号格式不正确，必须有11位，并且为数字，是正常的手机号码开头";
                                                    }
                                                } else {
                                                    return "邮箱格式不正确，应含有@ .在@后，以.com、.con结尾（qq,163等）";
                                                }
                                            } else {
                                                return "密码格式不正确,需要包含特殊字符字母数字，长度为8-16";
                                            }
                                        } else {
                                            return "登录名由3-16的字母和数字及下划线组成";
                                        }
                                    } else {
                                        return "名称只由中文组成，长度为1-20";
                                    }
                                } else {
                                    return "结束ip不可为空";
                                }
                            } else {
                                return "起始ip不可为空";
                            }
                        } else {
                            return "邮箱不可为空";
                        }
                    } else {
                        return "手机号不可为空";
                    }
                } else {
                    return "密码不可为空";
                }
            } else {
                return "登录名不可为空";
            }
        } else {
            return "名称不可为空";
        }
    }


    /**
     * 新增管理员
     */
    @Override
    public String saveManager(String name, String loginName, String rolegpIndex, String password, String phone, String email, String ip, String ipEnd, String time, Integer mark) {
        //正则表达
        if (!StringUtils.isBlank(name)) {
            if (!StringUtils.isBlank(loginName)) {
                if (!StringUtils.isBlank(password)) {
                    if (!StringUtils.isBlank(email)) {
                        if (!StringUtils.isBlank(phone)) {
                            if (!StringUtils.isBlank(ip)) {
                                if (!StringUtils.isBlank(ipEnd)) {
                                    //进行用户的所有正则
                                    if (PubUtils.patternName(name)) {
                                        if (PubUtils.patternUsername(loginName)) {
                                            if (PubUtils.patternPassword(password)) {
                                                if (PubUtils.patternEmail(email)) {
                                                    if (PubUtils.patternPhone(phone)) {
                                                        if (PubUtils.patternIp(ip)) {
                                                            if (PubUtils.patternIp(ipEnd)) {
                                                                List<User> users = new ArrayList<>();
                                                                users = um.getPhone(phone, 0);
                                                                //名称不能重复
                                                                if (users.size() > 0) {
                                                                    return "该手机号已被注册";
                                                                }
                                                                User user = new User();
                                                                user.setName(name);
                                                                user = um.selectOne(user);
                                                                if (null == user) {
                                                                    //登录名不能重复
                                                                    user = new User();
                                                                    user.setLoginName(loginName);
                                                                    user = um.selectOne(user);
                                                                    if (null == user) {
                                                                        //保存用户基本信息
                                                                        User temp = new User();
                                                                        String userIndex = UUID.randomUUID().toString();
                                                                        temp.setUserIndex(userIndex);
                                                                        temp.setName(name);
                                                                        temp.setLoginName(loginName);
                                                                        temp.setCasualUser(0);
                                                                        String secretkey = "";//随机产生工作秘钥
                                                                        String strsm4 = "";//SM4加密密码
                                                                        String strpwd = "";//SM4加密(密码+工作秘钥）
                                                                        try {
                                                                            secretkey = PubUtils.GetSecretKey();//随机产生工作秘钥
                                                                            SM4Utils sm4 = new SM4Utils(secretkey);
                                                                            strsm4 = sm4.encryptData_ECB(password);//SM4加密密码
                                                                            strpwd = sm4.encryptData_ECB(strsm4 + secretkey);//SM4加密(密码+工作秘钥）
                                                                        } catch (Exception ex) {
                                                                            return "用户密码国密加密失败";
                                                                        }
                                                                        temp.setPassword(strpwd);
                                                                        temp.setPhone(phone);
                                                                        temp.setEmail(email);
                                                                        temp.setRegisterTime(new Date());
                                                                        temp.setPsdvalidity(new Date());
                                                                        temp.setLoginTime(new Date());
                                                                        temp.setMark(mark);
                                                                        temp.setLimitIpStart(ip);
                                                                        temp.setLimitIpEnd(ipEnd);
                                                                        temp.setLimitTime(time);
                                                                        temp.setLoginErrorTimes(0);
                                                                        //新插入的用户，用户状态为3 待审核
                                                                        temp.setState(1);
                                                                        //保存用户密码加密信息
                                                                        SecretKey secretKey1 = new SecretKey();
                                                                        secretKey1.setSecretKeyIndex(UUID.randomUUID().toString());
                                                                        secretKey1.setUserIndex(userIndex);
                                                                        secretKey1.setSecretKey(secretkey);
                                                                        secretKey1.setStandBy(strsm4);
                                                                        //用户角色组的绑定（默认为非正式组）
                                                                        RoleGroup roleGroup = new RoleGroup();
                                                                        roleGroup.setRoleGpName(RoleGroupEnum.CASUAL.getEname());
                                                                        roleGroup = rolegroupMapper.selectOne(roleGroup);
                                                                        //保存用户配置信息
                                                                        UserSet userSet = new UserSet();
                                                                        userSet.setUserSetIndex(UUID.randomUUID().toString());//用户配置表Guid
                                                                        userSet.setUserIndex(userIndex);//user关系Guid
                                                                        userSet.setIsNotice(0);
                                                                        userSet.setRoleGpIndex(rolegpIndex);
                                                                        Example example = new Example(Depts.class);
                                                                        example.createCriteria().andEqualTo("parentNodeId", "0");
                                                                        List<Depts> depts = deptsMapper.selectByExample(example);
                                                                        if (CollectionUtils.isEmpty(depts)) {
                                                                            depts = deptsMapper.selectDeptAll();
                                                                            userSet.setDeptsIndex(depts.get(0).getDeptsIndex());
                                                                        } else {
                                                                            userSet.setDeptsIndex(depts.get(0).getDeptsIndex());
                                                                        }
                                                                        try {
                                                                            int flag = um.insert(temp);
                                                                            int flag1 = secretKeyMapper.insert(secretKey1);
                                                                            int flag2 = usm.insert(userSet);
                                                                            return "新增管理员成功！";
                                                                        } catch (Exception e) {
                                                                            return "新增用户失败，请稍后再试。";
                                                                        }
                                                                    } else {
                                                                        return "登录名已存在";
                                                                    }
                                                                } else {
                                                                    return "名称已存在";
                                                                }
                                                            } else {
                                                                return "结束ip地址格式不正确";
                                                            }
                                                        } else {
                                                            return "起始ip地址格式不正确";
                                                        }
                                                    } else {
                                                        return "手机号格式不正确，必须有11位，并且为数字，是正常的手机号码开头";
                                                    }
                                                } else {
                                                    return "邮箱格式不正确，应含有@ .在@后，以.com、.con结尾（qq,163等）";
                                                }
                                            } else {
                                                return "密码格式不正确,需要包含特殊字符字母数字，长度为8-16";
                                            }
                                        } else {
                                            return "登录名只能由3-16的字母和数字组成";
                                        }
                                    } else {
                                        return "名称只由中文组成，长度为1-20";
                                    }
                                } else {
                                    return "结束ip不可为空";
                                }
                            } else {
                                return "起始ip不可为空";
                            }
                        } else {
                            return "邮箱不可为空";
                        }
                    } else {
                        return "手机号不可为空";
                    }
                } else {
                    return "密码不可为空";
                }
            } else {
                return "登录名不可为空";
            }
        } else {
            return "名称不可为空";
        }
    }

    //密码确认


    @Override
    public String deleteUserByIndex(String index) {
        // TODO Auto-generated method stub
        //判断该用户是否存在
        User user1 = new User();
        user1.setUserIndex(index);
        user1 = um.selectOne(user1);
        if (null == user1) {
            return "该用户不存在，已注销！";
        } else {
            try {
                int state = 0;
                um.deleteUserByIndex(index, state);
                return "注销用户成功！";
            } catch (Exception e) {
                return "注销用户失败，请稍后再试";
            }
        }
    }

    @Override
    public String deleteAppUserByIndex(String index) {
        // TODO Auto-generated method stub
        //判断该用户是否存在
        User user1 = new User();
        user1.setUserIndex(index);
        user1 = um.selectOne(user1);
        if (null == user1) {
            return "该用户不存在，已注销！";
        } else {
            try {
                appUserMapper.deleteAppUserByIndex(index);
                um.deleteUserByIndex(index, 0);
                appUserMapper.deleteAppUserIndex(index);
                return "注销用户成功！";
            } catch (Exception e) {
                return "注销用户失败，请稍后再试";
            }
        }
    }

    @Override
    public int updateExaminer(String userIndex) {
        // TODO Auto-generated method stub
        try {
            RoleGroup roleGroup = new RoleGroup();
            roleGroup.setRoleGpName(RoleGroupEnum.NORMAL.getEname());
            roleGroup = rolegroupMapper.selectOne(roleGroup);

            UserSet userSet = new UserSet();
            userSet.setUserIndex(userIndex);
            UserSet userSet1 = new UserSet();
            userSet1 = userSetMapper.selectOne(userSet);
            userSet1.setUserSetIndex(userSet1.getUserSetIndex());
            userSet1.setRoleGpIndex(roleGroup.getRoleGpIndex());

            userSetMapper.updateByPrimaryKey(userSet1);
            um.updateExaminer(userIndex);
            String key = DataRealm.ROLE_NAME_KEY + userIndex + TokenManager.getSysType();
            redisCacheUtil.clearRolesData(key);
            return 1;
        } catch (Exception e) {
            // TODO: handle exception
            logger.error(e.getMessage());
            return 2;
        }
    }


    /**
     * 将用户从睡眠状态激活为正常状态
     *
     * @param userIndex 用户索引
     */
    @Override
    public void dealUserActive(String userIndex) {
        User user = new User();
        user.setUserIndex(userIndex);
        user = um.selectOne(user);
        if (null != user) {
            user.setPsdvalidity(new Date());
            user.setLoginTime(user.getPsdvalidity());
            user.setRegisterTime(user.getPsdvalidity());
            user.setState(1);
            user.setLoginErrorTimes(0);
            um.updateByPrimaryKeyBySql(user);
        }
    }


    /**
     * 将用户从锁定状态激活为正常状态
     *
     * @param userIndex 用户索引
     */
    @Override
    public void dealUserUnlock(String userIndex) {
        um.dealUserActive(userIndex);
    }

    /**
     * 根据用户获取区域信息
     * 1，获取当前用户的部门，
     * 2，迭代该部门的所有子部门
     */
    @Override
    public List<AreaInfo> getAreasByUser() {
        List<AreaInfo> areaInfos = new ArrayList<>();
        //根据用户获取其可看的区域或自定义小组
        Depts dept = userUtil.getCurrentDept();
        AreaInfo root = new AreaInfo();
        root.setId(dept.getDeptsIndex());
        root.setName(dept.getArea());
        root.setpId(dept.getParentNodeId());
        root.setOpen("true");
        areaInfos.add(root);
        List<Depts> depts = userUtil.getDeptsByNode(dept.getDeptsIndex());
        if (!CollectionUtils.isEmpty(depts)) {
            for (Depts temp : depts) {
                AreaInfo areaTemp = new AreaInfo();
                areaTemp.setId(temp.getDeptsIndex());
                if (temp.getCustomDept() == 1) {
                    areaTemp.setName(temp.getDeptsName());
                } else {
                    areaTemp.setName(temp.getArea());
                }
                areaTemp.setpId(temp.getParentNodeId());
                areaTemp.setOpen("false");
                areaInfos.add(areaTemp);
            }
        }
        return areaInfos;
    }


    /**
     * 判断用户名密码是否匹配
     */
    @Override
    public void judgeUsernameAndPwd(String username, String password) {
        User user = new User();
        user.setLoginName(username);
        user = um.selectOne(user);
        if (null == user) {
            throw new UnknownAccountException("用户不存在");
        } else {
            //该用户的加密内容
            SecretKey secretk = new SecretKey();
            secretk.setUserIndex(user.getUserIndex());
            secretk = secretKeyMapper.selectOne(secretk);
            if (null == secretk) {
                throw new AccountException("用户密码被破坏");
            } else {
                //针对所有用户的登录限制
                String standBy = secretk.getStandBy();
                String secretkey = secretk.getSecretKey();
                // 开始校验用户的密码是否正确
                String mPwd;//国密4加密的密码
                String strpwd;//国密4加密的（密码+工作秘钥）
                try {
                    SM4Utils sm4 = new SM4Utils(secretkey);
                    mPwd = sm4.encryptData_ECB(password);//SM4加密密码
                    strpwd = sm4.encryptData_ECB(mPwd + secretkey);//SM4加密(密码+工作秘钥）
                } catch (Exception ex) {
                    throw new AccountException("用户密码国密加密失败");
                }
                // 两次MD加密是否一致，一致后继续验证
                if (standBy.equalsIgnoreCase(mPwd)) {
                    if (!user.getPassword().equalsIgnoreCase(strpwd)) {
                        throw new AccountException("用户名密码不匹配");
                    }
                } else {
                    throw new AccountException("用户名密码不匹配");
                }
            }
        }

    }

    /**
     * 根据登录名，将用户锁定
     *
     * @param username 登录名
     */
    @Override
    public void updateUserLocked(String username) {
        User user = new User();
        user.setLoginName(username);
        user = um.selectOne(user);
        if (null != user) {
            user.setLockTime(new Date());//add by sw新增用户锁定记录锁定时间
            user.setState(UserStatusEnum.LOCKED.getCode());
            user.setLoginErrorTimes(user.getLoginErrorTimes() + 1);
            um.updateByPrimaryKeyBySql(user);
        }
    }

    /**
     * 根据登录名，累加用户密码错误次数
     *
     * @param username 用户登录名
     */
    @Override
    public void updateUserPasswordError(String username) {
        User user = new User();
        user.setLoginName(username);
        user = um.selectOne(user);
        if (null != user) {
            if (user.getLoginErrorTimes() == 0) { //add by sw新增第一次密码输入错误记录时间
                user.setFirstErrorTime(new Date());
            }
            user.setLoginErrorTimes(user.getLoginErrorTimes() + 1);
            um.updateByPrimaryKeyBySql(user);
        }
    }


    /**
     * 查询用户
     *
     * @param name      昵称
     * @param userIndex 用户索引
     */
    @Override
    public List<User> selectName(String name, String userIndex) {
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("name", name).andNotEqualTo("userIndex", userIndex);
        return um.selectByExample(example);
    }


    @Override
    public String selectIdName(String userIndex) {
        // TODO Auto-generated method stub
        return um.selectIdName(userIndex);
    }
}
