package com.ywt.alipaympapi.aop;

import com.alibaba.fastjson.JSON;
import com.ywt.dto.HeaderDTO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * @Desc 统一日志处理、统一返回
 */
@Aspect
@Component
@Slf4j
public class WebResultAspect {

    private Long take;

    @Pointcut("execution(public * com.ywt..controller..*.*(..)) ")
    public void controllerAspect() {
    }

    @Around("controllerAspect()")
    public Object proceed(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HeaderDTO headerDTO = getHeaderParams(request);

        //获取所有参数方法一：
        List<String> parameterList = new ArrayList<>();
        Enumeration<String> enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String paraName = enu.nextElement();
            parameterList.add(paraName + ": " + request.getParameter(paraName));
        }

        log.info("Request, URI:{}, Method : {} ___ {}, header : {}, Parameters : {}", request.getRequestURI(), joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), JSON.toJSONString(headerDTO), JSON.toJSONString(parameterList));
        return joinPoint.proceed();
    }

    @Before("controllerAspect()")
    public void before() {
        take = System.currentTimeMillis();

    }

    @AfterReturning("controllerAspect()")
    public void returnString() {
        log.info("this method takes : {}  ", System.currentTimeMillis() - take);
    }

    private HeaderDTO getHeaderParams(HttpServletRequest request) {
        String appId = request.getHeader("appId");
        String alipayUid = request.getHeader("alipayUid");
        String ticket = request.getHeader("ticket");
        return new HeaderDTO(alipayUid, appId, ticket);
    }
}
