package com.dtok.framework.http;


import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

@Slf4j
public class LoggingInterceptor implements Interceptor {

    private static final Logger WMS_LOG = LoggerFactory.getLogger("WmsLog");

    public Response intercept(Chain chain) throws IOException {
        // 这个chain里面包含了request和response，所以你要什么都可以从这里拿
        Request request = chain.request();

        long t1 = System.nanoTime();// 请求发起的时间
        WMS_LOG.info(String.format("发送请求 %s on %s%n%s", request.url(), chain.connection(), request.headers()));
        log.info(String.format("发送请求 %s on %s%n%s", request.url(), chain.connection(), request.headers()));
//            WMS_LOG.info("请求参数:{\n +" + request.body().writeTo(); + "\n}");
        StringBuilder bodyLog = new StringBuilder();
        if (request.body() instanceof FormBody) {
            FormBody body = (FormBody) request.body();
            for (int i = 0; i < body.size(); i++) {
                bodyLog.append(body.encodedName(i)).append("=").append(body.encodedValue(i)).append(",");
            }
            WMS_LOG.info("请求参数:" + bodyLog.toString());
            log.info("请求参数:" + bodyLog.toString());
        }
//		System.out.println(String.format("发送请求 %s on %s%n%s", request.url(), chain.connection(), request.headers()));
        Response response = chain.proceed(request);

        long t2 = System.nanoTime();// 收到响应的时间

        // 这里不能直接使用response.body().string()的方式输出日志
        // 因为response.body().string()之后，response中的流会被关闭，程序会报错，我们需要创建出一
        // 个新的response给应用层处理
        ResponseBody responseBody = response.peekBody(1024 * 1024);
        String respStr = responseBody.string();
        WMS_LOG.info(String.format("接收响应: [%s] %n返回json:【%s】 %.1fms%n%s", response.request().url(),
                respStr, (t2 - t1) / 1e6d, response.headers()));
        log.info(String.format("接收响应: [%s] %n返回json:【%s】 %.1fms%n%s", response.request().url(),
                respStr, (t2 - t1) / 1e6d, response.headers()));
        return response;

    }

}
