package com.zxhyis.toolss.ad

import android.os.Build
import android.util.Log
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ScreenUtils
import com.zxhyis.toolss.BuildConfig
import com.zxhyis.toolss.FileApp
import com.zxhyis.toolss.ad.KokoReportHelper.isCharging
import com.zxhyis.toolss.ad.bean.EventParams
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import org.json.JSONObject
import java.io.IOException

object EventHelper {

    private val url by lazy {
        val pkg = ConfigHelper.packageName
        val url = StringBuilder("${ConfigHelper.eventUrl}/${pkg.filter { it.isLowerCase() }.substring(4, 9)}sp")
        url.append("?pkg=$pkg")
        url.toString()
    }

    fun getEvenParams(eventParams: EventParams?): JSONObject {
        val pkg = ConfigHelper.packageName
        val d2 = JSONObject()

        if (eventParams != null) {
//            Log.e("getEvenParams", "eventParams=$eventParams")
            d2.put("${pkg}_1", "${eventParams.screenWidth}")
                .put("${pkg}_2", "${eventParams.screenHeight}")
                .put("${pkg}_4", Build.MANUFACTURER)
                .put("${pkg}_3", eventParams.mode)
                .put("${pkg}_5", Build.VERSION.SDK_INT)
                .put("${pkg}_6", "${eventParams.networkType}")
                .put("${pkg}_8", eventParams.appVersionName)
                .put("${pkg}_9", eventParams.androidID)
                .put("${pkg}_10", ConfigHelper.gid)
                .put("${pkg}_11", System.getProperty("http.agent"))
                .put("${pkg}_13", "android")
                .put("${pkg}_14", "${AppUtils.getAppVersionCode()}")
                .put("${pkg}_15", "google")
                .put("${pkg}_24", BuildConfig.BUILD_TYPE)
                .put("${pkg}_25", KokoReportHelper.isShellRooted())
                .put("${pkg}_26", KokoReportHelper.isHooked())
                .put("${pkg}_27", KokoReportHelper.isVirtualMachine())
                .put("${pkg}_28", KokoReportHelper.isSimCardInserted(FileApp.fContext))
                .put("${pkg}_29", KokoReportHelper.isProxy(FileApp.fContext))
                .put("${pkg}_30", KokoReportHelper.isVpnConnected(FileApp.fContext))
                .put("${pkg}_31", KokoReportHelper.isEnableDeveloperDebug(FileApp.fContext))
                .put("${pkg}_32", isCharging(FileApp.fContext))
                .put("${pkg}_33", GravitySensorManager.sensorParam)
        } else {
            d2.put("${pkg}_1", "${ScreenUtils.getScreenHeight()}")
                .put("${pkg}_2", "${ScreenUtils.getScreenWidth()}")
                .put("${pkg}_4", Build.MANUFACTURER)
                .put("${pkg}_3", DeviceUtils.getModel())
                .put("${pkg}_5", Build.VERSION.SDK_INT)
                .put("${pkg}_6", "${NetworkUtils.getNetworkType()}")
                .put("${pkg}_8", AppUtils.getAppVersionName())
                .put("${pkg}_9", DeviceUtils.getAndroidID())
                .put("${pkg}_10", ConfigHelper.gid)
                .put("${pkg}_11", System.getProperty("http.agent"))
                .put("${pkg}_13", "android")
                .put("${pkg}_14", "${AppUtils.getAppVersionCode()}")
                .put("${pkg}_15", "google")
                .put("${pkg}_24", BuildConfig.BUILD_TYPE)
                .put("${pkg}_25", KokoReportHelper.isShellRooted())
                .put("${pkg}_26", KokoReportHelper.isHooked())
                .put("${pkg}_27", KokoReportHelper.isVirtualMachine())
                .put("${pkg}_28", KokoReportHelper.isSimCardInserted(FileApp.fContext))
                .put("${pkg}_29", KokoReportHelper.isProxy(FileApp.fContext))
                .put("${pkg}_30", KokoReportHelper.isVpnConnected(FileApp.fContext))
                .put("${pkg}_31", KokoReportHelper.isEnableDeveloperDebug(FileApp.fContext))
                .put("${pkg}_32", isCharging(FileApp.fContext))
                .put("${pkg}_33", GravitySensorManager.sensorParam)
        }

        return d2
    }

    fun event(
        key: String,
        value: String? = null,
        ext: JSONObject? = null,
        isSingleEvent: Boolean = false,
        eventParams: EventParams? = null
    ) {
        if (isSingleEvent) {
            val stringSet = SPUtils.getInstance().getStringSet("singleEvent")
            if (stringSet.contains(key)) {
                return
            }
        }

        val d1 = JSONObject()
            .put("action", key)
            .put("value", value)
            .put("ext", ext)

        val data = JSONObject()
            .put("data", d1)
            .put("bp", getEvenParams(eventParams))
            .toString()

        var encrypt = ""
        try {
            //这里加密有崩溃
            encrypt = AESHelper.encrypt(data)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        val body = encrypt.toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())

        val client = OkHttpClient.Builder().apply {
            if (BuildConfig.DEBUG) {
                addInterceptor(HttpLoggingInterceptor().apply {
                    level = HttpLoggingInterceptor.Level.BODY
                })
            }
        }.build()

        val request = Request.Builder()
            .url(url)
            .post(body)
            .build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
            }

            override fun onResponse(call: Call, response: Response) {
                Log.d("TAG", "event: $key")
                if (isSingleEvent) {
                    val stringSet = SPUtils.getInstance().getStringSet("singleEvent", mutableSetOf())
                    stringSet.add(key)
                    SPUtils.getInstance().put("singleEvent", stringSet)
                }
            }
        })
    }
}