package com.njcn.web.service.impl;

import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.StrUtil;
import com.njcn.common.config.GeneralInfo;
import com.njcn.common.pojo.constant.LogInfo;
import com.njcn.common.pojo.dto.LogInfoDTO;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.ReflectCommonUtil;
import com.njcn.web.service.ILogService;
import com.njcn.web.utils.RequestUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.MethodArgumentNotValidException;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;


/**
 * @author hongawen
 * @version 1.0.0
 * @date 2022年03月14日 15:20
 */
@Slf4j
@Service
@AllArgsConstructor
public class LogServiceImpl implements ILogService {

    /**
     * 部分登录前的操作，获取用户名登录名的方式需特殊处理
     */
    private final static List<String> UN_LOGIN_METHOD = Arrays.asList("首次登录修改密码", "登录认证", "根据登录名查询用户信息", "认证后根据用户名判断用户状态", "更新用户登录认证密码错误次数", "根据登录名获取公钥", "根据客户端名查询信息");


    private final GeneralInfo generalInfo;

    /**
     * 异步记录controller中返回的信息内容
     *
     * @param request        请求头
     * @param returnType     返回类型
     * @param httpResult     返回结果
     * @param methodDescribe 方法描述
     */
    @Override
    @Async("asyncExecutor")
    public void recodeAdviceLog(ServerHttpRequest request, MethodParameter returnType, HttpResult httpResult, String methodDescribe) {
        //处理审计日志
        String userName;
        HttpServletRequest httpServletRequest = RequestUtil.getRequest(request);
        if (UN_LOGIN_METHOD.contains(methodDescribe)) {
            userName = RequestUtil.getLoginName(httpServletRequest);
        } else {
            userName = RequestUtil.getUserNickname(request);
        }
        String result = httpResult.getCode().equalsIgnoreCase(CommonResponseEnum.FAIL.getCode()) ? CommonResponseEnum.FAIL.getMessage() : CommonResponseEnum.SUCCESS.getMessage();
        String ip = RequestUtil.getRealIp(request);
        String type = ReflectCommonUtil.getOperateInfoByMethod(returnType.getMethod()).getOperateType();
        String level = ReflectCommonUtil.getOperateInfoByMethod(returnType.getMethod()).getOperateLevel();
        String operateType = ReflectCommonUtil.getOperateTypeByMethod(returnType.getMethod());
        LogInfoDTO logInfoDTO = new LogInfoDTO(userName, methodDescribe, result, ip, type, level, operateType, generalInfo.getMicroServiceName());
        System.out.println(logInfoDTO);
    }


    /**
     * 异步记录全局异常捕获器中返回的信息内容
     *
     * @param exception 异常数据
     * @param request   请求信息
     * @param message   信息
     */
    @Override
    @Async("asyncExecutor")
    public void recodeBusinessExceptionLog(Exception exception, HttpServletRequest request, String message) {
        LogInfoDTO tempLogInfo = RequestUtil.initLogInfo(request);
        //认证前，获取用户信息
        if (Objects.equals(tempLogInfo.getUserName(), LogInfo.UNKNOWN_USER)) {
            tempLogInfo.setUserName(RequestUtil.getLoginName(request));
        }
        //根据异常获取method方法
        Method method = ReflectCommonUtil.getMethod(exception);
        if (exception instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) exception;
            method = methodArgumentNotValidException.getParameter().getMethod();
        }
        String methodDescribe = StrFormatter.format("{}{}{}", ReflectCommonUtil.getMethodDescribeByMethod(method), StrUtil.C_COMMA, message);
        String result = CommonResponseEnum.FAIL.getMessage();
        String type = ReflectCommonUtil.getOperateInfoByMethod(method).getOperateType();
        String level = ReflectCommonUtil.getOperateInfoByMethod(method).getOperateLevel();
        String operateType = ReflectCommonUtil.getOperateTypeByMethod(method);
        LogInfoDTO logInfoDTO = new LogInfoDTO(tempLogInfo.getUserName(), methodDescribe, result, tempLogInfo.getIp(), type, level, operateType, generalInfo.getMicroServiceName());
        System.out.println(logInfoDTO);

    }

    /**
     * 异步记录全局异常捕获器中返回的信息内容
     *
     * @param exception 异常数据
     * @param request   请求信息
     * @param message   信息
     * @param userName  用户名
     */
    @Override
    @Async("asyncExecutor")
    public void recodeAuthExceptionLog(Exception exception, HttpServletRequest request, String message, String userName) {
        //根据异常获取method方法
        Method method = ReflectCommonUtil.getMethod(exception);
        if (exception instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) exception;
            method = methodArgumentNotValidException.getParameter().getMethod();
        }
        String methodDescribe = StrFormatter.format("{}{}{}", ReflectCommonUtil.getMethodDescribeByMethod(method), StrUtil.C_COMMA, message);
        String result = CommonResponseEnum.FAIL.getMessage();
        String ip = RequestUtil.getRealIp(request);
        String type = ReflectCommonUtil.getOperateInfoByMethod(method).getOperateType();
        String level = ReflectCommonUtil.getOperateInfoByMethod(method).getOperateLevel();
        String operateType = ReflectCommonUtil.getOperateTypeByMethod(method);
        LogInfoDTO logInfoDTO = new LogInfoDTO(userName, methodDescribe, result, ip, type, level, operateType, generalInfo.getMicroServiceName());
        System.out.println(logInfoDTO);

    }


}
