package com.base.pdfviewerscannerwhite.fcm

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.widget.RemoteViews
import androidx.core.app.NotificationCompat
import androidx.core.graphics.drawable.IconCompat
import com.base.pdfviewerscannerwhite.BuildConfig
import com.base.pdfviewerscannerwhite.R
import com.base.pdfviewerscannerwhite.bean.ConstObject.NOTIFICATION_ACTION_APP_PROCESS
import com.base.pdfviewerscannerwhite.bean.ConstObject.NOTIFICATION_ACTION_CLEAN_JUNK
import com.base.pdfviewerscannerwhite.bean.ConstObject.NOTIFICATION_ACTION_IMPORTANT_DOCUMENT
import com.base.pdfviewerscannerwhite.bean.ConstObject.NOTIFICATION_ACTION_NEW_IMAGE_PDF
import com.base.pdfviewerscannerwhite.bean.ConstObject.NOTIFICATION_ACTION_READ_DOCUMENTS
import com.base.pdfviewerscannerwhite.bean.ConstObject.NOTIFICATION_ACTION_READ_PDF
import com.base.pdfviewerscannerwhite.bean.ConstObject.NOTIFICATION_ACTION_UN_VIEW_FILES
import com.base.pdfviewerscannerwhite.bean.ConstObject.NOTIFICATION_ACTION_WEATHER
import com.base.pdfviewerscannerwhite.bean.WeatherBean
import com.base.pdfviewerscannerwhite.fcm.PopupConstObject.POPUP_WHERE_FCM
import com.base.pdfviewerscannerwhite.fcm.PopupConstObject.POPUP_WHERE_LOCK
import com.base.pdfviewerscannerwhite.fcm.PopupConstObject.POPUP_WHERE_TIMBER
import com.base.pdfviewerscannerwhite.fcm.PopupConstObject.popup_count
import com.base.pdfviewerscannerwhite.fcm.PopupConstObject.popup_end
import com.base.pdfviewerscannerwhite.fcm.PopupConstObject.popup_fcm_interval
import com.base.pdfviewerscannerwhite.fcm.PopupConstObject.popup_interval
import com.base.pdfviewerscannerwhite.fcm.PopupConstObject.popup_lock_interval
import com.base.pdfviewerscannerwhite.fcm.PopupConstObject.popup_start
import com.base.pdfviewerscannerwhite.fcm.PopupConstObject.popup_status
import com.base.pdfviewerscannerwhite.fcm.PopupConstObject.popup_timer_interval
import com.base.pdfviewerscannerwhite.helper.EventUtils
import com.base.pdfviewerscannerwhite.helper.MyApplication
import com.base.pdfviewerscannerwhite.helper.WeatherUtils
import com.base.pdfviewerscannerwhite.ui.cleanjunk.ScanJunkActivity.Companion.fastGetJunkSize
import com.base.pdfviewerscannerwhite.ui.splash.SplashActivity
import com.base.pdfviewerscannerwhite.utils.AppPreferences
import com.base.pdfviewerscannerwhite.utils.KotlinExt.toFormatSize
import com.base.pdfviewerscannerwhite.utils.LogEx
import com.base.pdfviewerscannerwhite.utils.RamUtils.ramPair
import com.base.pdfviewerscannerwhite.utils.TimeUtils.formatATime
import com.base.pdfviewerscannerwhite.utils.TimeUtils.isDayOrNight
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
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" // 通知渠道名称
    var NOTIFICATION_ID = 8999

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

    //当天推送次数
    var dayPopupCount = 0
        get() {
            return AppPreferences.getInstance().getInt("dayPopupCount_${currentDate()}", field)
        }
        set(value) {
            field = value
            AppPreferences.getInstance().put("dayPopupCount_${currentDate()}", value, true)
        }
    var lastPopupTime = 0L
        get() {
            return AppPreferences.getInstance().getLong("lastPopupTime", field)
        }
        set(value) {
            field = value
            AppPreferences.getInstance().put("lastPopupTime", value, true)
        }

    fun canSendNotification(where: String, actionId: String): Boolean {
        //是否开启推送
        val status = AppPreferences.getInstance().getString(popup_status, "1").toInt()
        if (status == 0) {
            EventUtils.event("Notification_Error", "status=$status")
            LogEx.logDebug("canSendNotification", "status")
            return false
        }
        //当天推送次数
        val count = AppPreferences.getInstance().getString(popup_count, "20").toInt()
        if (dayPopupCount > count) {
            LogEx.logDebug("canSendNotification", "count")
            EventUtils.event("Notification_Error", "dayPopupCount=$dayPopupCount count=$count where=$where actionId=$actionId")
            return false
        }
        //判断是否在时间区域
        val start = AppPreferences.getInstance().getString(popup_start, "0").toInt()
        val end = AppPreferences.getInstance().getString(popup_end, "24").toInt()
        val calendar = Calendar.getInstance()
        val currentHour = calendar.get(Calendar.HOUR_OF_DAY)
        if (currentHour !in start until end) {
            LogEx.logDebug("canSendNotification", "start-end currentHour=$currentHour start=$start end=$end")
            EventUtils.event("Notification_Error", "start=$start end=$end currentHour=$currentHour where=$where actionId=$actionId")
            return false
        }

        //单位分钟
        var interval = AppPreferences.getInstance().getString(popup_interval, "1").toInt()
        if (where == POPUP_WHERE_TIMBER) {
            interval = AppPreferences.getInstance().getString(popup_timer_interval, "7").toInt()
        }
        if (where == POPUP_WHERE_LOCK) {
            interval = AppPreferences.getInstance().getString(popup_lock_interval, "1").toInt()
        }
        if (where == POPUP_WHERE_FCM) {
            interval = AppPreferences.getInstance().getString(popup_fcm_interval, "1").toInt()
        }
        val passedTime = System.currentTimeMillis() - lastPopupTime
        if (passedTime < interval * 60 * 1000L) {
            EventUtils.event("Notification_Error", "where=$where actionId=$actionId interval=$interval passedTime=$passedTime")
            LogEx.logDebug("canSendNotification", "interval where=$where passedTime=$passedTime interval=$interval")
            return false
        }

        return true
    }

    var hoverActionId = ""

    @SuppressLint("RemoteViewLayout")
    fun sendNotificationIfCan(context: Context, actionId: String, where: String = "") {
        if (!canSendNotification(where, actionId)) return

        //发送通知
        setActionNotification(context, actionId)

        //上报通知
        EventUtils.event("Notification_Popup", "where=$where actionId=$actionId")
        //当天次数加一
        dayPopupCount += 1

        //推送时间
        lastPopupTime = System.currentTimeMillis()

        //悬停通知
        hoverActionId = actionId
        NotificationHoverUtils.sendHoverNotification(context)
    }

    fun setActionNotification(context: Context, actionId: String) {
        val bigRemoteViews = RemoteViews(MyApplication.context.packageName, R.layout.notification_message)
        val smallRemoteViews = RemoteViews(MyApplication.context.packageName, R.layout.notification_message)
        val intent = Intent(context, SplashActivity::class.java)
        intent.putExtra("actionId", actionId)

        when (actionId) {
            NOTIFICATION_ACTION_NEW_IMAGE_PDF -> {
                val tittle = context.getString(R.string.new_image_for_creating_pdf)
                val desc = context.getString(R.string.edit_images_to_create_pdf_files)
                bigRemoteViews.setTextViewText(R.id.tv_tittle, tittle)
                smallRemoteViews.setTextViewText(R.id.tv_tittle, tittle)
                bigRemoteViews.setTextViewText(R.id.tv_desc, desc)
                smallRemoteViews.setTextViewText(R.id.tv_desc, desc)
                sendCustomNotification(context, intent, bigRemoteViews, smallRemoteViews)
            }

            NOTIFICATION_ACTION_READ_PDF -> {
                val tittle = context.getString(R.string.read_your_pdf_file)
                val desc = context.getString(R.string.did_you_miss_this_pdf_file)
                bigRemoteViews.setTextViewText(R.id.tv_tittle, tittle)
                smallRemoteViews.setTextViewText(R.id.tv_tittle, tittle)
                bigRemoteViews.setTextViewText(R.id.tv_desc, desc)
                smallRemoteViews.setTextViewText(R.id.tv_desc, desc)
                sendCustomNotification(context, intent, bigRemoteViews, smallRemoteViews)
            }

            NOTIFICATION_ACTION_READ_DOCUMENTS -> {
                val tittle = context.getString(R.string.read_more_phone_documents)
                val desc = context.getString(R.string.click_to_read_and_edit_your_document)
                bigRemoteViews.setTextViewText(R.id.tv_tittle, tittle)
                smallRemoteViews.setTextViewText(R.id.tv_tittle, tittle)
                bigRemoteViews.setTextViewText(R.id.tv_desc, desc)
                smallRemoteViews.setTextViewText(R.id.tv_desc, desc)
                sendCustomNotification(context, intent, bigRemoteViews, smallRemoteViews)
            }

            NOTIFICATION_ACTION_UN_VIEW_FILES -> {
                val tittle = context.getString(R.string.there_are_unviewed_files)
                val desc = context.getString(R.string.click_to_read_now)
                bigRemoteViews.setTextViewText(R.id.tv_tittle, tittle)
                smallRemoteViews.setTextViewText(R.id.tv_tittle, tittle)
                bigRemoteViews.setTextViewText(R.id.tv_desc, desc)
                smallRemoteViews.setTextViewText(R.id.tv_desc, desc)
                sendCustomNotification(context, intent, bigRemoteViews, smallRemoteViews)
            }

            NOTIFICATION_ACTION_IMPORTANT_DOCUMENT -> {
                val tittle = context.getString(R.string.don_t_miss_important_documents)
                val desc = context.getString(R.string.view_now)
                bigRemoteViews.setTextViewText(R.id.tv_tittle, tittle)
                smallRemoteViews.setTextViewText(R.id.tv_tittle, tittle)
                bigRemoteViews.setTextViewText(R.id.tv_desc, desc)
                smallRemoteViews.setTextViewText(R.id.tv_desc, desc)
                sendCustomNotification(context, intent, bigRemoteViews, smallRemoteViews)
            }

            NOTIFICATION_ACTION_APP_PROCESS -> {
                val pair = MyApplication.context.ramPair()
                val percent = (pair.first * 100 / pair.second).toInt()

                val desc = "Memory is $percent% used"
                val smallRemoteViewsVar = RemoteViews(context.packageName, R.layout.notification_memory_small_1)
                smallRemoteViewsVar.setProgressBar(R.id.progress_bar, percent, 100, false)
                smallRemoteViewsVar.setTextViewText(R.id.tv_desc, desc)
                val btnRequestCode = Random.nextInt(1000)
                smallRemoteViewsVar.setOnClickPendingIntent(
                    R.id.tv_btn,
                    PendingIntent.getActivity(context, btnRequestCode, intent, PendingIntent.FLAG_IMMUTABLE)
                )

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

                sendCustomNotification(context, intent, bigRemoteViewsVar, smallRemoteViewsVar)
            }

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

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

                sendCustomNotification(context, intent, bigRemoteViewsVar, smallRemoteViewsVar)
            }

            NOTIFICATION_ACTION_WEATHER -> {
                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, 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
                }

                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_11h, icon)
                bigRemoteViewsVar.setImageViewResource(R.id.iv_weather_14h, icon)
                bigRemoteViewsVar.setImageViewResource(R.id.iv_weather_17h, icon)
                bigRemoteViewsVar.setImageViewResource(R.id.iv_weather_20h, icon)
                bigRemoteViewsVar.setImageViewResource(R.id.iv_weather_23h, icon)
                bigRemoteViewsVar.setImageViewResource(R.id.iv_weather, icon)

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

                bigRemoteViewsVar.setTextViewText(R.id.tv_wendu_now, 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()}")

                sendCustomNotification(context, intent, bigRemoteViewsVar, smallRemoteViewsVar)
            }


            else -> {
                EventUtils.event("Notification_Error", "unKnow actionId actionId=$actionId")
            }
        }
    }

    private fun sendCustomNotification(
        context: Context,
        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
            )
        )
        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)
            .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(NOTIFICATION_ID, builder.build())
    }

    val looper_actionId = listOf(
        NOTIFICATION_ACTION_READ_PDF,
        NOTIFICATION_ACTION_READ_DOCUMENTS,
        NOTIFICATION_ACTION_UN_VIEW_FILES,
        NOTIFICATION_ACTION_IMPORTANT_DOCUMENT,
        NOTIFICATION_ACTION_APP_PROCESS,
        NOTIFICATION_ACTION_CLEAN_JUNK,
        NOTIFICATION_ACTION_WEATHER
    )

    var actionIdList = arrayListOf<String>()
    fun getNextActionId(): String {
        if (actionIdList.isEmpty()) {
            actionIdList.addAll(looper_actionId)
        }
        val next = actionIdList[0]
        actionIdList.removeAt(0)
        if (BuildConfig.DEBUG) {
//            return NOTIFICATION_ACTION_WEATHER
        }
        return next
    }
}