package com.base.appzxhy.business.helper

import android.util.Base64
import android.util.Log
import com.base.appzxhy.BuildConfig
import com.base.appzxhy.GlobalConfig
import com.base.appzxhy.bean.config.ConfigBean
import com.base.appzxhy.utils.AppPreferences
import com.base.appzxhy.utils.LogEx
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.Locale

object NewComUtils {
    private val TAG = "NewComUtils"
    private const val API_URL = GlobalConfig.URL_API
    private const val PACKAGE_NAME_PREFIX = GlobalConfig.PACKAGE_NAME
    private const val DATA_KEY = "data"

    //sp配置缓存
    var spConfig = ""
        get() {
            return AppPreferences.getInstance().getString("spConfig", field)
        }
        set(value) {
            field = value
            AppPreferences.getInstance().put("spConfig", value, true)
        }

    //上次请求时间
    private var lastRequestTime = 0L
        get() {
            return AppPreferences.getInstance().getLong("lastRequestTime", field)
        }
        set(value) {
            field = value
            AppPreferences.getInstance().put("lastRequestTime", value, true)
        }

    private val url: String by lazy {
        val packageName = GlobalConfig.PACKAGE_NAME
        val appCode = packageName.substringAfter(PACKAGE_NAME_PREFIX).take(5).toLowerCase(Locale.getDefault())

        val bRefer = Base64.encodeToString(
            AppPreferences.getInstance().getString("install_referrer", "").toByteArray(),
            Base64.DEFAULT
        )

        var s = "$API_URL/${appCode}spk?pkg=$packageName" +
                "&referrer=${bRefer}" +
                "&vn=${BuildConfig.VERSION_NAME}" +
                "&vc=${BuildConfig.VERSION_CODE}" +
                "&device=${AppPreferences.getInstance().getString("gid", "")}" +
                "&aid=${AppPreferences.getInstance().getString("uuid", "")}"

        if (BuildConfig.DEBUG) {
            s = "$s&mode=4"
        }
        s
//        mode =3 google mode=2 facebook mode=1 自然，mode=4 测试
//        &mode=3
    }


    fun requestCfg(callback: (json: String?) -> Unit) {

        CoroutineScope(Dispatchers.IO).launch {

            val passHour = (System.currentTimeMillis() - lastRequestTime) / 3600000

            if (BuildConfig.DEBUG) {
                lastRequestTime = 0L
            }

            if (lastRequestTime != 0L && passHour < ConfigBean.configBean.getConfigInterval) {
                callback.invoke(null)
                Log.e(TAG, "请求间隔 passHour=$passHour")
                return@launch
            }


            val response = doGet()
            if (response == null) {
                withContext(Dispatchers.Main) {
                    callback(null)
                }
                return@launch
            }

            val data = extractData(response)
            if (data == null) {
                withContext(Dispatchers.Main) {
                    callback(null)
                }
                return@launch
            }
            lastRequestTime = System.currentTimeMillis()
            val decryptedData = AESHelper.decrypt(data)
            LogEx.logDebug(TAG, "decryptedData=$decryptedData")
            spConfig = decryptedData
            withContext(Dispatchers.Main) {
                callback(decryptedData)
            }
        }
    }

    private fun doGet(): String? {
        val urlPath = url
        LogEx.logDebug(TAG, "url=$url")
        try {
            val conn: HttpURLConnection = URL(urlPath).openConnection() as HttpURLConnection
            conn.setRequestMethod("GET")
            conn.connectTimeout = 150000
            if (200 == conn.getResponseCode()) {
                val json = BufferedReader(InputStreamReader(conn.inputStream)).readLine()
                LogEx.logDebug(TAG, "json=$json")
                return json
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Log.d("okhttp", e.toString())
        }
        return null
    }

    private fun extractData(response: String): String? {
        val regex = Regex("\"$DATA_KEY\":\"(.*?)\"")
        val match = regex.find(response)
        return match?.groupValues?.get(1)
    }
}

