package com.za.service

import android.app.Activity
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.media.RingtoneManager
import android.os.Build
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.AppUtils
import com.google.gson.Gson
import com.za.base.BaseActivityLifecycleCallbacks
import com.za.bean.JpushBean
import com.za.common.GlobalData
import com.za.common.log.LogUtil
import com.za.common.speech.SpeechManager
import com.za.servicing.R
import com.za.ui.servicing.order_give_up.OrderGiveUpActivity
import com.za.ui.view.CommonDialogFragment

class ZdPushServiceReceive : BroadcastReceiver() {
	companion object {
		const val RECEIVE_ACTION = "com.zd.servicing.PUSH_MESSAGE"
		private const val GIVE_UP_TYPE_NORMAL = 1
		private const val DIALOG_TAG_GIVE_UP = "giveUp"
	}

	private fun handlerMessage(context : Context?, intent : Intent?) {
		val activity = context ?: ActivityUtils.getTopActivity()
		activity as? AppCompatActivity
		if (intent?.action == RECEIVE_ACTION) {
			val type = intent.getStringExtra("type") ?: return
			val message = intent.getStringExtra("message") ?: return
			if (ActivityUtils.getTopActivity() == null) {
				AppUtils.launchApp(GlobalData.application.packageName)
			}
			LogUtil.print("PushActivityLifecycleCallbacks", "收到来自远程进程的消息: $type")
			when (type) {
				"broadcast" -> handleBroadcast("broadcast:$message")

				"giveUp" -> {
					try {
						val jpushBean = Gson().fromJson(message, JpushBean::class.java)
						val activity = BaseActivityLifecycleCallbacks.Companion.getCurrentActivity()
							?: ActivityUtils.getTopActivity()
						if (activity is AppCompatActivity) {
							handleGiveUpOrder(activity, jpushBean)
						}
					} catch (e : Exception) {
						LogUtil.print("PushActivityLifecycleCallbacks",
							"处理订单放弃消息失败: ${e.message}")
					}
				}                        // 处理其他类型的消息...
				"importantTip" -> {
					try {
						val jpushBean = Gson().fromJson(message, JpushBean::class.java)
						val activity = BaseActivityLifecycleCallbacks.Companion.getCurrentActivity()
							?: ActivityUtils.getTopActivity()
						if (activity is AppCompatActivity) {
							handleImportantTip(activity, jpushBean)
						}
					} catch (e : Exception) {
						LogUtil.print("PushActivityLifecycleCallbacks",
							"处理重要提示消息失败: ${e.message}")
					}
				}

				"reDispatch" -> {
					try {
						val jpushBean = Gson().fromJson(message, JpushBean::class.java)
						val activity = BaseActivityLifecycleCallbacks.Companion.getCurrentActivity()
							?: ActivityUtils.getTopActivity()
						if (activity is AppCompatActivity) {
							handleReDispatchOrder(activity, jpushBean)
						}
					} catch (e : Exception) {
						LogUtil.print("PushActivityLifecycleCallbacks",
							"处理订单重新派发消息失败: ${e.message}")
					}
				}

				"revoke" -> {
					try {
						val activity = BaseActivityLifecycleCallbacks.Companion.getCurrentActivity()
							?: ActivityUtils.getTopActivity()
						if (activity is AppCompatActivity) {
							handleRevokeOrder(activity)
						}
					} catch (e : Exception) {
						LogUtil.print("PushActivityLifecycleCallbacks",
							"处理订单撤回消息失败: ${e.message}")
					}
				}

			}
		}
	}

	private fun handleGiveUpOrder(activity : Activity, jpushBean : JpushBean) {
		if (activity !is AppCompatActivity) return

		// 播放提示音
		playNotificationSound(activity)

		if (GlobalData.currentOrder != null && GlobalData.currentOrder?.taskId == jpushBean.taskId) {
			SpeechManager.playCurrentOrderCanceled()
			CommonDialogFragment(title = "订单放弃",
				message = buildGiveUpMessage(jpushBean),
				confirmText = "去拍照",
				cancelText = "我已了解",
				confirm = {
					OrderGiveUpActivity.Companion.goOrderGiveUpActivity(activity,
						giveUpType = GIVE_UP_TYPE_NORMAL,
						userOrderId = jpushBean.userOrderId,
						taskId = jpushBean.taskId)
				}).show(activity.supportFragmentManager, DIALOG_TAG_GIVE_UP)
		} else {
			SpeechManager.playOrderCanceled()
		}
	}

	private fun handleRevokeOrder(activity : Activity) {
		playNotificationSound(activity)
		SpeechManager.speech("订单被撤回")
		ActivityUtils.getTopActivity().finish()
	}

	private fun handleReDispatchOrder(activity : Activity, jpushBean : JpushBean) {
		playNotificationSound(activity)
		BaseActivityLifecycleCallbacks.Companion.getCurrentActivity()?.let { currentActivity ->
			if (currentActivity is AppCompatActivity) {
				AlertDialog.Builder(currentActivity).setTitle("订单重新派发")
					.setMessage(buildReDispatchMessage(jpushBean)).setCancelable(false)
					.setPositiveButton("确定") { dialog, _ ->
						dialog.dismiss()
						currentActivity.finish()
					}.show()
			}
		}
	}

	private fun handleImportantTip(activity : Activity, jpushBean : JpushBean) {
		playNotificationSound(activity)
		SpeechManager.speech("重要提醒：${jpushBean.tipContent ?: ""}")
		AlertDialog.Builder(activity).setTitle("重要提醒").setMessage(jpushBean.tipContent)
			.setNegativeButton("我已了解") { dialog : DialogInterface, _ : Int -> dialog.dismiss() }
			.show()
	}

	// Handle broadcast messages
	private fun handleBroadcast(msg : String) {
		try {
			val content = msg.substring(10)
			sendNotification(GlobalData.application, content)
			LogUtil.print("JpushMessage", "Broadcast content: $content")
		} catch (e : Exception) {
			LogUtil.print("JpushMessage", "Broadcast failed: ${e.message}")
		}
	}

	private fun buildReDispatchMessage(jpushBean : JpushBean) : String {
		return buildString {
			append("该订单已重新派发")
			jpushBean.taskCode?.let { append("\n\n订单号：$it") }
			jpushBean.address?.let { append("\n地址：$it") }
			jpushBean.addressRemark?.let {
				if (it.isNotBlank()) {
					append("\n\n备注：$it")
				}
			}
		}
	}


	private fun buildGiveUpMessage(jpushBean : JpushBean) : String {
		return buildString {
			append("该工单已放弃")
			jpushBean.taskCode?.let { append("\n\n订单号：$it") }
			jpushBean.address?.let { append("\n地址：$it") }
			append("\n\n是否需要拍放空照片？")
		}
	}

	private fun playNotificationSound(activity : Activity?) {
		try {
			val notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
			RingtoneManager.getRingtone(activity, notification)?.play()
		} catch (e : Exception) {
			LogUtil.print("PushActivityLifecycleCallbacks", "播放提示音失败: ${e.message}")
		}
	}

	private val CHANNEL_ID = "ImportantMessagesChannel"
	private val NOTIFICATION_ID = 1003

	// Initialize notification channel
	private fun createNotificationChannel(context : Context) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			val channel = NotificationChannel(CHANNEL_ID,
				"订单通知",
				NotificationManager.IMPORTANCE_HIGH).apply {
				description = "用于接收重要消息通知"
				setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION),
					Notification.AUDIO_ATTRIBUTES_DEFAULT)
				enableVibration(true)
			}
			val notificationManager =
				context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
			notificationManager.createNotificationChannel(channel)
		}
	}

	// Send notification
	private fun sendNotification(context : Context, message : String) {
		createNotificationChannel(context)
		val notification =
			NotificationCompat.Builder(context, CHANNEL_ID).setContentTitle("重要通知")
				.setContentText(message).setSmallIcon(R.mipmap.ic_launcher) // 替换为你的应用图标
				.setPriority(NotificationCompat.PRIORITY_HIGH).setAutoCancel(true) // 点击后自动取消通知
				.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
				.setVibrate(longArrayOf(0, 100, 200, 300)).build()

		val notificationManager =
			context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
		notificationManager.notify(NOTIFICATION_ID, notification)
	}

	override fun onReceive(context : Context?, intent : Intent?) {
		handlerMessage(context, intent)
	}
}