package com.cheng.blzb.net

import android.text.TextUtils
import com.cheng.blzb.common.Constants
import com.cheng.blzb.manager.UserConfigManager
import com.cheng.blzb.utils.StringUtils
import com.example.base.utils.L
import okhttp3.Interceptor
import okhttp3.Response
import okio.Buffer
import java.nio.charset.StandardCharsets
import java.util.Arrays
import java.util.Locale

/**
 * @date 2020-06-05 13:53
 * @desc 网络请求可以在此处添加n多的请求拦截-加密数据
 */

class RequestInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        val method = request.method.lowercase(Locale.getDefault()).trim { it <= ' ' }
        val url = request.url
        val apiPath = String.format("%s", url)
        L.d("TAG-->>url=$apiPath")
        //如果请求的不是服务端的接口则不用加密
        if (!apiPath.startsWith(Constants.BaseUrl)) {
            L.d("TAG-->>content-type=${request.headers["Content-Type"]}")
            val requestBody = request.body
            L.d("TAG-->>${requestBody.toString()}")
            return chain.proceed(request)
        }
        var queryString = url.encodedQuery
        queryString = if (!TextUtils.isEmpty(queryString)) {
            (queryString + "&nonce=" + StringUtils.createUUID()) + "&timestamp=" + UserConfigManager.serverTimeMillis() / 1000
        } else {
            ("nonce=" + StringUtils.createUUID()) + "&timestamp=" + UserConfigManager.serverTimeMillis() / 1000
        }
        val sortQueryString = Arrays.stream(queryString.split("&".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray())
            .sorted { obj: String, anotherString: String? -> obj.compareTo(anotherString!!) }
            .reduce { x: String, y: String -> "$x&$y" }
            .get()
        //如果请求方式是get或者delete 则没有body
        var paramsStr = ""
        var bytes = ByteArray(0)
        var signature: String? = ""
        if (method == "put" || method == "post") {
            val requestBody = request.body
            L.d("TAG-->>${requestBody.toString()}")
            val buffer = Buffer()
            requestBody!!.writeTo(buffer)
            bytes = StringUtils.addByte(bytes, buffer.readByteArray())
            L.e("签名后bodyByte的长度为" + bytes.size)
            paramsStr = String(bytes, StandardCharsets.UTF_8)
            //            paramsStr = buffer.readUtf8();
            L.e("签名后body的长度为" + paramsStr.length)
        }
        signature = if (bytes.isNotEmpty()) {
            L.e("当前的数组长度为----" + bytes.size)
            StringUtils.getMD5Byte(
                StringUtils.addByte(
                    StringUtils.addByte("$sortQueryString&".toByteArray(), bytes),
                    ("&" + StringUtils.getMD5String(Constants.Signature)).toByteArray()
                )
            )
        } else {
            StringUtils.getMD5String(sortQueryString + "&" + StringUtils.getMD5String(Constants.Signature))
        }
        val newUrl = apiPath.split("\\?".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0] + "?" + queryString + "&signature=" + signature
        L.e("签名后的路径---", newUrl)
        request = request.newBuilder().url(newUrl).build()

        return chain.proceed(request)
    }

}