package com.cheng.blzb.service

import android.content.Context
import android.content.Intent
import com.cheng.blzb.event.PushMessageEvent
import com.cheng.blzb.manager.UserConfigManager
import com.example.base.common.RxBus
import com.example.base.utils.L
import com.google.gson.Gson
import com.igexin.sdk.GTIntentService
import com.igexin.sdk.message.GTCmdMessage
import com.igexin.sdk.message.GTNotificationMessage
import com.igexin.sdk.message.GTTransmitMessage
import java.net.URISyntaxException


class PushIntentService : GTIntentService() {

    override fun onReceiveServicePid(context: Context?, pid: Int) {}

    /**
     * 此方法用于接收和处理透传消息。透传消息个推只传递数据，不做任何处理，客户端接收到透传消息后需要自己去做后续动作处理，如通知栏展示、弹框等。
     * 如果开发者在客户端将透传消息创建了通知栏展示，建议将展示和点击回执上报给个推。
     */
    override fun onReceiveMessageData(context: Context?, msg: GTTransmitMessage) {
        val payload = msg.payload
        val data = String(payload)
        L.d("receiver payload = $data") //透传消息文本内容
    }

    // 接收 cid
    override fun onReceiveClientId(context: Context?, clientid: String) {
        L.d("PushIntentService---onReceiveClientId -> clientid = $clientid")
        UserConfigManager.saveGTCid(clientid)
    }

    // cid 离线上线通知
    override fun onReceiveOnlineState(context: Context?, online: Boolean) {}

    // 各种事件处理回执
    override fun onReceiveCommandResult(context: Context?, cmdMessage: GTCmdMessage?) {}

    // 通知到达，只有个推通道下发的通知会回调此方法
    override fun onNotificationMessageArrived(context: Context?, msg: GTNotificationMessage?) {
        L.d("PushIntentService---onNotificationMessageArrived: ${Gson().toJson(msg)}")
        if (msg!!.intentUri != null) {
            try {
                val intent = Intent.parseUri(msg.intentUri, Intent.URI_INTENT_SCHEME)
                RxBus.defaultInstance.post(PushMessageEvent(intent.getStringExtra("payload") ?: "", 2))
            } catch (e: URISyntaxException) {
                L.d(e)
            }
        }
    }

    // 通知点击，只有个推通道下发的通知会回调此方法
    override fun onNotificationMessageClicked(context: Context?, msg: GTNotificationMessage?) {
        L.d("PushIntentService---onNotificationMessageClicked: ${Gson().toJson(msg)}")
        if (msg!!.intentUri != null) {
            try {
                val intent = Intent.parseUri(msg.intentUri, Intent.URI_INTENT_SCHEME)
                startActivity(intent)
            } catch (e: URISyntaxException) {
                L.d(e)
            }
        }
    }
}