package com.huigou.topsun.sap.common;

import com.alibaba.fastjson.JSONWriter;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class EndpointInterceptor {

    private final static Logger LOG = LoggerFactory.getLogger(com.huigou.topsun.sap.common.EndpointInterceptor.class);

    @Around("@annotation(Endpoint)")
    public Object intercept(ProceedingJoinPoint pjp) throws Throwable {
        // HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Map<String, Object> result = new HashMap<>(2);
        try {
            pjp.proceed(pjp.getArgs());
            result.put("type", HttpServletResponse.SC_OK);
        } catch (IllegalArgumentException iae) {
            LOG.error("", iae);
            result.put("type", HttpServletResponse.SC_BAD_REQUEST);
            result.put("mesg", "请求失败," + iae.getMessage());
        } catch (Exception e) {
            LOG.error("", e);
            result.put("type", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            result.put("mesg", "请求失败");
        }
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(MimeTypeUtils.APPLICATION_JSON_VALUE);
        try (JSONWriter writer = new JSONWriter(response.getWriter())) {
            writer.writeObject(result);
            writer.flush();
        }
        return null;
    }

}
