package com.gh.gamecenter.acloud.push

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Build
import com.therouter.TheRouter
import com.alibaba.sdk.android.push.CloudPushService
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory
import com.gh.gamecenter.acloud.push.retrofit.RetrofitManager
import com.gh.gamecenter.common.BuildConfig
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.utils.toJson
import com.gh.gamecenter.common.utils.toRequestBody
import com.gh.gamecenter.core.provider.IAppProvider
import com.gh.gamecenter.core.utils.GsonUtils
import com.lightgame.utils.Utils
import io.reactivex.Single
import okhttp3.ResponseBody

object ACloudPushHelper {

    private const val PUSH_CHANNEL = "光环channel"

    /**
     * 初始化云推送通道
     * @param applicationContext
     */
    fun init(applicationContext: Context) {
        // 初始化云推送通道
        PushServiceFactory.init(applicationContext)
    }

    /**
     * 注册阿里云推送
     * @param applicationContext 上下文
     * @return 回调结果
     */
    fun register(applicationContext: Context): Single<String> {
        // Android 8.0+ 初始化NotificationChannel
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationManager =
                applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?
            // 用户可以看到的通知渠道的名字。
            val appProvider = TheRouter.get(IAppProvider::class.java)
            val name: CharSequence = appProvider?.getAppName() ?: "光环助手"
            val importance = NotificationManager.IMPORTANCE_HIGH
            val channel = NotificationChannel(PUSH_CHANNEL, name, importance)
            // 设置通知出现时的闪灯（如果Android设备支持的话）。
            channel.enableLights(true)
            channel.lightColor = Color.RED
            // 设置通知出现时的震动（如果Android设备支持的话）。
            channel.enableVibration(true)
            channel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
            // 创建通知渠道。
            notificationManager!!.createNotificationChannel(channel)
        }

        val pushService = PushServiceFactory.getCloudPushService()
        if (BuildConfig.DEBUG) {
            pushService.setLogLevel(CloudPushService.LOG_DEBUG)
        }

        return Single.create {
            pushService.register(applicationContext, ACloudPushCommonCallback(it))
        }
    }

    /**
     * 获取设备ID
     * @return 设备ID
     */
    fun getDeviceId(): String {
        val pushService = PushServiceFactory.getCloudPushService()
        return pushService.deviceId ?: ""
    }

    /**
     * 绑定账号
     * @param account 账号
     * @return 回调结果
     */
    fun bindAccount(account: String): Single<String> {
        val pushService = PushServiceFactory.getCloudPushService()
        return Single.create {
            pushService.bindAccount(
                account,
                ACloudPushCommonCallback(it)
            )
        }
    }

    /**
     * 绑定别名
     * @param alias 别名
     * @return 回调结果
     */
    fun bindAlias(alias: String): Single<String> {
        val data = mapOf(
            "device_id" to getDeviceId(),
            "user_id" to alias
        )
        return RetrofitManager
            .getInstance()
            .newApi
            .bindAlias(data.toRequestBody())
            .map { alias }
    }

    /**
     * 解绑别名
     * @param alias 别名
     * @return 回调结果
     */
    fun unbindAlias(alias: String): Single<String> {
        val data = mapOf(
            "device_id" to getDeviceId(),
            "user_id" to alias
        )
        return RetrofitManager
            .getInstance()
            .newApi
            .unbindAlias(data.toRequestBody())
            .map { alias }
    }

    /**
     * 绑定标签
     * @param tag 标签
     * @return 回调结果
     */
    fun bindTag(tag: String): Single<String> {
        val data = mapOf(
            "device_id" to getDeviceId(),
            "channel" to tag
        )
        return RetrofitManager
            .getInstance()
            .newApi
            .bindTag(data.toRequestBody())
            .map { tag }
    }

    /**
     * 处理通知栏点击事件
     * @param context 上下文
     * @param title 通知栏标题
     * @param summary 通知栏描述
     * @param extraMap json格式的附加参数
     */
    internal fun handleNotificationOpened(context: Context, title: String, summary: String, extraMap: String?) {
        Utils.log("ACloudPush->onNotificationOpened->title: $title, summary: $summary, extraMap: $extraMap")
        if (!extraMap.isNullOrEmpty()) {
            val map = GsonUtils.fromJson(extraMap, Map::class.java)
            val url = map["url"] as String?
            if (!url.isNullOrEmpty()) {
                val intent = Intent().apply {
                    data = Uri.parse(url)
                    action = Intent.ACTION_VIEW
                    addCategory(Intent.CATEGORY_DEFAULT)
                    addCategory(Intent.CATEGORY_BROWSABLE)
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                }
                context.startActivity(intent)
            }
        }
    }
}