package com.swiftcleaner.chovey.business.push

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.os.Build
import android.os.Handler
import android.os.HandlerThread
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import com.tool.elite.battery.business.push.BadgeUtils
import com.swiftcleaner.chovey.CleanApplication
import com.swiftcleaner.chovey.GlobalConfig.ID_APPMANAGER
import com.swiftcleaner.chovey.GlobalConfig.ID_APP_PROCESS
import com.swiftcleaner.chovey.GlobalConfig.ID_BATTERY_INFO
import com.swiftcleaner.chovey.GlobalConfig.ID_CLEAN_JUNK
import com.swiftcleaner.chovey.GlobalConfig.ID_LARGE_FILE_CLEANER

import com.swiftcleaner.chovey.GlobalConfig.ID_SCREENSHOT_CLEAN
import com.swiftcleaner.chovey.GlobalConfig.ID_SIMILAR_PHOTOS
import com.swiftcleaner.chovey.GlobalConfig.ID_WHATSAPP
import com.swiftcleaner.chovey.GlobalConfig.ID_WHEATHER
import com.swiftcleaner.chovey.GlobalConfig.ID_XINGZUO
import com.swiftcleaner.chovey.GlobalConfig.KEY_NOTIFICATION_ID
import com.swiftcleaner.chovey.R
import com.swiftcleaner.chovey.business.EventUtils
import com.swiftcleaner.chovey.util.SPUtils
import com.swiftcleaner.chovey.util.Utils.toDate
import com.swiftcleaner.chovey.view.activity.StartActivity
import com.swiftcleaner.chovey.view.function.constellation.XingzuoStringManager
import com.swiftcleaner.chovey.view.function.weather.TimeUtils.formatATime
import com.swiftcleaner.chovey.view.function.weather.TimeUtils.isDayOrNight
import com.swiftcleaner.chovey.view.function.weather.WeatherBean
import com.swiftcleaner.chovey.view.function.weather.WeatherUtils
import kotlin.random.Random

object NotificationUtils {

    private const val CHANNEL_ID = "notification_id" // 通知渠道ID
    private const val CHANNEL_NAME = "fcm_channel" // 通知渠道名称
    private const val NOTIFICATION_CURRENT = "notification_current"

    private val notificationIds = intArrayOf(
        ID_CLEAN_JUNK,
        ID_APPMANAGER,
        ID_WHATSAPP,
        ID_BATTERY_INFO,
        ID_LARGE_FILE_CLEANER,
        ID_SIMILAR_PHOTOS,
        ID_APP_PROCESS,
        ID_SCREENSHOT_CLEAN,
        ID_XINGZUO,
        ID_WHEATHER
    )

    private var currentNotificationId = -1
    private val nextNotificationId: Int
        get() {
            currentNotificationId = (currentNotificationId + 1) % notificationIds.size
            return notificationIds[currentNotificationId]
        }

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

    fun sendNotification(context: Context, type: String) {
        val id = nextNotificationId
        sendNotification(context, id, type)
    }

    @SuppressLint("RemoteViewLayout")
    fun sendNotification(context: Context, id: Int, type: String) {
        if (id == ID_XINGZUO) {
            //val icon = R.mipmap.xingzuoicon

            val desc = XingzuoStringManager.getNextDesc()
            val btn = XingzuoStringManager.getNextTitle()
            val smallRemoteViewsVar =
                RemoteViews(context.packageName, R.layout.notify_layout_xingzuo_small)
            smallRemoteViewsVar.setTextViewText(R.id.tv_desc, btn)
            smallRemoteViewsVar.setTextViewText(R.id.tv_btn, desc)
            val bigRemoteViewsVar =
                RemoteViews(context.packageName, R.layout.notify_layout_xingzuo_big)
            bigRemoteViewsVar.setTextViewText(R.id.id_title, btn)
            bigRemoteViewsVar.setTextViewText(R.id.tv_desc, desc)
//            sendCustomNotification(context, actionId, intent, bigRemoteViewsVar, smallRemoteViewsVar)
            sendNotification(
                context,
                btn,
                getLaunchIntent(context, id),
                smallRemoteViewsVar,
                bigRemoteViewsVar,
                id,
                type
            )
            return
        }
        if (id == ID_WHEATHER) {
            val weatherBean: WeatherBean = WeatherUtils.getWeatherEntity() ?: return
            if (weatherBean.list.isEmpty()) return
            val subBean = weatherBean.list[0]
            val smallRemoteViewsVar =
                RemoteViews(context.packageName, R.layout.notification_weather_small)
            smallRemoteViewsVar.setTextViewText(R.id.tv_city, weatherBean.city)
            val min = subBean.tempMin.toInt()
            val max = subBean.tempMax.toInt()
            smallRemoteViewsVar.setTextViewText(
                R.id.tv_wendu_now,
                kotlin.random.Random.nextInt(min, max).toString()
            )
            val icon = when (WeatherUtils.getWeatherType(subBean.iconDay.toInt())) {
                "Sunny day" -> R.mipmap.d_qing
                "Cloudy day" -> R.mipmap.d_yin
                "Rainy day" -> R.mipmap.d_dayu
                "Snowy day" -> R.mipmap.d_xiaxue
                "Greasy day" -> R.mipmap.d_wumaishachengbao
                "Unknown" -> R.mipmap.d_qing
                else -> R.mipmap.d_qing
            }

            var xiaoIcon = 0
            var imageBg = 0
            when (WeatherUtils.getWeatherType(subBean.iconDay.toInt())) {
                "Sunny day" -> {
                    xiaoIcon = R.mipmap.xiaoqing1
                    imageBg = R.mipmap.qingtian_bg
                }

                "Cloudy day" -> {
                    xiaoIcon = R.mipmap.xiaoyinyu1
                    imageBg = R.mipmap.yintian_bg
                }

                "Rainy day" -> {
                    xiaoIcon = R.mipmap.xiaoyinyu1
                    imageBg = R.mipmap.yutian_bg
                }

                "Snowy day" -> {
                    xiaoIcon = R.mipmap.xiaoxuetian1
                    imageBg = R.mipmap.xuetian
                }

                "Greasy day" -> {
                    xiaoIcon = R.mipmap.xiaoshachenbao1
                    imageBg = R.mipmap.shachenbao
                }

                "Unknown" -> {
                    xiaoIcon = R.mipmap.xiaoyinyu1
                    imageBg = R.mipmap.yintian_bg
                }

                else -> {
                    xiaoIcon = R.mipmap.xiaoyinyu1
                    imageBg = R.mipmap.yintian_bg
                }
            }
            smallRemoteViewsVar.setImageViewResource(R.id.weather_bg, xiaoIcon)
            smallRemoteViewsVar.setImageViewResource(R.id.iv_weather, icon)
            smallRemoteViewsVar.setTextViewText(R.id.tv_wendu_range, "$min℃/$max℃")
            val bigRemoteViewsVar =
                RemoteViews(context.packageName, R.layout.notification_weather_big)
            bigRemoteViewsVar.setImageViewResource(R.id.iv_weather, icon)
            bigRemoteViewsVar.setImageViewResource(R.id.big_bg, imageBg)
            bigRemoteViewsVar.setTextViewText(
                R.id.tv_wendu_now,
                kotlin.random.Random.nextInt(min, max).toString()
            )
            bigRemoteViewsVar.setTextViewText(
                R.id.tv_day_desc,
                if (isDayOrNight()) subBean.textDay else subBean.textNight
            )
            bigRemoteViewsVar.setTextViewText(
                R.id.tv_weather_info,
                "$min℃/$max℃ ${formatATime()}"
            )

            sendNotification(
                context,
                "Weather",
                getLaunchIntent(context, id),
                smallRemoteViewsVar,
                bigRemoteViewsVar,
                id,
                type
            )
            return
        }

        val (iconRes, contentRes) = getNotificationDetails(id)
        if (iconRes == 0 || contentRes == 0) return

        val notificationLayout = getNotificationLayout(context, iconRes, contentRes)
        val notificationLayoutExpanded = getExpandedNotificationLayout(context, iconRes, contentRes)
        val content = context.getString(contentRes)
        sendNotification(
            context,
            content,
            getLaunchIntent(context, id),
            notificationLayout,
            notificationLayoutExpanded,
            id,
            type
        )
    }

    fun sendBatteryNotification(context: Context, battery: Int, isCharging: Boolean, type: String) {
//        val state = if (isCharging) 1 else 0
//        val icon: Int
//        val status: String
//        val statusLarge: String
//        val color: Int
//        when (state) {
//            0 -> {
//                icon = R.mipmap.icon_battery_red
//                status = context.getString(R.string.low_lower)
//                statusLarge = context.getString(R.string.low)
//                color = context.getColor(R.color.color_ff6651)
//            }
//            1 -> {
//                icon = R.mipmap.icon_battery_green
//                status = context.getString(R.string.charging_lower)
//                statusLarge = context.getString(R.string.charging)
//                color = context.getColor(R.color.color_27d07e)
//            }
//            else -> return
//        }
//        val notificationLayout = RemoteViews(context.packageName, R.layout.notification_battery_small)
//        val notificationLayoutExpanded = RemoteViews(context.packageName, R.layout.notification_battery_large)
//        notificationLayout.setImageViewResource(R.id.iv_image, icon)
//        notificationLayout.setTextViewText(R.id.tv_battery_power, "${battery}%")
//        notificationLayout.setTextViewText(R.id.tv_battery_status, status)
//        notificationLayout.setTextColor(R.id.tv_battery_power, color)
//        notificationLayout.setTextColor(R.id.tv_battery_status, color)
//        notificationLayoutExpanded.setImageViewResource(R.id.iv_image, icon)
//        notificationLayoutExpanded.setTextViewText(R.id.tv_battery_power, "${battery}%")
//        notificationLayoutExpanded.setTextViewText(R.id.tv_battery_status, statusLarge)
//        notificationLayoutExpanded.setTextColor(R.id.tv_battery_status, color)
//        notificationLayoutExpanded.setTextColor(R.id.tv_battery_power, color)
//        sendNotification(context, statusLarge, getLaunchIntent(context, ID_BATTERY_LEVEL), notificationLayout, notificationLayoutExpanded, ID_BATTERY_LEVEL, type)
    }

    private fun getNotificationDetails(id: Int): Pair<Int, Int> {
        return when (id) {
            ID_CLEAN_JUNK -> Pair(R.mipmap.h_cleanjunk, R.string.notification_clean)
            ID_WHATSAPP -> Pair(R.mipmap.h_whatsapp, R.string.notification_whatsapp)
            ID_BATTERY_INFO -> Pair(R.mipmap.h_batteryinfo, R.string.notification_battery)
            ID_APPMANAGER -> Pair(R.mipmap.h_appmanager, R.string.notification_manager)
            ID_LARGE_FILE_CLEANER -> Pair(R.mipmap.h_large, R.string.notification_large_file)
            ID_APP_PROCESS -> Pair(R.mipmap.jg__appprocss, R.string.notification_app_process)
            ID_SIMILAR_PHOTOS -> Pair(R.mipmap.h_simiar, R.string.notification_similar_photos)
            ID_SCREENSHOT_CLEAN -> Pair(R.mipmap.h_screenshot, R.string.notification_screenshot)

            else -> Pair(0, 0)
        }
    }

    private fun getNotificationLayout(
        context: Context,
        iconRes: Int,
        contentRes: Int
    ): RemoteViews {
        return RemoteViews(context.packageName, R.layout.notification_common_small).apply {
            setImageViewResource(R.id.iv_icon, iconRes)
            setTextViewText(R.id.tv_desc, context.getString(contentRes))
        }
    }

    private fun getExpandedNotificationLayout(
        context: Context,
        iconRes: Int,
        contentRes: Int
    ): RemoteViews {
        return RemoteViews(context.packageName, R.layout.notification_common).apply {
            setImageViewResource(R.id.iv_icon, iconRes)
            setTextViewText(R.id.tv_desc, context.getString(contentRes))
        }
    }

    private fun getLaunchIntent(context: Context, id: Int): PendingIntent {
        val intent = Intent(context, StartActivity::class.java)
        intent.putExtra(KEY_NOTIFICATION_ID, id)
        return PendingIntent.getActivity(
            context,
            Random.Default.nextInt(3000),
            intent,
            PendingIntent.FLAG_IMMUTABLE
        )
    }

    private fun sendNotification(
        context: Context,
        title: String,
        intent: PendingIntent,
        smallRemoteView: RemoteViews,
        largeRemoteView: RemoteViews,
        notifyId: Int,
        type: String,
    ) {
//        if (CleanApplication.APP_STATE == 1) return

        val key = "${NOTIFICATION_CURRENT}_${context.toDate()}"
        val notificationCount = SPUtils.getInstance().getInt("notificationCount", 100)
        val current = SPUtils.getInstance().getInt(key)
        if (current >= notificationCount) {
            return
        }
        SPUtils.getInstance().putInt(key, current + 1)
        if (type.isNotEmpty())
            EventUtils.event("showNotification", value = type)

//        if (context.packageName != PACKAGE_NAME) {
//            smallRemoteView.setTextViewText(R.id.tv_mark, type)
//            largeRemoteView.setTextViewText(R.id.tv_mark, type)
//        }
        sendCustomNotification(
            context,
            title,
            intent,
            smallRemoteView,
            largeRemoteView,
            notifyId,
            type
        )
        setSuspensionRetention(
            context,
            title,
            intent,
            smallRemoteView,
            largeRemoteView,
            notifyId,
            type
        )
    }

    private fun sendCustomNotification(
        context: Context,
        title: String,
        intent: PendingIntent,
        smallRemoteView: RemoteViews,
        largeRemoteView: RemoteViews,
        notifyId: Int,
        type: String,
    ) {
        val deleteIntent = Intent(context, NotificationCancelReceiver::class.java)
        deleteIntent.putExtra(KEY_NOTIFICATION_ID, notifyId)
        val deletePendingIntent = PendingIntent.getBroadcast(
            context,
            Random.Default.nextInt(3000),
            deleteIntent,
            PendingIntent.FLAG_MUTABLE
        )

        val builder = NotificationCompat.Builder(context, CHANNEL_ID)
            .setSmallIcon(R.drawable.frame)
            .setVibrate(longArrayOf(0)) // 禁止震动
            .setSound(null) // 禁止声音
            .setContentTitle(title)
            .setContentIntent(intent)
            .setDeleteIntent(deletePendingIntent)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setAutoCancel(true)

        var content = largeRemoteView

        // Android 12以下需要适配小RemoteViews
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            content = smallRemoteView
        }
        builder.setContent(content)
        builder.setCustomHeadsUpContentView(content)
        builder.setCustomContentView(content)
        builder.setCustomBigContentView(largeRemoteView)

        val notificationManager =
            context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel =
                NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH)
            channel.lockscreenVisibility = NotificationCompat.VISIBILITY_PUBLIC
            channel.setShowBadge(true)
            notificationManager.createNotificationChannel(channel)
        }
        if (type.startsWith("fcm", true)) {
            val num = Random.nextInt(1, 10)
            val notification = builder.setNumber(num).build()
            notificationManager.notify(notifyId, notification)
            BadgeUtils.setBadgeNum(context, num, notification)
        } else {
            notificationManager.notify(notifyId, builder.build())
        }
    }

    fun setSuspensionRetention(
        context: Context,
        title: String,
        intent: PendingIntent,
        smallRemoteView: RemoteViews,
        largeRemoteView: RemoteViews,
        notifyId: Int,
        type: String,
    ) {
        val open = SPUtils.getInstance().getInt("NotificationStayStatus")
        if (open == 1) {
            val num = SPUtils.getInstance().getInt("NotificationStayCount")
            val delay = SPUtils.getInstance().getInt("NotificationStayDelay")
            handlerThread = HandlerThread("NotificationHandlerThread")
            handlerThread?.let {
                it.start()
                handler = Handler(it.getLooper())
            }

            for (i in 1..num) {
                val time = i * delay.toLong()
                // 使用 handler.postDelayed
                handler?.postDelayed({
                    if (CleanApplication.APP_STATE == 1) {
                        handler?.removeCallbacksAndMessages(null)
                    } else {
                        sendCustomNotification(
                            context,
                            title,
                            intent,
                            smallRemoteView,
                            largeRemoteView,
                            notifyId,
                            type
                        )
                    }
                }, time)
            }
        }
    }

    @JvmStatic
    fun stopNotificationHandler() {
        handler?.removeCallbacksAndMessages(null)
        handlerThread?.quit()
        handlerThread = null
        handler = null
    }
}