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.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_APP_PROCESS
import com.base.browserwhite.bean.ConstObject.ID_CLEAN_JUNK_MEMORY
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_WEATHER
import com.base.browserwhite.bean.NewsBean
import com.base.browserwhite.bean.WeatherBean
import com.base.browserwhite.help.NewsUtils.getNewSp
import com.base.browserwhite.utils.TimeUtils.formatATime
import com.base.browserwhite.utils.TimeUtils.isDayOrNight
import com.base.browserwhite.help.WeatherUtils
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.LogEx
import com.base.browserwhite.utils.RamUtils.ramPair
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, where: String) {


        if (!NotificationPushUtil.canPushNotification(actionId, where)) {
            return
        }

        when (actionId) {
            ID_JUNK_CLEANER, ID_INSTALL_APP, ID_UNINSTALL_APP -> {//清理
                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? = getNewSp()?.random()
                    if (news == null) {
                        LogEx.logDebug(TAG, "NewsBean==null")
                        return@Thread
                    }

                    val bitmap = getBitmapFromURL(news.orgImgPath)
                    if (bitmap == null) {
                        LogEx.logDebug(TAG, "bitmap==null")
                        return@Thread
                    }

                    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 -> {//内存
                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)
                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_small)
                bigRemoteViews.setProgressBar(R.id.progress_bar, percent, 100, false)
                bigRemoteViews.setTextViewText(R.id.tv_desc, desc)

                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, bigRemoteViews)
            }

            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())
//        }
        notificationManager.notify(actionId, builder.build())
        AppPreferences.getInstance().put("last_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) {
            AppPreferences.getInstance().put("last_process_notification_time", System.currentTimeMillis())
        }
    }

}