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.content.ContextCompat
import com.swiftcleaner.chovey.R
import com.swiftcleaner.chovey.model.bean.Global
import com.swiftcleaner.chovey.model.bean.Global.FUNCTION_APP_MANAGER
import com.swiftcleaner.chovey.model.bean.Global.FUNCTION_APP_PROCESS
import com.swiftcleaner.chovey.model.bean.Global.FUNCTION_BATTERY
import com.swiftcleaner.chovey.model.bean.Global.FUNCTION_CLEAN
import com.swiftcleaner.chovey.model.bean.Global.FUNCTION_LARGE_FILE
import com.swiftcleaner.chovey.model.bean.Global.FUNCTION_SCREENSHOT
import com.swiftcleaner.chovey.model.bean.Global.FUNCTION_SIMILAR_PHOTOS
import com.swiftcleaner.chovey.model.bean.Global.FUNCTION_WHATS_APP
import com.swiftcleaner.chovey.model.bean.Global.NotificationInterval
import com.swiftcleaner.chovey.model.bean.Global.NotificationStayCount
import com.swiftcleaner.chovey.model.bean.Global.NotificationStayDelay
import com.swiftcleaner.chovey.model.bean.Global.NotificationStayStatus
import com.swiftcleaner.chovey.view.activity.StartActivity
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.utils.SpUtils
import java.util.Random

object NotificationUtils {

    private val NOTIFICATION_IDS = arrayOf(
        FUNCTION_CLEAN,
        FUNCTION_BATTERY,
        FUNCTION_APP_MANAGER,
        FUNCTION_LARGE_FILE,
        FUNCTION_WHATS_APP,
        FUNCTION_APP_PROCESS,
        FUNCTION_SIMILAR_PHOTOS,
        FUNCTION_SCREENSHOT
    )

    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 notificationid = 1995

    private fun createNotificationChannel(context: Context) {
        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)
    }

    private fun sendNotification(
        context: Context,
        intent: Intent,
        bigRemoteViews: RemoteViews?,
        smallRemoteViews: RemoteViews?,
    ) {


        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("")
            .setContentIntent(pendingIntent)
            .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)

        notificationManager.notify(notificationid, builder.build())
    }


    private var lastNotificationTime = 0L
    fun sendNotification(context: Context, where: String) {
        if (isDeviceLocked || isAppInForeground || !isScreenOn) {
            return
        }
        val actionId = nextNotificationId

        val oneMinute = 1 * 60 * 1000L
        val intervalTime = System.currentTimeMillis() - lastNotificationTime
        val spInterval = SpUtils.getInstance().getInt(NotificationInterval, 1)
        Log.e("sendNotification", "where=$where actionId=$actionId intervalTime=$intervalTime spInterval=$spInterval")
        if (lastNotificationTime != 0L && intervalTime < spInterval * oneMinute) {
            return
        }

        val bigRemoteViews = RemoteViews(context.packageName, R.layout.notification_common)
        val smallRemoteViews = RemoteViews(context.packageName, R.layout.notification_common_small)
        var intentAction = ""
        when (actionId) {
            FUNCTION_CLEAN -> {
                bigRemoteViews.setImageViewResource(R.id.iv_icon, R.mipmap.h_cleanjunk)
                smallRemoteViews.setImageViewResource(R.id.iv_icon, R.mipmap.h_cleanjunk)

                val desc = "Clean out junk files to free up space on your phone!"
                bigRemoteViews.setTextViewText(R.id.tv_desc, desc)
                smallRemoteViews.setTextViewText(R.id.tv_desc, desc)
                intentAction = Global.FUNCTION_CLEAN

            }

            FUNCTION_APP_MANAGER -> {
                bigRemoteViews.setImageViewResource(R.id.iv_icon, R.mipmap.h_appmanager)
                smallRemoteViews.setImageViewResource(R.id.iv_icon, R.mipmap.h_appmanager)

                val desc = "Clean out junk files to free up space on your phone!"
                bigRemoteViews.setTextViewText(R.id.tv_desc, desc)
                smallRemoteViews.setTextViewText(R.id.tv_desc, desc)
                intentAction = Global.FUNCTION_CLEAN
            }

            FUNCTION_BATTERY -> {
                bigRemoteViews.setImageViewResource(R.id.iv_icon, R.mipmap.h_batteryinfo)
                smallRemoteViews.setImageViewResource(R.id.iv_icon, R.mipmap.h_batteryinfo)

                val desc = "Clean out junk files to free up space on your phone!"
                bigRemoteViews.setTextViewText(R.id.tv_desc, desc)
                smallRemoteViews.setTextViewText(R.id.tv_desc, desc)
                intentAction = Global.FUNCTION_CLEAN
            }

            FUNCTION_LARGE_FILE -> {
                bigRemoteViews.setImageViewResource(R.id.iv_icon, R.mipmap.h_large)
                smallRemoteViews.setImageViewResource(R.id.iv_icon, R.mipmap.h_large)

                val desc = "Clean out junk files to free up space on your phone!"
                bigRemoteViews.setTextViewText(R.id.tv_desc, desc)
                smallRemoteViews.setTextViewText(R.id.tv_desc, desc)
                intentAction = Global.FUNCTION_CLEAN
            }

            FUNCTION_WHATS_APP -> {
                bigRemoteViews.setImageViewResource(R.id.iv_icon, R.mipmap.h_whatsapp)
                smallRemoteViews.setImageViewResource(R.id.iv_icon, R.mipmap.h_whatsapp)

                val desc = "Clean out junk files to free up space on your phone!"
                bigRemoteViews.setTextViewText(R.id.tv_desc, desc)
                smallRemoteViews.setTextViewText(R.id.tv_desc, desc)
                intentAction = Global.FUNCTION_CLEAN
            }

            FUNCTION_APP_PROCESS -> {
                bigRemoteViews.setImageViewResource(R.id.iv_icon, R.mipmap.jg__appprocss)
                smallRemoteViews.setImageViewResource(R.id.iv_icon, R.mipmap.jg__appprocss)

                val desc = "Clean out junk files to free up space on your phone!"
                bigRemoteViews.setTextViewText(R.id.tv_desc, desc)
                smallRemoteViews.setTextViewText(R.id.tv_desc, desc)
                intentAction = Global.FUNCTION_CLEAN
            }

            FUNCTION_SIMILAR_PHOTOS -> {
                bigRemoteViews.setImageViewResource(R.id.iv_icon, R.mipmap.h_simiar)
                smallRemoteViews.setImageViewResource(R.id.iv_icon, R.mipmap.h_simiar)

                val desc = "Clean out junk files to free up space on your phone!"
                bigRemoteViews.setTextViewText(R.id.tv_desc, desc)
                smallRemoteViews.setTextViewText(R.id.tv_desc, desc)
                intentAction = Global.FUNCTION_CLEAN
            }

            FUNCTION_SCREENSHOT -> {
                bigRemoteViews.setImageViewResource(R.id.iv_icon, R.mipmap.h_screenshot)
                smallRemoteViews.setImageViewResource(R.id.iv_icon, R.mipmap.h_screenshot)

                val desc = "Clean out junk files to free up space on your phone!"
                bigRemoteViews.setTextViewText(R.id.tv_desc, desc)
                smallRemoteViews.setTextViewText(R.id.tv_desc, desc)
                intentAction = Global.FUNCTION_CLEAN
            }

            else -> {
                return
            }
        }
        val flag = PendingIntent.FLAG_IMMUTABLE
        val btnRequestCode = Random().nextInt(1000)
        val intent = Intent(context, StartActivity::class.java)
        intent.putExtra("actionId", intentAction)
        val btnPendingIntent = PendingIntent.getActivity(context, btnRequestCode, intent, flag)
        bigRemoteViews.setOnClickPendingIntent(R.id.fl_btn, btnPendingIntent)
        smallRemoteViews.setOnClickPendingIntent(R.id.tv_btn, btnPendingIntent)

        val open = SpUtils.getInstance().getInt(NotificationStayStatus, 0)
        if (open == 1) {
            notificationHover(context, intent, bigRemoteViews, smallRemoteViews)
        } else {
            sendNotification(
                context,
                intent,
                bigRemoteViews,
                smallRemoteViews,
            )
            lastNotificationTime = System.currentTimeMillis()
        }
    }

    fun notificationHover(context: Context, intent: Intent, bigRemoteViews: RemoteViews, smallRemoteViews: RemoteViews) {
        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)
                }
            }, time)
        }
    }


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

