package com.muchinfo.mtp3century.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.muchinfo.mtp3century.service.IArearoleService;
import com.muchinfo.mtp3century.service.ICommonService;
import com.muchinfo.mtp3century.service.ISystemmanagerService;
import com.muchinfo.mtp3century.utils.RedisServiceUtil;
import com.muchinfo.mtp3century.vo.LoginCodeVo;
import com.muchinfo.mtp3century.vo.systemlogin.LoginReq;
import com.muchinfo.mtp3century.vo.systemlogin.LoginRsp;
import com.muchinfo.mtp3common.enumtype.*;
import com.muchinfo.mtp3common.utils.*;
import com.muchinfo.mtp3century.utils.AjaxResult;
import com.muchinfo.mtp3common.vo.PageResult;
import com.muchinfo.mtp3interface.mapper.*;
import com.muchinfo.mtp3pojos.entity.*;
import com.muchinfo.mtp3pojos.vo.systemuser.SystemUserPwdParam;
import com.muchinfo.mtp3pojos.vo.systemuser.SystemUserReqParam;
import com.muchinfo.mtp3pojos.vo.systemuser.SystemUserResResult;
import com.muchinfo.mtp3pojos.vo.systemuser.SystemUserVo;
import com.wf.captcha.ArithmeticCaptcha;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class SystemmanagerServiceImpl extends ServiceImpl<ISystemmanagerMapper, Systemmanager> implements ISystemmanagerService {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private RedisServiceUtil redisServiceUtil;
    @Resource
    private IIpbacklistMapper iIpbacklistMapper;
    @Resource
    private ISystemmanagerroleMapper iSystemmanagerroleMapper;
    @Resource
    private ITaaccountMapper iTaaccountMapper;
    @Resource
    private IArearoleService iArearoleService;
    @Resource
    private ISystemmanagerMapper iSystemmanagerMapper;
    @Resource
    private ICommonService iCommonService;
    @Resource
    private IUseraccountMapper iUseraccountMapper;
    @Resource
    private IRoleuserMapper iRoleuserMapper;
    @Resource
    private IFuncmenulistMapper iFuncmenulistMapper;
    @Resource
    private ISystemmanagerlogMapper iSystemmanagerlogMapper;

    /**
     * @return message 验证码
     */
    @Override
    public AjaxResult getVerifyCode(HttpServletRequest request) {
        // 算术类型
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
        // 几位数运算，默认是两位
        captcha.setLen(2);
        // 获取运算的结果
        String result = "";
        try {
            result = new Double(Double.parseDouble(captcha.text())).intValue() + "";
        } catch (Exception e) {
            result = captcha.text();
        }
        //生成uuid做为验证码的key
        UUID key = UUID.randomUUID();
        //存储验证码信息到redis中，60秒过期
        redisServiceUtil.setCacheObject(RedisConstants.LOGIN_CODE + key, result, RedisConstants.LOGIN_CODE_TIME, TimeUnit.SECONDS);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM006.getCode(), request.getHeader("Accept-Language"), new LoginCodeVo(captcha.toBase64(), key.toString()));
    }

    @Override
    public AjaxResult loginIn(LoginReq loginReq, HttpServletRequest request, Systemmanager systemmanager) {
        LoginRsp rsp = new LoginRsp();
        if (systemmanager.getManagertype() != 1) {
            rsp.setCode(Constants.loginTradeManage);
            rsp.setMessage(Constants.loginTradeManage_msg);
            return AjaxResult.error(Constants.loginTradeManage, MessageType.LOGIN_ERROR_CODE_001.getCode(), request.getHeader("Accept-Language"), rsp);
        }
        //校验验证码
        /*if (!verifyCode(loginReq.getKey(), loginReq.getVerifyCode())) {
            return AjaxResult.error(Constants.Error_Code_Design, Constants.vcodeError_msg);
        }*/
        loginReq.setLoginIp(CommonUtil.getIpAddress(request));
        //ip黑名单
        Ipbacklist ip = iIpbacklistMapper.selectOne(new QueryWrapper<Ipbacklist>()
                .eq("IP", loginReq.getLoginIp())
                .eq("IPTYPE", "1"));
        if (ip != null) {
            log.debug("code:{},ip:{}", loginReq.getAccountCode(), loginReq.getLoginIp());
            rsp.setCode(Constants.loginCountError);
            rsp.setMessage(Constants.loginCountError_msg);
            return AjaxResult.error(Constants.loginCountError, MessageType.LOGIN_ERROR_CODE_002.getCode(), request.getHeader("Accept-Language"), rsp);
        }
        // 如果用户被锁定，判断锁定时长 超过时常可以登陆
        if (SysEnums.SysStatus.lock.getCode().equals(systemmanager.getManagerstatus())) {
            Object redisParam = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM,
                    SysConstants.SYSPARAM_CODE_LOCKTIME);
            double defaultMin;
            if (redisParam == null) {
                defaultMin = (double) 180;
            } else {
                defaultMin = Double.parseDouble(String.valueOf(redisParam));
            }
            //没有超过锁定时常，不能登陆
            if (DateTimeUtils.getDoubleMin(new Date(), systemmanager.getLogintime()) < defaultMin) {
                rsp.setCode(Constants.userlock);
                rsp.setMessage(Constants.loginlock_msg);
                return AjaxResult.error(Constants.userlock, MessageType.LOGIN_ERROR_CODE_003.getCode(), request.getHeader("Accept-Language"), rsp);
            } else {
                //超过时间更新失败次数
                systemmanager.setManagerstatus(SysEnums.SysStatus.ok.getCode());
                systemmanager.setLoginfailnum(0);
                iSystemmanagerMapper.update(systemmanager, new QueryWrapper<Systemmanager>().eq("AUTOID", systemmanager.getAutoid()));
            }
        } else if (!SysEnums.SysStatus.ok.getCode().equals(systemmanager.getManagerstatus())) {
            log.debug("manager status={}", systemmanager.getManagerstatus());
            rsp.setCode(Constants.unOk);
            rsp.setMessage(Constants.loginStop_msg);
            return AjaxResult.error(Constants.unOk, MessageType.LOGIN_ERROR_CODE_004.getCode(), request.getHeader("Accept-Language"), rsp);
        }

        Object o = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "975");
        if (o == null)
            rsp.setForcechangepass("1");
        else
            rsp.setForcechangepass(o.toString());
        if (systemmanager.getPwdexpdate().before(new Date())) {
            rsp.setCode(Constants.loginChange);
        }
        //角色敏感词权限
        List<Systemmanagerrole> systemmanagerroles = iSystemmanagerroleMapper.getRoleLsitByUserid(systemmanager.getAutoid());
        Set<String> set = getStrings(systemmanagerroles);
        rsp.setSensitive(set);
        //如果是会员管理员那么把会员角色查出
        rsp.setOrgztypes(iArearoleService.getRolesByAreaid(systemmanager.getAreauserid()));
        //根据userid，查询正常状态的资金账户数量
        if (SysConstantsEnum.SYS_TYPE_CLIENT.getCode() == systemmanager.getReletype()) {
            //用于判断经纪会员登录能否开户
            Integer size = Math.toIntExact(iTaaccountMapper.selectCount(new QueryWrapper<Taaccount>()
                    .eq("USERID", systemmanager.getAreauserid())
                    .eq("ISMAIN", 1)
                    .eq("TAACCOUNTTYPE", 2)
                    .eq("TRADESTATUS", 1)
            ));
            rsp.setActive(size == null ? 0 : size);
        }
        rsp.setReleType(systemmanager.getReletype());
        rsp.setLogincode(systemmanager.getLogincode());
        rsp.setUsername(systemmanager.getUsername());
        rsp.setAreauserid(systemmanager.getAreauserid());
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM007.getCode(), request.getHeader("Accept-Language"), rsp);
    }

    private Set<String> getStrings(List<Systemmanagerrole> systemmanagerroles) {
        Set<String> set = new HashSet<>();
        for (Systemmanagerrole r : systemmanagerroles) {
            if (r == null) {
                continue;
            }
            String sen = r.getSensitivefields();
            if (StringUtils.isEmpty(sen)) {
                continue;
            }
            String[] sen_ = sen.split(",");
            for (int i = 0; i < sen_.length; i++) {
                if (StringUtils.isEmpty(sen_[i])) {
                    continue;
                }
                set.add(sen_[i]);
            }
        }
        return set;
    }

    @Override
    public PageResult<SystemUserResResult> queryUserMsg(HttpServletRequest request, SystemUserReqParam systemUserReqParam) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemUserReqParam.getAreaIds() == null) {
            log.debug("areauserid={}", systemmanager.getAreauserid());
            //如果是平台管理员，那么areauserid=0
            systemUserReqParam.setAreaIds(systemmanager.getAreauserid() + "");
        }
        if (systemUserReqParam.getLoginCode() != null) {
            systemUserReqParam.setLoginCode(systemUserReqParam.getLoginCode().trim());
        }
        IPage<SystemUserResResult> page = new Page<>(systemUserReqParam.getPageNum(), systemUserReqParam.getPageSize());
        IPage<SystemUserResResult> systemUserResResultIPage = iSystemmanagerMapper.selectByPageVo(page, systemUserReqParam);
        return getSystemUserResResultPageResult(systemUserResResultIPage, request);
    }

    private PageResult<SystemUserResResult> getSystemUserResResultPageResult(IPage<SystemUserResResult> systemUserVoPage, HttpServletRequest request) {
        PageResult<SystemUserResResult> pageResult = new PageResult<>();
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(systemUserVoPage.getPages());
        pageResult.setCurrent(systemUserVoPage.getCurrent());
        pageResult.setTotal(systemUserVoPage.getTotal());
        pageResult.setPageSize(systemUserVoPage.getSize());
        pageResult.setData(systemUserVoPage.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult<SystemUserResResult> queryDetail(Integer autoId, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        StringBuilder stringBuilder = new StringBuilder();
        StringBuilder idStr = new StringBuilder();
        //基本信息
        Systemmanager user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("AUTOID", autoId));
        //是否有查询权限
        if (user.getReletype() != 1) {
            if (!iCommonService.checkIsAreaSon2(systemmanager.getAreauserid(), user.getAreauserid())) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_004.getCode(), request.getHeader("Accept-Language"));
            }
        }
        SystemUserResResult userResResult = new SystemUserResResult();
        BeanUtils.copyProperties(user, userResResult);
        Systemmanager updateUser = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("AUTOID", user.getUploginid()));
        if (Objects.nonNull(updateUser)) {
            userResResult.setUpLoginName(updateUser.getUsername());
        }
        //角色信息
        List<Systemmanagerrole> role = iSystemmanagerroleMapper.getRoleLsitByUserid(user.getAutoid());
        for (int i = 0; i < role.size(); i++) {
            if (role.get(i) == null) {
                continue;
            }
            if (i == role.size() - 1) {
                stringBuilder.append(role.get(i).getRolename());
                idStr.append(role.get(i).getAutoid());
            } else {
                stringBuilder.append(role.get(i).getRolename()).append(",");
                idStr.append(role.get(i).getAutoid()).append(",");
                ;
            }
        }
        userResResult.setRoleName(stringBuilder.toString());
        userResResult.setRoleId(idStr.toString());
        //密码不返回
        userResResult.setPassword("");
        if (user.getAreauserid() != 0) {
            userResResult.setAreaName(iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("USERID", user.getAreauserid())).getAccountname());
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), userResResult);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult dealUserMsg(SystemUserVo systemUserVo, HttpServletRequest request) {
        AjaxResult ajaxResult;
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        Systemmanager addUser = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", systemUserVo.getLogincode()));
        //判断当前管理员信息是否存在，存在则更改
        if (StringUtils.isEmpty(systemUserVo.getAutoid())) {
            if (Objects.nonNull(addUser)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.LOGIN_ERROR_CODE_005.getCode(), request.getHeader("Accept-Language"));
            }
            String lPwd = iCommonService.getSystemParam(Constants.REDIS_HEADER_SYSPARAM, SysConstants.SYSPARAM_CODE_DEFAULT_PWD);
            Systemmanager user = new Systemmanager();
            BeanUtils.copyProperties(systemUserVo, user);
            //设置所属机构
            user.setAreauserid(systemmanager.getAreauserid());
            user.setPwdexpdate(new Date());
            user.setSystemtype(2);
            user.setLoginstatus(SysEnums.LoginStatus.loginout.getCode());
            user.setReletype(systemmanager.getReletype());
            user.setLoginfailnum(0);
            user.setPassword(EncryptionUtils.encryptSHA(user.getLogincode() + lPwd));
            user.setManagerstatus(SysEnums.SysStatus.ok.getCode());
            user.setModifytime(new Date());
            user.setUploginid(systemmanager.getAutoid());
            user.setIsdefault(0);
            user.setManagertype(1);
            iSystemmanagerMapper.insert(user);
            //添加角色信息
            ajaxResult = dealRoleMsg(systemUserVo, user, request);
        } else {
            addUser.setLogincode(systemUserVo.getLogincode());
            addUser.setUsername(systemUserVo.getUsername());
            addUser.setRemark(systemUserVo.getRemark());
            addUser.setUploginid(systemmanager.getAutoid());
            addUser.setModifytime(new Date());
            iSystemmanagerMapper.update(addUser, new QueryWrapper<Systemmanager>().eq("AUTOID", addUser.getAutoid()));
            //删除当前角色信息
            iRoleuserMapper.delete(new QueryWrapper<Roleuser>().eq("MANAGERID", systemUserVo.getAutoid()));
            //添加角色信息
            ajaxResult = dealRoleMsg(systemUserVo, addUser, request);
        }
        return ajaxResult;
    }

    @Override
    public AjaxResult dealUserStatus(SystemUserVo systemUserVo, HttpServletRequest request) {
        //登录用户
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        Systemmanager currentUser = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("AUTOID", systemUserVo.getAutoid()));
        if (Objects.isNull(currentUser)) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.LOGIN_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
        }
        if (systemmanager.getReletype() != 1 && !iCommonService.checkIsAreaSon2(systemmanager.getAreauserid(), currentUser.getAreauserid())) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_004.getCode(), request.getHeader("Accept-Language"));
        }
        if (systemUserVo.getType() == 1 && systemmanager.getAutoid().intValue() == systemUserVo.getAutoid().intValue()) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.LOGIN_ERROR_CODE_007.getCode(), request.getHeader("Accept-Language"));
        }

        switch (systemUserVo.getType()) {
            case 0:
                resetPwd(currentUser, systemmanager);
                break;
            case 1:
                updateStatus(currentUser, SysEnums.SysStatus.stop.getCode());
                break;
            case 2:
                updateStatus(currentUser, SysEnums.SysStatus.ok.getCode());
                break;
            case 3:
                unlockUser(currentUser, SysEnums.SysStatus.ok.getCode());
                break;
            default:
                break;
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult<Systemmanager> queryRoleUser(Integer autoId, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        Systemmanagerrole systemmanagerrole = iSystemmanagerroleMapper.selectOne(new QueryWrapper<Systemmanagerrole>().eq("autoid", autoId));
        if (systemmanagerrole != null && systemmanager.getAreauserid().compareTo(systemmanagerrole.getAreauserid()) != 0) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_004.getCode(), request.getHeader("Accept-Language"));
        }
        List<Systemmanager> systemManagers = iSystemmanagerMapper.getSystemManagerByRole(autoId);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), systemManagers);
    }

    @Override
    public AjaxResult updatePwd(SystemUserPwdParam systemUserPwdParam, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemUserPwdParam.getOldPwd().equals(systemUserPwdParam.getNewPwd())) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.LOGIN_ERROR_CODE_008.getCode(), request.getHeader("Accept-Language"));
        }
        if (!systemmanager.getPassword().equals(systemUserPwdParam.getOldPwd())) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.LOGIN_ERROR_CODE_009.getCode(), request.getHeader("Accept-Language"));
        }
        String expday = iCommonService.getSystemParam(Constants.REDIS_HEADER_SYSPARAM, SysConstants.SYSPARAM_CODE_EXPDAY);
        systemmanager.setPassword(systemUserPwdParam.getNewPwd());
        systemmanager.setPwdexpdate(DateTimeUtils.addDay(new Date(), Integer.parseInt(expday.trim())));
        iSystemmanagerMapper.update(systemmanager, new QueryWrapper<Systemmanager>().eq("AUTOID", systemmanager.getAutoid()));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public void saveMGLog(Systemmanager sm, String partInvestorManage, Long userid) {
        Systemmanagerlog log = new Systemmanagerlog();
        log.setReletype(1);
        log.setUserid(sm.getAutoid());
        log.setLogincode(sm.getLogincode());
        log.setUsername(sm.getUsername());
        log.setContent("查看 [" + userid + "] 敏感信息");
        log.setIp(sm.getLoginip());
        log.setResourcecode(partInvestorManage);
        log.setParentuserid(sm.getAreauserid());
        Funcmenulist menu = iFuncmenulistMapper.selectOne(new QueryWrapper<Funcmenulist>().eq("RESOURCECODE", partInvestorManage));
        log.setResourcename(menu == null ? "" : menu.getResourcename());
        log.setOperatetime(new Date());
        iSystemmanagerlogMapper.insert(log);
    }

    private void unlockUser(Systemmanager currentUser, Integer status) {
        currentUser.setManagerstatus(status);
        currentUser.setModifytime(new Date());
        currentUser.setLoginfailnum(0);
        iSystemmanagerMapper.update(currentUser, new QueryWrapper<Systemmanager>().eq("AUTOID", currentUser.getAutoid()));
    }

    private void updateStatus(Systemmanager currentUser, Integer status) {
        currentUser.setManagerstatus(status);
        currentUser.setModifytime(new Date());
        iSystemmanagerMapper.update(currentUser, new QueryWrapper<Systemmanager>().eq("AUTOID", currentUser.getAutoid()));
    }

    private void resetPwd(Systemmanager currentUser, Systemmanager systemmanager) {
        String lPwd = iCommonService.getSystemParam(Constants.REDIS_HEADER_SYSPARAM, SysConstants.SYSPARAM_CODE_DEFAULT_PWD);

        currentUser.setPassword(EncryptionUtils.encryptSHA(currentUser.getLogincode() + lPwd));
        currentUser.setLoginfailnum(0);
        currentUser.setModifytime(new Date());
        //重置密码后首次登陆强制修改
        currentUser.setPwdexpdate(new Date());
        iSystemmanagerMapper.update(currentUser, new QueryWrapper<Systemmanager>().eq("AUTOID", currentUser.getAutoid()));
        //写入日志
        writeOperateLog(SysConstants.PART_CODE_ORGZ, "重置密码id=" + currentUser.getLogincode(), systemmanager, null, null, null);
    }

    public void writeOperateLog(String resourceCode, String content, Systemmanager currentUser, String remark, String oldvalue, String newvalue) {
        Systemmanagerlog syslog = new Systemmanagerlog();
        syslog.setUserid(currentUser.getAutoid());
        syslog.setReletype(currentUser.getReletype());
        syslog.setLogincode(currentUser.getLogincode());
        syslog.setUsername(currentUser.getUsername());
        syslog.setParentuserid(currentUser.getAreauserid());
        syslog.setOperatetime(new Date());
        syslog.setIp(currentUser.getLoginip());
        syslog.setResourcecode(resourceCode);
        Funcmenulist menu = iFuncmenulistMapper.selectOne(new QueryWrapper<Funcmenulist>().eq("RESOURCECODE", resourceCode));
        if (menu != null)
            syslog.setResourcename(menu.getResourcename());
        if (content != null)
            syslog.setContent(content);
        if (remark != null)
            syslog.setRemark(remark);
        if(oldvalue != null)
            if (isJsonObject(oldvalue)){
                syslog.setPrevalue(oldvalue);
            }else{
                syslog.setPrevalue("{\"content\":\"" + oldvalue + "\"}");
            }
        if(newvalue != null)
            if (isJsonObject(newvalue)){
                syslog.setNewvalue(newvalue);
            }else{
                syslog.setNewvalue("{\"content\":\"" + newvalue + "\"}");
            }
        iSystemmanagerlogMapper.insert(syslog);
    }

    private boolean isJsonObject(String str){
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            JsonNode jsonNode = objectMapper.readTree(str); // 解析字符串
            return jsonNode.isObject();  // 检查解析后的节点是否为 JSON 对象
        } catch (Exception e) {
            return false;  // 解析失败，说明不是 JSON
        }
    }

    private AjaxResult dealRoleMsg(SystemUserVo systemUserVo, Systemmanager addUser, HttpServletRequest request) {
        if (!StringUtils.isEmpty(systemUserVo.getRoleId())) {
            String r[] = systemUserVo.getRoleId().split(",");
            for (String s : r) {
                Systemmanagerrole roleBean = iSystemmanagerroleMapper.selectOne(new QueryWrapper<Systemmanagerrole>().eq("AUTOID", s));
                if (Objects.nonNull(roleBean)) {
                    Roleuser ur = new Roleuser();
                    ur.setManagerid(addUser.getAutoid());
                    ur.setRoleid(Long.valueOf(s));
                    ur.setRoletype(addUser.getReletype());
                    iRoleuserMapper.insert(ur);
                } else {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.LOGIN_ERROR_CODE_010.getCode(), request.getHeader("Accept-Language"));
                }
            }
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    private boolean verifyCode(String key, String code) {
        String result = redisServiceUtil.getCacheObject(RedisConstants.LOGIN_CODE + key);
        //验证码不存在直接返回null
        if (result == null) {
            return false;
        }
        return result.equals(code);
    }
}
