package com.rc.httpcore.interceptor

import android.util.Log
import com.google.gson.Gson
import com.google.gson.JsonObject
import okhttp3.*
import okio.Buffer
import java.io.IOException

class RequestInterceptor : Interceptor {
    private val gson = Gson()
    private val TAG = "RequestInterceptor" // 日志标签

    override fun intercept(chain: Interceptor.Chain): Response {
        // 获取原始请求
        val originalRequest: Request = chain.request()

        // 处理不同类型的请求
        return when (originalRequest.method()) {
            "GET" -> handleGetRequest(originalRequest, chain)
            "POST" -> handlePostRequest(originalRequest, chain)
            else -> chain.proceed(originalRequest) // 对于其他请求方法，直接执行
        }
    }

    private fun handleGetRequest(request: Request, chain: Interceptor.Chain): Response {
        val response = chain.proceed(chain.request())
        val mediaType = response.body()!!.contentType()
        val content = response.body()!!.string()
        // 获取 URL 查询参数
        val url = request.url()
        val jsonParams = JsonObject()
        // 检查查询参数是否为空
        if (url.queryParameterNames().isEmpty()) {
            Log.d(TAG, "GET Request: ${request.url()}, No query parameters.")
        } else {
            // 将查询参数解析为 JsonObject
            for (name in url.queryParameterNames()) {
                val value = url.queryParameter(name)
                if (value != null) {
                    jsonParams.addProperty(name, value)
                } else {
                    jsonParams.addProperty(name, "default_value") // 可选：处理空值的默认值
                }
            }

            // 日志输出 GET 请求及其参数
            Log.d(TAG, "GET Request: ${request.url()}")
            Log.d(TAG, "GET Request: Params: ${gson.toJson(jsonParams)}")
            Log.d(TAG, "GET Request: Params: $content")
        }

        return response.newBuilder()
            .body(ResponseBody.create(mediaType, content))
            .build()
    }

    private fun handlePostRequest(request: Request, chain: Interceptor.Chain): Response {
        val response = chain.proceed(chain.request())
        val mediaType = response.body()!!.contentType()
        val content = response.body()!!.string()
        // 获取请求体并转换为字符串
        val requestBody = request.body() ?: throw IOException("Request body cannot be null")
        val jsonString = requestBodyToString(requestBody) ?: throw IOException("Request parameters cannot be null or empty")

        // 解析 JSON 并处理空值
        val jsonObject = gson.fromJson(jsonString, JsonObject::class.java)
        val fillDefaultValues = fillDefaultValues(jsonObject)

        // 创建新的请求体
        val modifiedRequestBody = RequestBody.create(requestBody.contentType(), gson.toJson(jsonObject))

        // 构建新的请求
        val modifiedRequest = request.newBuilder()
            .method(request.method(), modifiedRequestBody)
            .header("Authorization", "Bearer your_token_here") // 可选：添加认证头
            .build()

        // 日志输出 POST 请求
        Log.d(TAG, "POST Request: ${modifiedRequest.url()}, Body: ${gson.toJson(jsonObject)}")

        return response.newBuilder()
            .body(ResponseBody.create(mediaType, gson.toJson(jsonObject)))
            .build()
    }

    private fun requestBodyToString(body: RequestBody): String? {
        val buffer = Buffer()
        body.writeTo(buffer)
        return buffer.readUtf8()
    }

    private fun fillDefaultValues(jsonObject: JsonObject): String {
        // 遍历 JSON 对象并替换空值
        for ((key, value) in jsonObject.entrySet()) {
            if (value.isJsonNull || (value.isJsonPrimitive && value.asJsonPrimitive.isString && value.asString.isEmpty())) {
                jsonObject.addProperty(key, "default_value") // 设置默认值
            }
        }
        // 返回更新后的 JSON 字符串
        return gson.toJson(jsonObject)
    }
}