package com.gh.gamecenter.jg.push

import android.annotation.SuppressLint
import android.content.Context
import android.net.Uri
import android.os.Build
import android.util.Base64
import cn.jiguang.api.utils.JCollectionAuth
import cn.jpush.android.api.JPushInterface
import com.gh.gamecenter.common.entity.LinkEntity
import com.gh.gamecenter.common.utils.SensorsBridge
import com.gh.gamecenter.common.utils.singleToMain
import com.gh.gamecenter.common.utils.toRequestBody
import com.gh.gamecenter.core.provider.IAppProvider
import com.gh.gamecenter.core.utils.GsonUtils
import com.gh.gamecenter.jg.push.retrofit.RetrofitManager
import com.lightgame.utils.Utils
import com.therouter.TheRouter

object JPushHelper {
    const val TAG = "JPushHelper"
    private const val KEY_REGISTRATION_ID = "registration_id"

    private var badgeCount = 0 // 角标计数

    var onPushOpenedCallback: ((String, String, String, String, String) -> Unit)? = null

    fun init(applicationContext: Context) {
        // 关闭SDK自启动 (https://docs.jiguang.cn/jverification/guideline/jghgzy)
        JCollectionAuth.enableAutoWakeup(applicationContext, false)
        JPushInterface.setSmartPushEnable(applicationContext, false)
        JPushInterface.setLinkMergeEnable(applicationContext, false)
        JPushInterface.setNotificationCallBackEnable(applicationContext, true)

        JPushInterface.setDebugMode(BuildConfig.DEBUG)
        JPushInterface.init(applicationContext)
    }

    fun setChannel(context: Context, channel: String) {
        JPushInterface.setChannel(context, channel)
    }

    fun getRegistrationId(context: Context): String = JPushInterface.getRegistrationID(context)

    // 绑定ID关系
    @SuppressLint("CheckResult")
    fun bindRegistrationId(registrationId: String?) {
//        SensorsBridge.profileSet(KEY_REGISTRATION_ID, registrationId ?: "")

        val appProvider = TheRouter.get(IAppProvider::class.java)
        val data = mapOf(
            "oaid" to appProvider?.getOaid(),
            "registration_id" to registrationId,
            "system_version" to Build.VERSION.RELEASE,
            "application_version" to appProvider?.getAppVersion(),
            "channel" to appProvider?.getChannel()
        )
        RetrofitManager.getInstance().newApi.bind(data.toRequestBody())
            .compose(singleToMain())
            .subscribe({
                Utils.log(TAG, "bind response: ${it.string()}")
            }, {
                Utils.log(TAG, "bind error $it")
            })
    }

    // 角标+1
    fun appendBadgeNumber(applicationContext: Context) {
        JPushInterface.setBadgeNumber(applicationContext, ++badgeCount)
    }

    // 角标-1
    fun subtractBadgeNumber(applicationContext: Context) {
        JPushInterface.setBadgeNumber(applicationContext, if (badgeCount > 0) --badgeCount else 0)
    }

    // 清除角标
    fun cleanBadgeNumber(applicationContext: Context) {
        badgeCount = 0
        JPushInterface.setBadgeNumber(applicationContext, badgeCount)
    }

    fun onNotifyMessageOpened(
        id: String,
        title: String,
        content: String,
        deepLink: String,
    ) {
        val uri = Uri.parse(deepLink)
        val dataString = uri.getQueryParameter("data") ?: return
        val linkData: ByteArray = Base64.decode(dataString, Base64.DEFAULT)
        val linkDataString = String(linkData, charset("UTF-8"))
        val link = GsonUtils.fromJson(linkDataString, LinkEntity::class.java)

        onPushOpenedCallback?.invoke(id, title, content, link.type ?: "", link.link ?: "")
    }
}