package com.base.browserwhite.fcm

import CloseNotificationReceiver
import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Icon
import android.os.Build
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import androidx.core.graphics.drawable.IconCompat
import com.base.browserwhite.MyApplication
import com.base.browserwhite.R
import com.base.browserwhite.bean.ConstObject.ID_CLEAN_JUNK_MEMORY
import com.base.browserwhite.bean.ConstObject.ID_JUNK_CLEANER
import com.base.browserwhite.bean.ConstObject.ID_NEWS
import com.base.browserwhite.bean.NewsBean
import com.base.browserwhite.help.EventUtils
import com.base.browserwhite.help.NewsUtils.getNews
import com.base.browserwhite.ui.activity.cleanjunk.ScanJunkActivity.Companion.fastGetJunkSize
import com.base.browserwhite.ui.activity.splash.Splash2Activity
import com.base.browserwhite.utils.AppPreferences
import com.base.browserwhite.utils.ImageUtils.getBitmapFromURL
import com.base.browserwhite.utils.KotlinExt.toFormatSize
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import kotlin.random.Random


/**
 * 构建发送通知
 * 用的actionId代替notificationId使用
 */
object NotificationUtil {

    private const val CHANNEL_ID = "recovery_notification_id" // 通知渠道ID
    private const val CHANNEL_NAME = "recovery_fcm_channel" // 通知渠道名称

    @SuppressLint("RemoteViewLayout")
    fun sendNotification(context: Context, actionId: Int) {

        when (actionId) {
            ID_JUNK_CLEANER -> {
                var size = fastGetJunkSize(context)
                if (size == 0L) {
                    size = Random.nextLong(1024 * 5, 1024 * 10)
                }
                val bigRemoteViews = RemoteViews(context.packageName, R.layout.notification_junk_big)
                bigRemoteViews.setTextViewText(R.id.tv_size, size.toFormatSize())

                val smallRemoteViews = RemoteViews(context.packageName, R.layout.notification_junk_small)

                sendNotificationUI(context, actionId, bigRemoteViews, smallRemoteViews)
            }

            ID_CLEAN_JUNK_MEMORY -> {
                var size = fastGetJunkSize(context)
                if (size == 0L) {
                    size = Random.nextLong(1024 * 5, 1024 * 10)
                }
                val bigRemoteViews = RemoteViews(context.packageName, R.layout.notification_junk_memory_small)
                bigRemoteViews.setTextViewText(R.id.tv_size, size.toFormatSize())

                val smallRemoteViews = RemoteViews(context.packageName, R.layout.notification_junk_memory_small)
                smallRemoteViews.setTextViewText(R.id.tv_size, size.toFormatSize())

                sendNotificationUI(context, actionId, bigRemoteViews, smallRemoteViews)
            }

            ID_NEWS -> {
                val mainHandler = Handler(Looper.getMainLooper())

                Thread {
                    val news: NewsBean = getNews()?.random() ?: return@Thread
                    val bitmap = getBitmapFromURL(news.orgImgPath) ?: return@Thread

                    mainHandler.post {
                        val bigRemoteViews = RemoteViews(context.packageName, R.layout.notification_big_small)
                        bigRemoteViews.setTextViewText(R.id.tv_head_line, news.headline)
                        bigRemoteViews.setImageViewBitmap(R.id.iv_media, bitmap)

                        val smallRemoteViews = RemoteViews(context.packageName, R.layout.notification_news_small)
                        smallRemoteViews.setTextViewText(R.id.tv_head_line, news.headline)
                        smallRemoteViews.setImageViewBitmap(R.id.iv_media, bitmap)

                        sendNotificationUI(context, actionId, bigRemoteViews, smallRemoteViews)
                    }
                }.start()
            }

            else -> {
            }
        }


    }

    /**
     * UI操作
     */
    private fun sendNotificationUI(context: Context, actionId: Int, bigRemoteViews: RemoteViews, smallRemoteViews: RemoteViews) {
        //跳转
        val intent = Intent(context, Splash2Activity::class.java)
        intent.putExtra("actionId", actionId)
        val btnRequestCode = Random.nextInt(1000)
        val btnPendingIntent = PendingIntent.getActivity(context, btnRequestCode, intent, PendingIntent.FLAG_IMMUTABLE)
        bigRemoteViews.setOnClickPendingIntent(R.id.tv_btn, btnPendingIntent)
        smallRemoteViews.setOnClickPendingIntent(R.id.tv_btn, btnPendingIntent)

        sendCustomNotification(context, actionId, intent, bigRemoteViews, smallRemoteViews)
    }

    private fun cancelNotificationPendingIntent(context: Context, actionId: Int): PendingIntent {
        val cancelIntent = Intent(context, CloseNotificationReceiver::class.java)
        cancelIntent.setAction(CloseNotificationReceiver.Action)
        cancelIntent.putExtra(CloseNotificationReceiver.NotificationId, actionId)
        val broadcastRequestCode = Random.nextInt(1000)
        return PendingIntent.getBroadcast(context, broadcastRequestCode, cancelIntent, PendingIntent.FLAG_IMMUTABLE)
    }


    private fun sendCustomNotification(
        context: Context,
        actionId: Int,
        intent: Intent,
        bigRemoteViews: RemoteViews,
        smallRemoteViews: RemoteViews
    ) {

        val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        //创建channel
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                CHANNEL_NAME,
                NotificationManager.IMPORTANCE_HIGH
            )
            channel.lockscreenVisibility = NotificationCompat.VISIBILITY_PUBLIC
            notificationManager.createNotificationChannel(channel)
        }


        // Create the notification
        val builder: NotificationCompat.Builder = NotificationCompat.Builder(context, CHANNEL_ID)

        //设置状态栏内的小图标
        val smallIcon = IconCompat.createFromIcon(
            context, Icon.createWithResource(
                context, R.mipmap.logo_notification_small
            )
        )
        smallIcon?.let {
            builder.setSmallIcon(smallIcon)
        }
        builder.setContentTitle(context.resources.getString(R.string.app_name))
            .setContentText("notification")

        val requestCode = Random.nextInt(1000)
        val pendingIntent = PendingIntent.getActivity(context, requestCode, intent, PendingIntent.FLAG_IMMUTABLE)
        builder.setContentIntent(pendingIntent)
            .setDeleteIntent(cancelNotificationPendingIntent(context, actionId))
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setAutoCancel(true)


        var small: RemoteViews? = 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)

        // Show the notification
        if (AppPreferences.getInstance().getString("actionS", "1").toInt() == 1) {
            notificationManager.notify(intent.getIntExtra("actionId", actionId), builder.build())
        } else {
            notificationManager.notify(actionId, builder.build())
        }
        AppPreferences.getInstance().put("last_notification_time", System.currentTimeMillis())
    }


    private var handlerThread: HandlerThread? = null
    private var handler: Handler? = null

    private fun getCurrentDate(): String {
        val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        val currentDate = Calendar.getInstance().time
        return dateFormat.format(currentDate)
    }

    fun sendNotification(context: Context, where: String = "") {
        val actionId: Int = getNextNotificationId()

        if (MyApplication.PAUSED_VALUE == 1) {
            return
        }
        val maxShowNotificationCount = AppPreferences.getInstance().getString("maxShowNotificationCount", "200").toInt()
        val todayShowCount = AppPreferences.getInstance().getInt("notificationCount_${getCurrentDate()}", 0)
        if (todayShowCount >= maxShowNotificationCount) {
            return
        }

        val interval: Int = AppPreferences.getInstance().getString("notificationInterval", "60").toIntOrNull() ?: 60
        val lastTime: Long = AppPreferences.getInstance().getLong("last_notification_time", 0)
        val nowTime = System.currentTimeMillis()
        val x = nowTime - lastTime
        if (x < (interval * 1000)) {
            return
        }

        sendNotification(context, actionId)
        EventUtils.event("showNotification", where, null, false)

        AppPreferences.getInstance().putInt("notificationCount_${getCurrentDate()}", todayShowCount + 1)

        val open: Int = AppPreferences.getInstance().getString("open", "0").toIntOrNull() ?: 0

        if (open == 1) {
            val num: Int = AppPreferences.getInstance().getString("num", "0").toIntOrNull() ?: 0
            val delay: Long = AppPreferences.getInstance().getString("delay", "0").toLongOrNull() ?: 0L
            handlerThread = HandlerThread("NotificationHandlerThread")
            handlerThread?.start()

            // 创建 Handler
            handler = Handler(handlerThread!!.looper)
            for (i in 1..num) {
                val time = i * delay
                handler?.postDelayed(Runnable {

                    if (MyApplication.PAUSED_VALUE != 1
                        && ScreenStatusReceiver.isDeviceInteractive()
                        && !ScreenStatusReceiver.isSecureLockActive()
                    ) {
                        sendNotification(context, actionId)
                    }

                    if (MyApplication.PAUSED_VALUE == 1) {
                        if (handler != null) {
                            handler?.removeCallbacksAndMessages(null)
                        }
                        return@Runnable
                    }
                }, time)
            }
        }
    }


    fun stopNotificationHandler() {
        // 停止 HandlerThread
        if (handler != null) {
            handler?.removeCallbacksAndMessages(null)
        }
        if (handlerThread != null) {
            handlerThread?.quit()
            handlerThread = null
        }
        handler = null
    }

    private var currentNotificationIdIndex = -1

    private fun getNextNotificationId(): Int {
        // 将当前通知 ID 索引加 1
        currentNotificationIdIndex++

        // 如果当前通知 ID 索引超出列表范围，则将其重置为 0
        if (currentNotificationIdIndex >= NOTIFICATION_IDS.size) {
            currentNotificationIdIndex = 0
        }

        // 返回下一个通知 ID
        return NOTIFICATION_IDS[currentNotificationIdIndex]
    }

    private val NOTIFICATION_IDS = intArrayOf(
        0
    )
}