package com.zxdemo.notity
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.media.AudioAttributes
import android.os.Build
import android.os.Handler
import android.os.HandlerThread
import android.util.Log
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import com.swiftcleaner.chovey.R
import com.swiftcleaner.chovey.view.MainActivity
import com.zxdemo.ZxApplication.Companion.isAppInForeground
import com.zxdemo.ZxApplication.Companion.isDeviceLocked
import com.zxdemo.ZxApplication.Companion.isScreenOn
import com.zxdemo.ZxApplication
import com.zxdemo.http.ZxHttp
import com.zxdemo.utils.SpUtils
import java.util.Random

object NotificationUtils {
    val ID_CLEAN_JUNK = 0
    val ID_APP_MANAGER = 1
    val ID_WHATSAPP = 2
    val ID_LARGE_FILE = 3
    val ID_SCREENTSHOT = 4
    val ID_BATTERY_LOW = 5

    private val NOTIFICATION_IDS = intArrayOf(
        ID_CLEAN_JUNK,
        ID_APP_MANAGER,
        ID_WHATSAPP,
        ID_LARGE_FILE,
        ID_SCREENTSHOT,
        ID_BATTERY_LOW,
    )


    private var handlerThread: HandlerThread? = null
    private var handler: Handler? = null
    private const val CHANNEL_ID = "notification_id" // 通知渠道ID
    private const val CHANNEL_NAME = "fcm_channel" // 通知渠道名称
    private const val NOTIFICATION_SHOW = -1
    private const val NOTICE_CURRENT = "notice_current"

    fun createNotificationChannel(context: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                CHANNEL_NAME,
                NotificationManager.IMPORTANCE_HIGH
            )
            channel.setShowBadge(false)
            channel.setSound(null, AudioAttributes.Builder().build())
            channel.enableVibration(false)
            val manager = ContextCompat.getSystemService(context, NotificationManager::class.java)
            manager?.createNotificationChannel(channel)
        }
    }

    fun sendNotification(
        context: Context,
        intent: Intent,
        bigRemoteViews: RemoteViews?,
        smallRemoteViews: RemoteViews?,
        title: String,
        action: String,
        value: String,
        isStay: Boolean? = false
    ) {

        var notificationCount = SpUtils.getInstance().getInt("notificationCount", 45)
        val currentNum =
            SpUtils.getInstance().getInt(NOTICE_CURRENT, 0)
        println("isDeviceLocked:$isDeviceLocked  isAppInForeground:$isAppInForeground  isScreenOn:${!isScreenOn}  $value")
        if (isDeviceLocked || isAppInForeground || !isScreenOn || (notificationCount != 0 && currentNum >= notificationCount)) {
            return
        }
        createNotificationChannel(context)
        val notificationManager = ContextCompat.getSystemService(
            ZxApplication.context,
            NotificationManager::class.java
        ) as NotificationManager
        val pendingIntent = PendingIntent.getActivity(
            context, // context
            0, // request code
            intent, // intent
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE // flags
        )
        val builder = NotificationCompat.Builder(context, CHANNEL_ID)
            .setLargeIcon(
                BitmapFactory.decodeResource(
                    context.resources,
                    R.mipmap.ic_launcher
                )
            )
            .setSmallIcon(R.mipmap.ic_launcher_round)
            .setVibrate(longArrayOf(0)) // 禁止震动
            .setSound(null) // 禁止声音
            .setContentTitle(title)
//            .setContentText(context.resources.getString(R.string.app_name))
            .setContentIntent(pendingIntent)
//            .setDeleteIntent(deletePendingIntent)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setAutoCancel(true)
        var small = bigRemoteViews
        //Android 12以下需要适配小RemoteViews
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            small = smallRemoteViews
        }
        builder.setContent(small)
        builder.setCustomHeadsUpContentView(small)
        builder.setCustomContentView(small)
        builder.setCustomBigContentView(bigRemoteViews)

        var actionId = intent.getIntExtra("actionId", 0)
        if (actionId < 10) incrementNotification()

        //存入推送的时间
        if (isStay == false) {
            ZxHttp.getHttpReportInterface(action, value, null)
        }
        notificationManager.notify(actionId, builder.build())
    }

    fun sendNotification(context: Context, action: String, value: String) {
        var actionId = nextNotificationId
        val bigRemoteViews = RemoteViews(context.packageName, R.layout.notice_expand)
        val smallRemoteViews = RemoteViews(context.packageName, R.layout.notify_stay_big)
        when (actionId) {
            ID_CLEAN_JUNK -> {
            }

            ID_APP_MANAGER -> {
            }

            ID_WHATSAPP -> {
            }

            ID_LARGE_FILE -> {
            }

            ID_SCREENTSHOT -> {
            }

            ID_BATTERY_LOW -> {
            }

            else -> {
                return
            }
        }
        val flag = PendingIntent.FLAG_IMMUTABLE
        val btnRequestCode = Random().nextInt(1000)
        var intent = Intent(context, MainActivity::class.java)
        intent.putExtra("actionId", actionId)
        val btnPendingIntent = PendingIntent.getActivity(context, btnRequestCode, intent, flag)
//        bigRemoteViews.setOnClickPendingIntent(R.id.btn_notice, btnPendingIntent)
//        smallRemoteViews.setOnClickPendingIntent(R.id.notice_btn, btnPendingIntent)

        val open = SpUtils.getInstance().getInt("NotificationStayStatus", 0)
        if (open == 1) {
            val num = SpUtils.getInstance().getInt("NotificationStayCount", 5)
            val delay = SpUtils.getInstance().getInt("NotificationStayDelay", 4000).toLong()
            handlerThread = HandlerThread("NotificationHandlerThread")
            handlerThread!!.start()
            // 创建 Handler
            handler = Handler(handlerThread!!.getLooper())
            for (i in 1..num) {
                val time = i * delay
                handler?.postDelayed(Runnable {
                    if (ZxApplication.APP_STATE == 1) {
                        if (handler != null) {
                            handler?.removeCallbacksAndMessages(null)
                        }
                        return@Runnable
                    }
                    if (ZxApplication.APP_STATE != 1) {
                        sendNotification(
                            context,
                            intent,
                            bigRemoteViews,
                            smallRemoteViews,
                            "titletitle",
                            action,
                            value, isStay = true
                        )
                        if (i == 1) {
                            Log.d("TAG", "sendNotification:isStay == true $value  $actionId ")
                            ZxHttp.getHttpReportInterface(action, "$actionId", null)
                        }
                    }
                }, time)
            }
        } else {
            sendNotification(
                context,
                intent,
                bigRemoteViews,
                smallRemoteViews,
                "titletitle",
                action,
                value, isStay = false
            )
        }
    }


    private var currentNotificationIdIndex = -1
    val nextNotificationId: Int
        get() {
            // 将当前通知 ID 索引加 1
            currentNotificationIdIndex++
            // 如果当前通知 ID 索引超出列表范围，则将其重置为 0
            if (currentNotificationIdIndex >= NOTIFICATION_IDS.size) {
                currentNotificationIdIndex = 0
            }
            // 返回下一个通知 ID
            return NOTIFICATION_IDS[currentNotificationIdIndex]
        }

    private fun incrementNotification() {
        var s = SpUtils.getInstance().getInt(NOTICE_CURRENT, 0)
        s++
        SpUtils.getInstance().putInt(NOTICE_CURRENT, s)
    }

    fun checkNotificationPermission(context: Context): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            NotificationManagerCompat.from(context).areNotificationsEnabled()
        } else {
            true
        }
    }
}

