package com.diagbot.aop;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.diagbot.dto.QcCasesDTO;
import com.diagbot.dto.QcCasesEntryHospitalDTO;
import com.diagbot.dto.SysLoginLogDTO;
import com.diagbot.dto.SysOperationLogDTO;
import com.diagbot.dto.SysRoleDTO;
import com.diagbot.entity.BasDeptInfo;
import com.diagbot.entity.QcType;
import com.diagbot.dto.SysUserRoleDTO;
import com.diagbot.entity.SysHospitalSet;
import com.diagbot.entity.SysRole;
import com.diagbot.entity.SysUser;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.facade.LoginLogFacade;
import com.diagbot.facade.OperationLogFacade;
import com.diagbot.facade.SysHospitalSetFacade;
import com.diagbot.util.AddressUtils;
import com.diagbot.util.HttpUtils;
import com.diagbot.util.IpUtils;
import com.diagbot.util.ListUtil;
import com.diagbot.util.StringUtil;
import com.diagbot.util.SysUserUtils;
import com.diagbot.vo.DeleteQcTypeVO;
import com.diagbot.vo.QcCasesEntryUpdataVO;
import com.diagbot.vo.QcCasesSaveListVO;
import com.diagbot.vo.SysRoleMenuSaveVO;
import com.diagbot.vo.SysUserBaseVO;
import com.diagbot.vo.SysUserDeptVO;
import com.diagbot.vo.SysUserRoleVO;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description:日志记录处理
 * @author: songxl
 * @time: 2022/5/09 14:28
 */

@Aspect
@Component
public class LogAspect {
    @Autowired
    LoginLogFacade loginLogFacade;
    @Autowired
    SysHospitalSetFacade sysHospitalSetFacade;
    @Autowired
    OperationLogFacade operationLogFacade;

    // 操作配置织入点
    @Pointcut("execution(public * com.diagbot.web.*.*(..))" +
            "&& !execution(public * com.diagbot.web.SysUserController.getJwt(..))" +
            "&& !execution(public * com.diagbot.web.SysUserController.getCaptcha(..))" +
            "&& !execution(public * com.diagbot.web.SysUserController.getJwtNoPass(..))" +
            "&& !execution(public * com.diagbot.web.SysUserController.getHospitalMark(..))" +
            "&& !execution(public * com.diagbot.web.SysUserController.midifyPassword(..))"
    )
    public void operPointCut() {
    }

    // 登录织入点
    @Pointcut("execution(public * com.diagbot.web.SysUserController.getJwt(..))")
    public void loginAfterReturning() {
    }


    /**
     * 登录成功之后执行
     *
     * @param
     */
    @AfterReturning(pointcut = "loginAfterReturning()", returning = "jsonResult")
    public void loginAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        loginLogHandle(joinPoint, jsonResult);
    }

    /**
     * 操作之前执行
     *
     * @param
     */
    @Before(value = "operPointCut()")
    public void operPointCut(JoinPoint joinPoint) {
        operationLogHandler(joinPoint);
    }

    /**
     * 操作日志处理类
     *
     * @param joinPoint
     * @Return void
     */
    private void operationLogHandler(JoinPoint joinPoint) {

        try {
            //1.去sys_hospital_set表中拿所有需要进行操作日志记录的url
            List<SysHospitalSet> hospitalSets = sysHospitalSetFacade
                    .getHospitalSetByRemark(Long.parseLong(SysUserUtils.getCurrentHospitalID()), "operationLog");
            if (ListUtil.isNotEmpty(hospitalSets)) {
                havingOperation(hospitalSets, HttpUtils.getHttpServletRequest(), joinPoint);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 有包含操作日志配置的进行处理
     *
     * @param hospitalSets       操作日志配置
     * @param httpServletRequest 请求
     * @param joinPoint          入参
     * @Return void
     */
    private void havingOperation(List<SysHospitalSet> hospitalSets, HttpServletRequest httpServletRequest, JoinPoint joinPoint) {

        StringBuffer operationRecordBuffer = new StringBuffer();
        //结果拼接容器
        Map<String, Object> outMap = new HashMap<>();
        initOutMap(outMap);
        //1.判断该请求是否需要操作日志记录
        hospitalSets.stream().forEach(hospitalSet -> {
            if (matchers(hospitalSet.getCode(), httpServletRequest)) {
                operationUrlHandler(outMap, HttpUtils.getHttpServletRequest().getRequestURI(), joinPoint);
                //替换拼接结果
                String operationRecord = makeOperationRecord(hospitalSet.getValue(), outMap);
                if (!operationRecord.contains("#")) {
                    operationRecordBuffer.append(operationRecord).append(";");
                }

                //                try {
                //                    //由于两个对象大多结构不一样（例如:obj list），对比先不统一处理，放到case中每个方法单独处理
                //                                        Object old = getOldOperation(HttpUtils.getHttpServletRequest().getRequestURI(), params);
                //                                        Object[] args = joinPoint.getArgs();
                //                                        if (args != null && args.length > 0){
                //                                            for(int i = 0;i<args.length;i++){
                //                                                //对比
                //                                                comparePara(old, args[i]);
                //                                            }
                //
                //                                        }
                //                } catch (Exception e) {
                //                    e.printStackTrace();
                //                }
            }

        });
        //保存操作记录
        saveOperationLog(joinPoint, operationRecordBuffer.toString());
    }

    /**
     * 一些常用结果装入map集合
     *
     * @param outMap
     * @Return void
     */
    private void initOutMap(Map<String, Object> outMap) {
        //添加excelName：获取前端要导出的文件名
        if (StringUtil.isNotBlank(SysUserUtils.getExcelName())) {
            try {
                outMap.put("#excelName", URLDecoder.decode(SysUserUtils.getExcelName(), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        if (StringUtil.isNotBlank(SysUserUtils.getIsPlacefile())) {
            outMap.put("#isPlacefile", SysUserUtils.getIsPlacefile());
        }
    }

    /**
     * 保存操作日志
     *
     * @param joinPoint
     * @param operationRecord
     * @Return void
     */
    private void saveOperationLog(JoinPoint joinPoint, String operationRecord) {

        try {
            if (StringUtil.isNotBlank(operationRecord)) {
                SysOperationLogDTO operationLog = new SysOperationLogDTO();
                Date date = new Date();
                operationLog.setOperationDate(date);
                operationLog.setGmtCreate(date);
                operationLog.setOperationId(SysUserUtils.getCurrentPrincipleID());
                try {
                    SysUser sysUser = operationLogFacade.getSysUser(Long.parseLong(SysUserUtils.getCurrentPrincipleID()));
                    if (sysUser != null) {
                        operationLog.setOperationName(sysUser.getLinkman());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                String ip = HttpUtils.getIpAddress();
                if (IpUtils.isIPv4LiteralAddress(ip)) {
                    operationLog.setOperationIp(ip);
                } else {
                    operationLog.setRemark("[非ipv4地址]:" + ip);
                }

                // 设置方法名称
                String className = joinPoint.getTarget().getClass().getName();
                String methodName = joinPoint.getSignature().getName();
                operationLog.setOperationMethod(className + "." + methodName + "()");
                // 设置请求方式
                operationLog.setOperationWay(HttpUtils.getHttpServletRequest().getMethod());
                operationLog.setOperationUrl(HttpUtils.getHttpServletRequest().getRequestURI());
                // 处理设置注解上的参数
                try {
                    String params = getControllerMethodDescription(joinPoint);
                    if (StringUtils.isNotBlank(params)) {
                        operationLog.setOperationParam(params);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                operationLog.setIsPlacefile(SysUserUtils.getIsPlacefile() == null ? "0" : SysUserUtils.getIsPlacefile());
                operationLog.setOperationRecord(operationRecord.substring(0, operationRecord.length() - 1));
                operationLog.setHospitalId(SysUserUtils.getCurrentHospitalID());
                operationLogFacade.getBaseMapper().addOperationRecord(operationLog);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 操作日志模板拼接
     *
     * @param value  数据库模板内容弄个
     * @param outMap 拼接集合<占位符,替换值>
     * @Return java.lang.String
     */
    private String makeOperationRecord(String value, Map<String, Object> outMap) {

        if (StringUtil.isBlank(value) || outMap.keySet().size() == 0) {
            return value;
        }
        //直接占位符替换
        for (String key : outMap.keySet()) {
            if (value.contains(key)) {
                value = value.replaceAll(key, outMap.get(key) + "");
            }
        }
        try {
            //对通过入参的值为key获取value[针对统一url，根据入参的值不同，替换的内容也不同，把这些内容拼接到模板value中{"入参值1":"拼接结果1","入参值2":"拼接结果2","key":"入参名称"}]
            value = transformModeValue(value, outMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

    /**
     * 针对根据入参值不同取不同内容进行处理
     * 根据入参的值不同，替换的内容也不同，把这些内容拼接到模板value中{"入参值1":"拼接结果1","入参值2":"拼接结果2","key":"入参名称"}
     *
     * @param value
     * @param outMap
     * @Return java.lang.String
     */
    private String transformModeValue(String value, Map<String, Object> outMap) {
        while (value.contains("{") && value.contains("}")) {
            String strParam = value.substring(value.indexOf("{"), value.indexOf("}") + 1);
            JSONObject paramJSON = JSONObject.parseObject(strParam);
            String temp = paramJSON.getString(outMap.get("#" + paramJSON.getString("key")) + "");
            if (temp == null) {
                temp = "#";
            }
            value = StringUtils.replace(value, strParam, temp);
        }
        return value;
    }

    private void comparePara(Object old, Object params, Map<String, Object> outMap) {
        try {
            //对比新旧数据变化
            compareTwoClass(old, params, outMap);
            //拼接操作结果
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 两个对象进行比较
     *
     * @param class1
     * @param class2
     * @param outMap
     * @Return void
     */
    public static void compareTwoClass(Object class1, Object class2, Map<String, Object> outMap) {

        //获取对象的class
        Class<?> clazz1 = class1.getClass();
        Class<?> clazz2 = class2.getClass();
        //获取对象的属性列表
        Field[] field1 = clazz1.getDeclaredFields();
        Field[] field2 = clazz2.getDeclaredFields();
        List<String> fieldList1 = new ArrayList<>();
        for (Field field : field1) {
            fieldList1.add(field.getName());
        }
        for (Field field : field2) {
            fieldList1.remove(field.getName());
        }

        //遍历属性列表field1
        for (int i = 0; i < field1.length; i++) {
            field1[i].setAccessible(true);
            //遍历属性列表field2
            for (int j = 0; j < field2.length; j++) {
                //如果field1[i]属性名与field2[j]属性名内容相同
                if (field1[i].getName().equals(field2[j].getName())) {
                    field2[j].setAccessible(true);
                    try {
                        //如果field1[i]属性值与field2[j]属性值内容不相同
                        if (!compareTwo(field1[i].get(class1), field2[j].get(class2))) {
                            outMap.put("#" + field1[i].getName() + "_old", field1[i].get(class1));
                            outMap.put("#" + field1[i].getName() + "_new", field2[j].get(class2));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
            //把old中有的属性new中没有的加入map
            if (fieldList1.contains(field1[i].getName())) {
                try {
                    outMap.put("#" + field1[i].getName(), field1[i].get(class1));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    //对比两个数据是否内容相同
    public static boolean compareTwo(Object object1, Object object2) {

        if (object1 == null && object2 == null) {
            return true;
        }
        if (object1 == null && object2 != null) {
            return false;
        }
        if (object1.equals(object2)) {
            return true;
        }
        return false;
    }

    private Object getOldOperation(String requestURI, String params) {
        switch (requestURI) {
            case "/qc/cases/saveQcCases"://修改模块分值
                if (StringUtil.isNotEmpty(params)) {
                    //通过id获取模块名称以及目前分值
                    JSONObject paramJSON = JSONObject.parseObject(params);
                    QcCasesDTO old = operationLogFacade.getQcCasesById(paramJSON.getJSONArray("qcCasesSaveVOList")
                            .getJSONObject(0).getString("id"));
                    return old;
                }
                break;
        }
        return null;
    }

    /**
     * 操作日志处理中心
     *
     * @param outMap
     * @param requestURI
     * @param joinPoint
     * @Return void
     */
    private void operationUrlHandler(Map<String, Object> outMap, String requestURI, JoinPoint joinPoint) {

        try {
            Object[] args = joinPoint.getArgs();
            switch (requestURI) {
                case "/qc/cases/saveQcCases"://修改模块分值
                    if (null != args && args.length >= 0) {
                        //通过id获取模块名称以及目前分值
                        if (args[0] instanceof QcCasesSaveListVO) {
                            QcCasesSaveListVO qcCasesSaveListVO = (QcCasesSaveListVO) args[0];
                            QcCasesDTO old = operationLogFacade.getQcCasesById(qcCasesSaveListVO.getQcCasesSaveVOList().get(0).getId() + "");
                            compareTwoClass(old, qcCasesSaveListVO.getQcCasesSaveVOList().get(0), outMap);
                        }
                    }
                    break;
                case "/sys/user/disable"://禁用用户
                    if (null != args && args.length >= 0) {
                        //通过id获取用户具体信息
                        if (args[0] instanceof SysUserBaseVO) {
                            SysUserBaseVO sysUserBaseVO = (SysUserBaseVO) args[0];
                            SysUser sysUser = operationLogFacade.getSysUser(sysUserBaseVO.getUserId());
                            compareTwoClass(sysUser, sysUserBaseVO.getUserId(), outMap);
                        }
                    }
                    break;
                case "/sys/user/enable"://启用用户
                    if (null != args && args.length >= 0) {
                        //通过id获取用户具体信息
                        if (args[0] instanceof SysUserBaseVO) {
                            SysUserBaseVO sysUserBaseVO = (SysUserBaseVO) args[0];
                            SysUser sysUser = operationLogFacade.getSysUser(sysUserBaseVO.getUserId());
                            compareTwoClass(sysUser, sysUserBaseVO.getUserId(), outMap);
                        }
                    }
                    break;
                case "/sys/role/saveRoleMenu"://修改角色权限
                    if (null != args && args.length >= 0) {
                        //通过id获取角色信息
                        if (args[0] instanceof SysRoleMenuSaveVO) {
                            SysRoleMenuSaveVO sysRoleMenuSaveVO = (SysRoleMenuSaveVO) args[0];
                            SysRole sysRole = operationLogFacade.getRoleMenu(sysRoleMenuSaveVO.getRoleId());
                            compareTwoClass(sysRole, sysRoleMenuSaveVO, outMap);
                        }
                    }
                    break;
                case "/sys/user/editUserRoles"://修改用户角色
                    if (null != args && args.length >= 0) {
                        //通过id获取角色信息
                        if (args[0] instanceof SysUserRoleVO) {
                            SysUserRoleVO sysUserRoleVO = (SysUserRoleVO) args[0];
                            SysUserRoleDTO sysUserRoleDTO = operationLogFacade.editUserRoles(sysUserRoleVO.getUserId());
                            SysUser sysUser = operationLogFacade.getSysUser(sysUserRoleVO.getUserId());
                            compareTwoClass(sysUser, sysUserRoleVO.getUserId(), outMap);
                            if (ListUtil.isNotEmpty(sysUserRoleDTO.getSelRoles())) {
                                if (ListUtil.isNotEmpty(sysUserRoleVO.getRoleIds())) {
                                    List<Long> oldRoleIds = sysUserRoleDTO.getSelRoles().stream().map(SysRoleDTO::getId).collect(Collectors.toList());
                                    List<Long> temp = new ArrayList<>(sysUserRoleVO.getRoleIds());
                                    temp.removeAll(oldRoleIds);
                                    if (ListUtil.isNotEmpty(temp)) {//角色被改动
                                        List<SysRole> roles = operationLogFacade.getSysUserRoles(sysUserRoleVO.getRoleIds());
                                        outMap.put("#roles", roles.stream().map(SysRole::getName).collect(Collectors.joining(",")));
                                    } else if (sysUserRoleVO.getRoleIds().size() != oldRoleIds.size()) {//两次角色不一致
                                        List<SysRole> roles = operationLogFacade.getSysUserRoles(sysUserRoleVO.getRoleIds());
                                        outMap.put("#roles", roles.stream().map(SysRole::getName).collect(Collectors.joining(",")));
                                    }
                                } else {
                                    outMap.put("#roles", "空");
                                }
                            } else {
                                if (ListUtil.isNotEmpty(sysUserRoleVO.getRoleIds())) {//角色被改动
                                    List<SysRole> roles = operationLogFacade.getSysUserRoles(sysUserRoleVO.getRoleIds());
                                    outMap.put("#roles", roles.stream().map(SysRole::getName).collect(Collectors.joining(",")));
                                }
                            }
                        }
                    }
                    break;
                case "/sys/user/editUserDepts"://修改用户科室
                    if (null != args && args.length >= 0) {
                        //通过id获取角色信息
                        if (args[0] instanceof SysUserDeptVO) {
                            SysUserDeptVO sysUserDeptVO = (SysUserDeptVO) args[0];
                            //获取用户现在的科室信息
                            List<String> oldDeptIds = operationLogFacade.getUserDept(sysUserDeptVO.getUserId());
                            SysUser sysUser = operationLogFacade.getSysUser(sysUserDeptVO.getUserId());
                            compareTwoClass(sysUser, sysUserDeptVO.getUserId(), outMap);
                            if (ListUtil.isNotEmpty(oldDeptIds)) {
                                if (ListUtil.isNotEmpty(sysUserDeptVO.getDeptIds())) {
                                    List<String> temp = new ArrayList<>(sysUserDeptVO.getDeptIds());
                                    temp.removeAll(oldDeptIds);
                                    if (ListUtil.isNotEmpty(temp)) {//科室被改动
                                        List<BasDeptInfo> deptInfos = operationLogFacade.getSysDepts(sysUserDeptVO.getDeptIds());
                                        outMap.put("#depts", deptInfos.stream().map(BasDeptInfo::getDeptName).collect(Collectors.joining(",")));
                                    } else if (sysUserDeptVO.getDeptIds().size() != oldDeptIds.size()) {//两次科室不一致
                                        List<BasDeptInfo> deptInfos = operationLogFacade.getSysDepts(sysUserDeptVO.getDeptIds());
                                        outMap.put("#depts", deptInfos.stream().map(BasDeptInfo::getDeptName).collect(Collectors.joining(",")));
                                    }
                                } else {
                                    outMap.put("#depts", "空");
                                }
                            } else {
                                if (ListUtil.isNotEmpty(sysUserDeptVO.getDeptIds())) {//科室被改动
                                    List<BasDeptInfo> deptInfos = operationLogFacade.getSysDepts(sysUserDeptVO.getDeptIds());
                                    outMap.put("#depts", deptInfos.stream().map(BasDeptInfo::getDeptName).collect(Collectors.joining(",")));
                                }
                            }
                        }
                    }
                    break;
                case "/qc/casesEntryHospital/updataQcCasesEntry"://修改条目提示信息
                    if (null != args && args.length >= 0) {
                        //通过id获取模块名称以及目前分值
                        if (args[0] instanceof QcCasesEntryUpdataVO) {
                            QcCasesEntryUpdataVO qcCasesEntryUpdataVO = (QcCasesEntryUpdataVO) args[0];
                            QcCasesEntryHospitalDTO qcCasesEntryHospitalDTO = operationLogFacade.getQcCasesEntryById(qcCasesEntryUpdataVO.getId());
                            compareTwoClass(qcCasesEntryHospitalDTO, qcCasesEntryUpdataVO, outMap);
                        }
                    }
                    break;
                case "/qc/qcType/delete":
                    if (null != args && args.length >= 0) {
                        if (args[0] instanceof DeleteQcTypeVO) {
                            DeleteQcTypeVO deleteQcTypeVO = (DeleteQcTypeVO) args[0];
                            if (ListUtil.isNotEmpty(deleteQcTypeVO.getIds())) {
                                QcType qcType = operationLogFacade.getQCTypeById(deleteQcTypeVO.getIds().get(0));
                                compareTwoClass(qcType, new Object(), outMap);
                            }
                        }
                    }
                    break;
                default:
                    if (null != args && args.length >= 0) {
                        for (Object o : args) {
                            compareTwoClass(o, new Object(), outMap);
                        }
                    }
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * @Description:获取请求的参数
     * @Param: [joinPoint, logInformation]
     * @return: void
     * @Author: cy
     * @Date: 2021/9/2
     */
    private String getControllerMethodDescription(JoinPoint joinPoint) {
        Map<String, String[]> map = HttpUtils.getHttpServletRequest().getParameterMap();
        if (MapUtils.isNotEmpty(map)) {
            String params = JSONObject.toJSONString(map);
            return params;
        } else {
            Object args = joinPoint.getArgs();
            if (null != args) {
                String params = argsArrayToString(joinPoint.getArgs());
                return params;
            }
        }
        return "";
    }


    /**
     * 参数拼装
     *
     * @Description:
     * @Param: [paramsArray]
     * @return: java.lang.String
     * @Author: cy
     * @Date: 2021/9/2
     */
    private String argsArrayToString(Object[] paramsArray) {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0) {
            for (int i = 0; i < paramsArray.length; i++) {
                if (null != (paramsArray[i])) {
                    Object jsonObj = JSONObject.toJSONString(paramsArray[i]);
                    params += jsonObj.toString() + " ";
                }
            }
        }
        return params.trim();
    }

    /**
     * 登录日志处理
     *
     * @param joinPoint
     * @param jsonResult
     * @Return void
     */
    public void loginLogHandle(JoinPoint joinPoint, Object jsonResult) {
        // 返回参数
        if (null != jsonResult) {
            ObjectMapper objectWriter = new ObjectMapper();
            try {
                String strResult = objectWriter.writeValueAsString(jsonResult);
                JSONObject JSONResult = JSONObject.parseObject(strResult);
                SysLoginLogDTO loginLog = new SysLoginLogDTO();
                Date date = new Date();
                loginLog.setLoginDate(date);
                loginLog.setGmtCreate(date);
                String token = JSONResult.getJSONObject("data").get("accessToken").toString();
                DecodedJWT jwt = decodedJWT(token);
                Map<String, Claim> claims = jwt.getClaims();
                Claim claimUID = claims.get("user_id");
                Claim claimUName = claims.get("user_name");
                loginLog.setLoginId(claimUID.asLong());
                loginLog.setLoginName(claimUName.asString());
                loginLog.setLoginIp(HttpUtils.getIpAddress() == null ? "" : HttpUtils.getIpAddress());
                UserAgent userAgent = UserAgent.parseUserAgentString(HttpUtils.getHttpServletRequest().getHeader("User-Agent"));
                loginLog.setLoginAddress(AddressUtils.getRealAddressByIP(loginLog.getLoginIp()));
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();
                loginLog.setLoginBrowser(browser);
                String hospitalId = claims.get("hosp_id").asLong()+"";
                loginLog.setHospitalId(hospitalId == null ? "0" : hospitalId);

                //插入登录日志
                loginLogFacade.getBaseMapper().addLoginLog(loginLog);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * token解析
     *
     * @param token
     * @Return com.auth0.jwt.interfaces.DecodedJWT
     */
    public static DecodedJWT decodedJWT(String token) {

        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt;
        } catch (JWTDecodeException var2) {
            var2.printStackTrace();
            throw new CommonException(CommonErrorCode.ANALYZER_TOKEN_FAIL);
        }
    }

    /**
     * url比对
     *
     * @param url
     * @param request
     * @Return boolean
     */
    private boolean matchers(String url, HttpServletRequest request) {

        AntPathRequestMatcher matcher = new AntPathRequestMatcher(url);
        if (matcher.matches(request)) {
            return true;
        }
        return false;
    }
}


