package  com.test.basd.smartjunkcleaner.display


import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Build
import android.service.notification.StatusBarNotification
import android.util.Log
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.test.basd.smartjunkcleaner.R
import com.test.basd.smartjunkcleaner.activity.AppManagerActivity
import com.test.basd.smartjunkcleaner.activity.BatteryInfoActivity
import com.test.basd.smartjunkcleaner.activity.MainActivity
import com.test.basd.smartjunkcleaner.activity.ScanJunkActivity
import com.test.basd.smartjunkcleaner.display.NotificationHelper.postActionNotification
import com.test.basd.smartjunkcleaner.helps.BaseApplication
import com.test.basd.smartjunkcleaner.helps.EventHelper
import com.test.basd.smartjunkcleaner.helps.KotlinExt.string
import com.test.basd.smartjunkcleaner.service.FlashlightService


object NotificationUtils {

    private val TAG = "NotificationUtils"
    const val NOTIFICATION_TAG = "SmartCleanNotification"
    private const val CHANNEL_ID = "Misc"

    fun showNotification(
        context: Context,
        notificationId: Int,
        remoteViews: RemoteViews,
        closeViewId: Int,
        pendingIntent: PendingIntent,
        pushStayTime: Long
    ) {
        if (closeViewId != 0) {
            val closeIntent = Intent(context, CloseNotificationReceiver::class.java).apply {
                putExtra("notificationId", notificationId)
            }
            val closePendingIntent =
                PendingIntent.getBroadcast(context, 0, closeIntent, PendingIntent.FLAG_MUTABLE)
            remoteViews.setOnClickPendingIntent(closeViewId, closePendingIntent)
        }
        val builder = createNotificationBuilder(context, remoteViews, pendingIntent, pushStayTime)
        sendNotification(context, notificationId, builder)
    }

    private fun createNotificationBuilder(
        context: Context,
        remoteViews: RemoteViews,
        pendingIntent: PendingIntent,
        pushStayTime: Long
    ): NotificationCompat.Builder {
        val notificationManager =
            context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel =
                NotificationChannel(CHANNEL_ID, CHANNEL_ID, NotificationManager.IMPORTANCE_HIGH)
            channel.lockscreenVisibility = NotificationCompat.VISIBILITY_PUBLIC
            notificationManager.createNotificationChannel(channel)
        }

        val deleteIntent = Intent(context, CloseNotificationReceiver::class.java).apply {
            action = "DELETE_NOTIFICATION"
        }
        val deletePendingIntent = PendingIntent.getBroadcast(context, 0, deleteIntent, PendingIntent.FLAG_MUTABLE)

        return NotificationCompat.Builder(context, CHANNEL_ID)
            .setSmallIcon(R.mipmap.logo)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setCategory(NotificationCompat.CATEGORY_ALARM)
            .setWhen(System.currentTimeMillis())
            .setAutoCancel(true)
            .setDeleteIntent(deletePendingIntent)
            .setContentIntent(pendingIntent)
            .setContent(remoteViews)
            .setCustomHeadsUpContentView(remoteViews)
            .setCustomBigContentView(remoteViews)
            .setCustomContentView(remoteViews)
            .setStyle(NotificationCompat.BigTextStyle())
            .setFullScreenIntent(pendingIntent, true)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setTimeoutAfter(pushStayTime)
            .setSound(null)
            .setLights(0, 0, 0)
            .setVibrate(null)
            .setAllowSystemGeneratedContextualActions(true)
            .setBubbleMetadata(null)
    }

    private fun sendNotification(
        context: Context,
        notificationId: Int,
        builder: NotificationCompat.Builder
    ) {
        val notificationManager =
            context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val notification = builder.build()
        notificationManager.notify(NOTIFICATION_TAG, notificationId, notification)
    }


    fun createPermanentNotification(context: Context): Notification {
        Log.d(
            "startForegroundService",
            "Start foreground service."
        )
        val isOngoing = true //是否持续(为不消失的常驻通知)
        val channelName = R.string.foreground_service_channel.string()
        val channelId = "Service_Id"
        val category = Notification.CATEGORY_SERVICE
        val contentView = RemoteViews(context.packageName, R.layout.reminder_layout_notification_notify)
        val expendView = RemoteViews(context.packageName, R.layout.reminder_layout_notification_big_notify)

        val intent0 = Intent(context, ScanJunkActivity::class.java)
        val pendingIntent0 =
            PendingIntent.getActivity(context, 0, intent0, PendingIntent.FLAG_IMMUTABLE)
        contentView.setOnClickPendingIntent(R.id.id_ll_clean, pendingIntent0)
        expendView.setOnClickPendingIntent(R.id.id_ll_clean, pendingIntent0)


        val intent2 = Intent(context, BatteryInfoActivity::class.java)
        val pendingIntent2 =
            PendingIntent.getActivity(context, 0, intent2, PendingIntent.FLAG_IMMUTABLE)
        contentView.setOnClickPendingIntent(R.id.id_battery, pendingIntent2)
        expendView.setOnClickPendingIntent(R.id.id_battery, pendingIntent2)

        val intent3 = Intent()
        val serviceComponent = ComponentName(context, FlashlightService::class.java)
        intent3.component = serviceComponent
        val pendingIntent3 =
            PendingIntent.getService(context, 0, intent3, PendingIntent.FLAG_IMMUTABLE)
        contentView.setOnClickPendingIntent(R.id.id_lighit, pendingIntent3)
        expendView.setOnClickPendingIntent(R.id.id_lighit, pendingIntent3)

        val intent4 = Intent(context, AppManagerActivity::class.java)
        val pendingIntent4 =
            PendingIntent.getActivity(context, 0, intent4, PendingIntent.FLAG_IMMUTABLE)
        contentView.setOnClickPendingIntent(R.id.id_app_manager, pendingIntent4)
        expendView.setOnClickPendingIntent(R.id.id_app_manager, pendingIntent4)

        val nfIntent = Intent(context, MainActivity::class.java)
        val pendingIntent =
            PendingIntent.getActivity(context, 0, nfIntent, PendingIntent.FLAG_IMMUTABLE)


        val builder = NotificationCompat.Builder(context, channelId)

        builder.setCustomContentView(contentView)
        builder.setCustomBigContentView(expendView)
        builder.setContentIntent(pendingIntent) //设置PendingIntent
        builder.setSmallIcon(R.mipmap.logo) //设置状态栏内的小图标
        builder.setVisibility(NotificationCompat.VISIBILITY_PRIVATE) //设置通知公开可见
        builder.setOngoing(isOngoing) //设置持续(不消失的常驻通知)
//        builder.setCategory(category) //设置类别
        builder.setAutoCancel(false)
        builder.setPriority(NotificationCompat.PRIORITY_MAX) //优先级为：重要通知

        builder.setWhen(System.currentTimeMillis())
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel =
                NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW)
            channel.lockscreenVisibility = 1
            val notificationManager =
                context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
            builder.setChannelId(channelId)
        }

        val notification = builder.build()

        return notification
    }

    fun sendTimerPush(s: Long) {
        Log.d(TAG, "sendTimerPush")
        val id = NotificationHelper.getPresentPushId()
        val isPush = PushStrategy.isPush(id)
        val log = "isPush=$isPush " + "id=${id} "
        Log.d(TAG, log)
        EventHelper.event("pushCircleOrder_isPush", log)
        if (isPush) {
//            var extra: Int? = null
//            if (id == ID_PHONE_ACCELERATE) {
//                extra = RamMemoryEx.getMemoryUsage(BaseApplication.context).toInt()
//            }
            BaseApplication.context.postActionNotification(id, null, s)
        }
    }

    fun isNotificationExist(context: Context, notificationId: Int): Boolean {
        // 获取 NotificationManagerCompat 实例
        val notificationManager = NotificationManagerCompat.from(context)

        // 获取当前活动的通知列表
        val notifications: MutableList<StatusBarNotification> = notificationManager.activeNotifications

        // 检查指定的通知是否在列表中
        for (notification in notifications) {
            if (notification.id == notificationId) {
                return true
            }
        }
        return false
    }


}
