package mingzuozhibi.action;

import mingzuozhibi.support.Dao;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Optional;

public class BaseController {

    protected static final String MEDIA_TYPE = MediaType.APPLICATION_JSON_UTF8_VALUE;
    protected Logger LOGGER;

    @Autowired
    protected Dao dao;

    public BaseController() {
        LOGGER = LoggerFactory.getLogger(this.getClass());
    }

    protected String objectResult(Object result) {
        JSONObject root = new JSONObject();
        root.put("success", true);
        root.put("data", result);
        return root.toString();
    }

    protected String errorMessage(String message) {
        JSONObject root = new JSONObject();
        root.put("success", false);
        root.put("message", message);
        return root.toString();
    }

    protected void responseText(HttpServletResponse response, String content) throws IOException {
        response.setContentType(MEDIA_TYPE);
        byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
        response.setContentLength(bytes.length);
        response.getOutputStream().write(bytes);
        response.flushBuffer();
    }

    protected Optional<Authentication> getAuthentication() {
        return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication());
    }

    protected String getUserName() {
        return getAuthentication().map(Authentication::getName).orElse("null");
    }

    protected ServletRequestAttributes getAttributes() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return ((ServletRequestAttributes) attributes);
    }

    private String getRemoteAddr() {
        HttpServletRequest request = getAttributes().getRequest();
        String xRealIp = request.getHeader("X-Real-IP");
        return xRealIp != null ? xRealIp : request.getRemoteAddr();
    }

    private String getCommon() {
        HttpServletRequest request = getAttributes().getRequest();
        String common = String.format("[%s][%s][%s][%s][%s]",
                getRemoteAddr(), getUserName(), request.getMethod(),
                request.getRequestURI(), paramString(request));
        return common.replace("{}", "\\{}");
    }

    private String paramString(HttpServletRequest request) {
        StringBuilder builder = new StringBuilder();
        request.getParameterMap().forEach((key, arr) -> {
            if (arr.length == 0) {
                builder.append(key).append('&');
            } else if (arr.length == 1) {
                builder.append(key).append('=').append(arr[0]).append('&');
            } else {
                builder.append(key).append('=').append(Arrays.toString(arr)).append('&');
            }
        });
        if (builder.length() > 0) {
            builder.deleteCharAt(builder.length() - 1);
        } else {
            builder.append("NoParam");
        }
        return builder.toString();
    }

    protected void debugRequest(String format, Object... args) {
        LOGGER.debug(getCommon() + format, args);
    }

    protected void infoRequest(String format, Object... args) {
        LOGGER.info(getCommon() + format, args);
    }

    protected void warnRequest(String format, Object... args) {
        LOGGER.warn(getCommon() + format, args);
    }

    protected void errorRequest(String format, Object... args) {
        LOGGER.error(getCommon() + format, args);
    }

}

@@ -2594,24 +2594,42 @@
 tCommon() %7B%0A
+        try %7B%0A    
         Http
@@ -2687,24 +2687,28 @@
 ();%0A        
+   
+ 
 String commo
@@ -2750,11 +2750,19 @@
 %5B%25s%5D
-%22,%0A
+%5B%25s%5D%22,%0A    
     
@@ -2834,32 +2834,36 @@
                 
+  
+  
 request.getReque
@@ -2870,16 +2870,37 @@
 stURI(),
+ bodyString(request),
  paramSt
@@ -2911,24 +2911,28 @@
 (request));%0A
+    
         retu
@@ -2960,14 +2960,616 @@
 %22, %22
-%5C%5C%7B%7D%22)
+%7Bempty%7D%22);%0A        %7D catch (Exception e) %7B%0A            return String.format(%22%5B%E8%8E%B7%E5%8F%96%E8%AF%B7%E6%B1%82%E6%95%B0%E6%8D%AE%E5%A4%B1%E8%B4%A5%5D%5Berror=%25s%5D%22, e.getMessage())%0A                    .replace(%22%7B%7D%22, %22%7Bempty%7D%22);%0A        %7D%0A    %7D%0A%0A    private Object bodyString(HttpServletRequest request) %7B%0A        Object jsonRequestBody = request.getAttribute(%22JSON_REQUEST_BODY%22);%0A        if (jsonRequestBody instanceof String) %7B%0A            String body = (String) jsonRequestBody;%0A            if (body.length() %3E 200) %7B%0A                return body.substring(0, 200) + %22...%22;%0A            %7D else %7B%0A                return body;%0A            %7D%0A        %7D%0A        return %22NoBody%22
 ;%0A  

Add Log Request BodyString