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.Bitmap
import android.graphics.drawable.Icon
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import androidx.core.graphics.drawable.IconCompat
import androidx.core.graphics.drawable.toBitmap
import com.base.browserwhite.MyApplication
import com.base.browserwhite.R
import com.base.browserwhite.bean.ConstObject.ID_APP_PROCESS_1
import com.base.browserwhite.bean.ConstObject.ID_APP_PROCESS_2
import com.base.browserwhite.bean.ConstObject.ID_CONSTELLATION
import com.base.browserwhite.bean.ConstObject.ID_INSTALL_APP
import com.base.browserwhite.bean.ConstObject.ID_JUNK_CLEANER
import com.base.browserwhite.bean.ConstObject.ID_NEWS
import com.base.browserwhite.bean.ConstObject.ID_UNINSTALL_APP
import com.base.browserwhite.bean.ConstObject.ID_USAGE_REPORT
import com.base.browserwhite.bean.ConstObject.ID_WEATHER
import com.base.browserwhite.bean.NewsBean
import com.base.browserwhite.bean.WeatherBean
import com.base.browserwhite.help.NewsUtils.getNewSp
import com.base.browserwhite.help.WeatherUtils
import com.base.browserwhite.ui.activity.appprocess.AppProcessActivity
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 com.base.browserwhite.utils.KotlinExt.toFormatTime
import com.base.browserwhite.utils.LogEx
import com.base.browserwhite.utils.RamUtils.ramPair
import com.base.browserwhite.utils.TimeUtils.formatATime
import com.base.browserwhite.utils.TimeUtils.isDayOrNight
import kotlin.random.Random


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

    private val TAG = "NotificationUiUtil"
    private const val CHANNEL_ID = "browser_notification_id" // 通知渠道ID
    private const val CHANNEL_NAME = "browser_fcm_channel" // 通知渠道名称

    @SuppressLint("RemoteViewLayout")
    fun sendNotification(context: Context, actionId: Int) {
        when (actionId) {
            //安装
            ID_INSTALL_APP -> {
                val smallRemoteViews = RemoteViews(context.packageName, R.layout.notification_un_install_small)
                smallRemoteViews.setTextViewText(R.id.tv_tittle_1, "Clean up useless installation packages")
                smallRemoteViews.setTextViewText(R.id.tv_tittle_2, "App installation successful")


                val bigRemoteViews = RemoteViews(context.packageName, R.layout.notification_un_install_big)
                bigRemoteViews.setTextViewText(R.id.tv_tittle_1, "Clean up useless installation packages")
                bigRemoteViews.setTextViewText(R.id.tv_tittle_2, "App installation successful")

                sendNotificationUI(context, actionId, bigRemoteViews, smallRemoteViews)
            }
            //卸载
            ID_UNINSTALL_APP -> {
                val smallRemoteViews = RemoteViews(context.packageName, R.layout.notification_un_install_small)
                smallRemoteViews.setTextViewText(R.id.tv_tittle_1, "Clean up residual files")
                smallRemoteViews.setViewVisibility(R.id.tv_tittle_2, View.GONE)

                val bigRemoteViews = RemoteViews(context.packageName, R.layout.notification_un_install_big)
                bigRemoteViews.setTextViewText(R.id.tv_tittle_1, "Clean up residual files")
                bigRemoteViews.setTextViewText(R.id.tv_tittle_2, "Uninstalling successful")

                sendNotificationUI(context, actionId, bigRemoteViews, smallRemoteViews)
            }

            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)
                smallRemoteViews.setTextViewText(R.id.tv_size, size.toFormatSize())

                sendNotificationUI(context, actionId, bigRemoteViews, smallRemoteViews)
            }

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

                Thread {
                    val list: List<NewsBean> = getNewSp()
                    if (list.isEmpty()) {
                        LogEx.logDebug(TAG, "NewsBean list==null")
                        return@Thread
                    }

                    val news = list.random()
                    val bitmap = getBitmapFromURL(news.orgImgPath)
                    if (bitmap == null) {
                        LogEx.logDebug(TAG, "bitmap==null")
                    }

                    mainHandler.post {
                        val bigRemoteViews = RemoteViews(context.packageName, R.layout.notification_news_big)
                        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()
            }

            ID_APP_PROCESS_1 -> {//内存样式一
                val pair = MyApplication.context.ramPair()
                val percent = (pair.first * 100 / pair.second).toInt()

                val desc = "Memory is $percent% used"
                val smallRemoteViews = RemoteViews(context.packageName, R.layout.notification_memory_small_1)
                smallRemoteViews.setProgressBar(R.id.progress_bar, percent, 100, false)
                smallRemoteViews.setTextViewText(R.id.tv_desc, desc)

                val bigRemoteViews = RemoteViews(context.packageName, R.layout.notification_memory_big)

                sendNotificationUI(context, actionId, bigRemoteViews, smallRemoteViews)
            }

            ID_APP_PROCESS_2 -> {//内存样式二
                val smallRemoteViews = RemoteViews(context.packageName, R.layout.notification_memory_small_2)
                val bigRemoteViews = RemoteViews(context.packageName, R.layout.notification_memory_big)
                sendNotificationUI(context, actionId, bigRemoteViews, smallRemoteViews)
            }

            ID_WEATHER -> {//天气

                val weatherBean: WeatherBean = WeatherUtils.getWeatherEntity() ?: return
                if (weatherBean.list.isEmpty()) return

                val subBean = weatherBean.list[0]
                val smallRemoteViews = RemoteViews(context.packageName, R.layout.notification_weather_small)
                smallRemoteViews.setTextViewText(R.id.tv_city, weatherBean.city)
                val min = subBean.tempMin.toInt()
                val max = subBean.tempMax.toInt()
                smallRemoteViews.setTextViewText(R.id.tv_wendu_now, 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
                }

                smallRemoteViews.setImageViewResource(R.id.iv_weather, icon)
                smallRemoteViews.setTextViewText(R.id.tv_wendu_range, "$min℃/$max℃")

                val bigRemoteViews = RemoteViews(context.packageName, R.layout.notification_weather_big)
                bigRemoteViews.setImageViewResource(R.id.iv_weather_11h, icon)
                bigRemoteViews.setImageViewResource(R.id.iv_weather_14h, icon)
                bigRemoteViews.setImageViewResource(R.id.iv_weather_17h, icon)
                bigRemoteViews.setImageViewResource(R.id.iv_weather_20h, icon)
                bigRemoteViews.setImageViewResource(R.id.iv_weather_23h, icon)
                bigRemoteViews.setImageViewResource(R.id.iv_weather, icon)

                bigRemoteViews.setTextViewText(R.id.tv_wendu_11h, Random.nextInt(min, max).toString())
                bigRemoteViews.setTextViewText(R.id.tv_wendu_14h, Random.nextInt(min, max).toString())
                bigRemoteViews.setTextViewText(R.id.tv_wendu_17h, Random.nextInt(min, max).toString())
                bigRemoteViews.setTextViewText(R.id.tv_wendu_20h, Random.nextInt(min, max).toString())
                bigRemoteViews.setTextViewText(R.id.tv_wendu_23h, Random.nextInt(min, max).toString())

                bigRemoteViews.setTextViewText(R.id.tv_wendu_now, Random.nextInt(min, max).toString())
                bigRemoteViews.setTextViewText(R.id.tv_day_desc, if (isDayOrNight()) subBean.textDay else subBean.textNight)
                bigRemoteViews.setTextViewText(R.id.tv_weather_info, "$min℃/$max℃ ${formatATime()}")
                sendNotificationUI(context, actionId, bigRemoteViews, smallRemoteViews)
            }

            ID_CONSTELLATION -> {//星座
                val smallRemoteViews = RemoteViews(context.packageName, R.layout.notification_constellation_small)
                val bigRemoteViews = RemoteViews(context.packageName, R.layout.notification_constellation_big)

                sendNotificationUI(context, actionId, bigRemoteViews, smallRemoteViews)

            }

            ID_USAGE_REPORT -> {//使用报告
                val smallRemoteViews = RemoteViews(context.packageName, R.layout.notification_usage_report_small)
                smallRemoteViews.setTextViewText(R.id.tv_tittle_1, "${System.currentTimeMillis().toFormatTime()} Usage Report")

                val bigRemoteViews = RemoteViews(context.packageName, R.layout.notification_usage_report_big)
                val pm = context.packageManager
                val apps = AppProcessActivity.fastGetAppIcon(context)
                LogEx.logDebug("ID_USAGE_REPORT", "${apps.size}")

                val size = context.resources.getDimensionPixelSize(R.dimen.dp_30)
                runCatching {
                    val app1 = apps[0]
                    val drawable1 = app1.applicationInfo.loadIcon(pm)
                    val bitmap1 = drawable1.toBitmap(size, size, Bitmap.Config.ARGB_8888)
                    bigRemoteViews.setImageViewBitmap(R.id.iv_app_1, bitmap1)

                    val app2 = apps[1]
                    val drawable2 = app2.applicationInfo.loadIcon(pm)
                    val bitmap2 = drawable2.toBitmap(size, size, Bitmap.Config.ARGB_8888)
                    bigRemoteViews.setImageViewBitmap(R.id.iv_app_2, bitmap2)

                    val app3 = apps[2]
                    val drawable3 = app3.applicationInfo.loadIcon(pm)
                    val bitmap3 = drawable3.toBitmap(size, size, Bitmap.Config.ARGB_8888)
                    bigRemoteViews.setImageViewBitmap(R.id.iv_app_3, bitmap3)

                    val app4 = apps[3]
                    val drawable4 = app4.applicationInfo.loadIcon(pm)
                    val bitmap4 = drawable4.toBitmap(size, size, Bitmap.Config.ARGB_8888)
                    bigRemoteViews.setImageViewBitmap(R.id.iv_app_4, bitmap4)

                    val app5 = apps[4]
                    val drawable5 = app5.applicationInfo.loadIcon(pm)
                    val bitmap5 = drawable5.toBitmap(size, size, Bitmap.Config.ARGB_8888)
                    bigRemoteViews.setImageViewBitmap(R.id.iv_app_5, bitmap5)

                    val app6 = apps[5]
                    val drawable6 = app6.applicationInfo.loadIcon(pm)
                    val bitmap6 = drawable6.toBitmap(size, size, Bitmap.Config.ARGB_8888)
                    bigRemoteViews.setImageViewBitmap(R.id.iv_app_6, bitmap6)

                    val app7 = apps[6]
                    val drawable7 = app7.applicationInfo.loadIcon(pm)
                    val bitmap7 = drawable7.toBitmap(size, size, Bitmap.Config.ARGB_8888)
                    bigRemoteViews.setImageViewBitmap(R.id.iv_app_7, bitmap7)

                    val app8 = apps[7]
                    val drawable8 = app8.applicationInfo.loadIcon(pm)
                    val bitmap8 = drawable8.toBitmap(size, size, Bitmap.Config.ARGB_8888)
                    bigRemoteViews.setImageViewBitmap(R.id.iv_app_8, bitmap8)

                    val app9 = apps[8]
                    val drawable9 = app9.applicationInfo.loadIcon(pm)
                    val bitmap9 = drawable9.toBitmap(size, size, Bitmap.Config.ARGB_8888)
                    bigRemoteViews.setImageViewBitmap(R.id.iv_app_9, bitmap9)

                    val app10 = apps[9]
                    val drawable10 = app10.applicationInfo.loadIcon(pm)
                    val bitmap10 = drawable10.toBitmap(size, size, Bitmap.Config.ARGB_8888)
                    bigRemoteViews.setImageViewBitmap(R.id.iv_app_10, bitmap10)

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

            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.setCustomContentView(smallRemoteViews)

        // 设置悬浮通知视图（Android 12 及以上）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            builder.setCustomHeadsUpContentView(bigRemoteViews)
        }

        // 设置大视图
        builder.setCustomBigContentView(bigRemoteViews)

        notificationManager.notify(actionId, builder.build())
        if (actionId == ID_WEATHER) {
            AppPreferences.getInstance().put("last_weather_notification_time", System.currentTimeMillis())
        }
        if (actionId == ID_JUNK_CLEANER) {
            AppPreferences.getInstance().put("last_junk_notification_time", System.currentTimeMillis())
        }
        if (actionId == ID_NEWS) {
            AppPreferences.getInstance().put("last_news_notification_time", System.currentTimeMillis())
        }
        if (actionId == ID_APP_PROCESS_1 || actionId == ID_APP_PROCESS_2) {
            AppPreferences.getInstance().put("last_process_notification_time", System.currentTimeMillis())
        }
        if (actionId == ID_CONSTELLATION) {
            AppPreferences.getInstance().put("last_constellation_notification_time", System.currentTimeMillis())
        }
        if (actionId == ID_USAGE_REPORT) {
            AppPreferences.getInstance().put("last_usage_notification_time", System.currentTimeMillis())
        }
    }

}