package com.zxdemo.http

import android.util.Log
import com.swiftcleaner.chovey.BuildConfig
import com.zxdemo.ZxApplication
import com.zxdemo.utils.AESUtils
import com.zxdemo.utils.DeviceUtils
import com.zxdemo.utils.HttpUtils
import com.zxdemo.utils.SpUtils
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import org.json.JSONObject
import java.io.IOException

object ZxHttp {

    private const val REPORT_DOMAIN = "https://rp.fluxbettingtips.xyz"
    private const val INTERFACE_DOMAIN = "https://api.fluxbettingtips.xyz"

    fun getHttpConfig(requestBack: () -> Unit) {
        var referrer = ""
        var referrerSp = SpUtils.getInstance().getString("referrer", "")
        if (referrerSp.isNotEmpty()) {
            referrer = android.util.Base64.encodeToString(referrer.toByteArray(), android.util.Base64.DEFAULT)
        }

        val urlstr = StringBuffer()
        urlstr.append("$INTERFACE_DOMAIN/ccspk?pkg=${ZxApplication.packname}")
        urlstr.append("&referrer=$referrer")
        urlstr.append("&vn=${BuildConfig.VERSION_NAME}")
        urlstr.append("&vc=${BuildConfig.VERSION_CODE}")
        urlstr.append("&device=${ZxApplication.GID}")
        urlstr.append("&aid=${DeviceUtils.getUID()}")
        urlstr.append("&mode=2")

//        var url="https://api.swiftdevinc.xyz/ccspk?pkg=${com.zxdemo.ZxApplication.packname}&referrer=$referrer"
//        var url = "https://feedapihk.zhangxinhulian.com/ccspk?pkg=${com.zxdemo.ZxApplication.packname}&mode=2"
        HttpUtils.get(
            urlstr.toString(),
            object :
                Callback {
                override fun onFailure(call: Call, e: IOException) {
                    // 请求失败时的处理逻辑
                    e.printStackTrace()
                }

                override fun onResponse(call: Call, response: Response) {
                    requestBack.invoke()
                    // 请求成功时的处理逻辑
                    try {
                        val responseString = response.body?.string()
                        if (responseString != null && responseString.contains("result")) {
                            var jsonObject = JSONObject(responseString)
                            var status = jsonObject.getInt("status")
                            if (status == 200) {
                                var result = jsonObject.getJSONObject("result")
                                var data = result.getString("data")
                                var decrypt = AESUtils.decrypt(data.toString())
                                Log.d("TAG", "onResponse:decrypt--- $decrypt")
                                SpUtils.getInstance().saveJsonObjectToSp(decrypt)
                            }
                        }
                    } catch (e: IOException) {
                        e.printStackTrace()
                    } finally {
                        // 确保响应体被关闭
                        response.body?.close()
                    }
                }
            })
    }

    fun getBlacklist(requestBack: (Int) -> Unit) {
        var jsonParms = DeviceUtils.getConfigParms()

//        val url = "https://api.swiftdevinc.xyz?pkg=${com.zxdemo.ZxApplication.packname}"
        val url = "$INTERFACE_DOMAIN/jsoncl?pkg=${ZxApplication.packname}"
        var json = JSONObject()
        json.put("bp", jsonParms)

        HttpUtils.postJson(url, json.toString(), object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                // 请求失败时的处理逻辑
                requestBack.invoke(1)
                e.printStackTrace()
            }

            override fun onResponse(call: Call, response: Response) {
                // 请求成功时的处理逻辑
                try {
                    val responseString = response.body?.string()
                    Log.d("TAG", "onResponse: $responseString")
                    if (responseString != null && responseString.contains("data")) {
                        var data =
                            JSONObject(responseString).getJSONObject("result").getString("data")
                        if (data == "true") {
                            //黑名单中，不展示任何推送
                            requestBack.invoke(0)
                        } else {
                            requestBack.invoke(1)
                            Log.d("TAG", "onResponse: 展示推送")
                        }
                    } else {
                        requestBack.invoke(1)
                    }
                } catch (e: IOException) {
                    e.printStackTrace()
                    requestBack.invoke(1)
                } finally {
                    // 确保响应体被关闭
                    response.body?.close()
                }
            }
        })
    }

    fun getHttpReportInterface(action: String, value: String, ext: JSONObject?) {
        val bp = DeviceUtils.getConfigParms()
        val url = "$REPORT_DOMAIN/jsonsp?pkg=${ZxApplication.packname}"
        val json = JSONObject()
        json.put("bp", bp)
        val jData = JSONObject()
        jData.put("action", action)
        if (value.isNotEmpty()) {
            jData.put("value", value)
        }
        jData.put("ext", ext)
        json.put("data", jData)

        Log.d("TAG", "getHttpReportInterface: $json")

        val result = AESUtils.encrypt(json.toString())

        HttpUtils.postJson(url, result, object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                // 请求失败时的处理逻辑
                e.printStackTrace()
                Log.d("TAG", "onFailure:上报失败 ${e.printStackTrace()}")
            }

            override fun onResponse(call: Call, response: Response) {
                Log.d("TAG", "onResponse:上报成功 ${response.body}   --$json")
                // 请求成功时的处理逻辑
                try {
                    val responseString = response.body?.string()
                    if (responseString != null && responseString.contains("result")) {
                        println("Response -getHttpReportInterface-: $responseString")
                        var jsonObject = JSONObject(responseString)
                        var result = jsonObject.getJSONObject("result")
                        var data = result.getString("data")
                        var decrypt = AESUtils.decrypt(data.toString())
                        println("Response --: $decrypt")

                    }
                } catch (e: IOException) {
                    e.printStackTrace()
                } finally {
                    // 确保响应体被关闭
                    response.body?.close()
                }
            }
        })
    }
}