package com.cheng.blzb.net

import android.content.Intent
import android.text.TextUtils
import android.util.Log
import com.alibaba.fastjson.JSON
import com.example.base.common.RxBus
import com.example.base.utils.L
import com.example.base.utils.Utils
import com.cheng.blzb.BuildConfig
import com.cheng.blzb.common.Constants
import com.cheng.blzb.event.HomeRefreshEvent
import com.cheng.blzb.manager.LoginManager
import com.cheng.blzb.ui.activity.LoginActivity
import com.cheng.blzb.ui.activity.PublicActivity
import com.cheng.blzb.ui.fragment.mine.vip.VipFragment
import com.cheng.blzb.utils.AESpkcs7paddingUtil
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Response
import okhttp3.ResponseBody
import java.nio.charset.Charset
import java.nio.charset.UnsupportedCharsetException


/**
 * @date 2020-06-05 13:55
 * @desc 可以在此处添加n多的响应拦截- 比如解密数据
 */
class ResponseInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val url = request.url
        val apiPath = String.format("%s", url)
        //如果请求的不是服务端的接口则不用加密
        if (!apiPath.startsWith(if (BuildConfig.DEBUG) Constants.TestUrl else Constants.BaseUrl)) {
            return chain.proceed(request)
        }
        val response = chain.proceed(request)
        var charset = Charset.forName("UTF-8")
        val contentType = response.header("Content-Type")
        if (contentType != null && contentType.contains("application/json")) {
            val responseBody = response.body
            if (responseBody != null) {
                val source = responseBody.source()
                source.request(Long.MAX_VALUE)
                val buffer = source.buffer
                val mediaType = responseBody.contentType()
                if (mediaType != null) {
                    try {
                        charset = mediaType.charset(Charset.forName("UTF-8"))
                    } catch (e: UnsupportedCharsetException) {
                        e.printStackTrace()
                    }
                }
                val respBody = buffer.clone().readString(charset!!)
                L.d("response=${respBody}")
                if (TextUtils.isEmpty(respBody)) {
                    return response
                }
                val code = JSON.parseObject(respBody).getInteger("code")
                if (code == 1001003 || code == 1001004 || code == 1001005) {
                    LoginManager.logout()
                    val intent = Intent(Utils.getApp(), LoginActivity::class.java)
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    Utils.getApp().startActivity(intent)
                }

                val isEncrypt = JSON.parseObject(respBody).getBoolean("encrypt")
                L.e("是否需要解密$isEncrypt")
                if (isEncrypt == null || !isEncrypt) { //如果不需要加密 直接返回
                    L.d("response=${response.body}")
                    return response
                }
                val decrybody = JSON.parseObject(respBody).getString("data")
                L.e("Json解析后的字符串为$decrybody")
                var decryString: String?
                try {
                    decryString = AESpkcs7paddingUtil.decryptNormal(decrybody, Constants.Encrypt)
                    Log.e("ResponseInterceptor", "解密后返回的字符串为$decryString")
                    val decCode = JSON.parseObject(decryString).getInteger("code")
                    when (decCode) {
                        11018 -> {
                            RxBus.defaultInstance.post(HomeRefreshEvent())
                        }

                        19000 -> {
                            PublicActivity.newStart(Utils.getApp(), VipFragment::class.java, Pair("origin", "interceptor"))
                        }

                        1001003, 1001004, 1001005 -> {
                            LoginManager.logout()
                            val intent = Intent(Utils.getApp(), LoginActivity::class.java)
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                            Utils.getApp().startActivity(intent)
                        }
                    }

                    //返回新创建的response
                    return response.newBuilder().body(ResponseBody.create("text/plain".toMediaType(), decryString)).build()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
        return response
    }

}