package com.za.base

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.Gson
import com.za.bean.JpushBean
import com.za.common.log.LogUtil
import com.za.service.PushListener
import com.za.service.ServiceManager
import com.za.service.ZdPushServiceReceive

open class PushMessageActivity : AppCompatActivity() {
	private var currentDialog : AlertDialog? = null

	override fun onCreate(savedInstanceState : Bundle?) {
		super.onCreate(savedInstanceState)
//		setupPushMessageReceiver()
	}

	private fun setupPushMessageReceiver() {        // 注册推送消息接收器
		ServiceManager.registerPushListener(object : PushListener {
			override fun broadcast(msg : String) {
				sendMessageToMainProcess("broadcast", msg)
			}

			override fun giveUpOrder(jpushBean : JpushBean) {
				sendMessageToMainProcess("giveUp", Gson().toJson(jpushBean))
			}

			override fun importantTip(jpushBean : JpushBean) {
				sendMessageToMainProcess("importantTip", Gson().toJson(jpushBean))
			}

			override fun newOrderMsg(jpushBean : JpushBean) {
				sendMessageToMainProcess("newOrder", Gson().toJson(jpushBean))
			}

			override fun reDispatchOrder(jpushBean : JpushBean) {
				sendMessageToMainProcess("reDispatch", Gson().toJson(jpushBean))
			}

			override fun revokeOrder(jpushBean : JpushBean) {
				sendMessageToMainProcess("revoke", Gson().toJson(jpushBean))
			}
		})
	}

	private fun sendMessageToMainProcess(type : String, message : String) {        // 使用广播将消息发送到主进程
		val intent = Intent(ZdPushServiceReceive.RECEIVE_ACTION).setPackage(packageName)
		intent.putExtra("type", type)
		intent.putExtra("message", message)
		sendBroadcast(intent)
		LogUtil.print("KeepAliveService", "发送消息到主进程: $type")
	}

	override fun onPause() {
		super.onPause()
		dismissCurrentDialog()
	}

	private fun dismissCurrentDialog() {
		try {
			currentDialog?.dismiss()
			currentDialog = null
		} catch (e : Exception) {
			LogUtil.print("PushActivityLifecycleCallbacks", "关闭对话框失败: ${e.message}")
		}
	}

	companion object {
		internal const val GIVE_UP_TYPE_NORMAL = 1
		internal const val DIALOG_TAG_GIVE_UP = "giveUp"
	}
}