package com.xingxi.api.configuration;

import com.xingxi.common.annotation.Log;
import com.xingxi.api.common.DTO;
import com.xingxi.api.common.ResponseDTO;
import com.xingxi.system.domain.SysOperLog;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.springframework.scheduling.annotation.Async;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RequiredArgsConstructor
//@Component
class OperLogService {
    private final ObjectMapper objectMapper;

    @Async
    public void handleBeforeLog(JoinPoint joinPoint, Log controllerLog, HttpServletRequest request) {

        DTO dto = null;
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if (arg instanceof DTO) {
                dto = (DTO)arg;
                break;
            }
        }

        String jsonParams = null;
        try {
            jsonParams = objectMapper.writeValueAsString(dto);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        String url = request.getRequestURI();
        if (request.getQueryString() != null) {
            url += "?" + request.getQueryString();
        }

        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();

        String requestId = (String) request.getAttribute("X-REQUEST-ID");
        SysOperLog sysOperLog = new SysOperLog();
        sysOperLog.setMethod(className + "." + methodName + "()");
        sysOperLog.setStatus(0);
        sysOperLog.setBusinessType(0);
        sysOperLog.setOperatorType(2);
        sysOperLog.setDeptName("定制模块接口");
        sysOperLog.setTitle(controllerLog.title());
        sysOperLog.setOperName(requestId);
        sysOperLog.setOperParam(jsonParams);
        sysOperLog.setRequestMethod(request.getMethod());
        sysOperLog.setOperUrl(url);
    }

    @Async
    public void handleAfterLog(ResponseDTO<?> responseDTO, HttpServletRequest request){
        String requestId = (String) request.getAttribute("X-REQUEST-ID");
//        SysOperLog sysOperLog = sysOperLogRepository.selectSysOperLogByOperName(requestId);
//        if (sysOperLog != null) {
//            try {
//                sysOperLog.setJsonResult(objectMapper.writeValueAsString(responseDTO));
//                sysOperLog.setOperTime(new Date());
//                sysOperLogRepository.deleteOperLogByIds(new String[] {sysOperLog.getOperId() + ""});
//                sysOperLogRepository.insertOperlog(sysOperLog);
//            } catch (JsonProcessingException e) {
//                e.printStackTrace();
//            }
//        }
    }
}
