package com.base.locationsharewhite.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.locationsharewhite.BuildConfig
import com.base.locationsharewhite.R
import com.base.locationsharewhite.fcm.PopupConstObject.ACTION_1
import com.base.locationsharewhite.fcm.PopupConstObject.ACTION_2
import com.base.locationsharewhite.fcm.PopupConstObject.ACTION_3
import com.base.locationsharewhite.fcm.PopupConstObject.ACTION_4
import com.base.locationsharewhite.fcm.PopupConstObject.ACTION_5
import com.base.locationsharewhite.fcm.PopupConstObject.ACTION_6
import com.base.locationsharewhite.fcm.PopupConstObject.ACTION_7
import com.base.locationsharewhite.fcm.PopupConstObject.POPUP_WHERE_BATTERY
import com.base.locationsharewhite.fcm.PopupConstObject.POPUP_WHERE_FCM
import com.base.locationsharewhite.fcm.PopupConstObject.POPUP_WHERE_LOCK
import com.base.locationsharewhite.fcm.PopupConstObject.POPUP_WHERE_PACKAGE
import com.base.locationsharewhite.fcm.PopupConstObject.POPUP_WHERE_TIMBER
import com.base.locationsharewhite.fcm.PopupConstObject.popupConfigBean
import com.base.locationsharewhite.fcm.receiver.BatteryStatusReceiver
import com.base.locationsharewhite.fcm.receiver.PackageStatusReceiver
import com.base.locationsharewhite.fcm.receiver.ScreenStatusReceiver
import com.base.locationsharewhite.helper.EventUtils
import com.base.locationsharewhite.helper.MyApplication
import com.base.locationsharewhite.ui.main.MainActivity
import com.base.locationsharewhite.ui.splash.SplashActivity
import com.base.locationsharewhite.utils.AppPreferences
import com.base.locationsharewhite.utils.LogEx
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 val CHANNEL_ID = "location_notification_id" // 通知渠道ID
    private val CHANNEL_NAME = "location_fcm_channel" // 通知渠道名称
    private 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)
        }

    private fun canSendNotification(where: String, actionId: String): Boolean {
        //是否开启推送

        if (!popupConfigBean.popupStatus) {
            EventUtils.event("Notification_Error", "status=${popupConfigBean.popupStatus}")
            LogEx.logDebug("canSendNotification", "status")
            return false
        }
        //当天推送次数
        val count = popupConfigBean.popupCount
        if (dayPopupCount > count) {
            LogEx.logDebug("canSendNotification", "count")
            EventUtils.event("Notification_Error", "dayPopupCount=$dayPopupCount count=$count where=$where actionId=$actionId")
            return false
        }
        //判断是否在时间区域
        val start = popupConfigBean.popupStart
        val end = popupConfigBean.popupEnd
        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 = popupConfigBean.popupInterval
        if (where == POPUP_WHERE_TIMBER) {
            interval = popupConfigBean.popupTimerInterval
        }
        if (where == POPUP_WHERE_FCM) {
            interval = popupConfigBean.popupFcmInterval
        }
        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 = ""

    private var isUnLimit: Boolean = if (BuildConfig.DEBUG) false else false

    @SuppressLint("RemoteViewLayout")
    fun sendNotificationIfCan(context: Context, where: String = "", id: String? = null) {
        LogEx.logDebug(TAG, "sendNotificationIfCan where=$where")
        EventUtils.event("Notification_Popup_Start", "where=$where")

        val actionId = id ?: getNextActionId()

        if (!isUnLimit) {
            //总的限制条件
            if (!canSendNotification(where, actionId)) return

            //特定类限制条件
            if (!canOtherSend(where, actionId)) return

            if (MyApplication.PAUSED_VALUE == 1) {
                LogEx.logDebug(TAG, "APP Resumed")
                return
            }
        }

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

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

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

        //保存其他特定场景的推送判断条件
        saveOtherPopupData(actionId, where)

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

    /**
     * 特定类型的是否可以推送
     */
    private fun canOtherSend(where: String, actionId: String): Boolean {

        var canPush = true
        if (where == POPUP_WHERE_BATTERY) {
            canPush = BatteryStatusReceiver.canBatteryStatusReceiverPush()
        }
        if (where == POPUP_WHERE_PACKAGE) {
            canPush = PackageStatusReceiver.canPackageStatusReceiverPush()
        }
        if (where == POPUP_WHERE_LOCK) {
            canPush = ScreenStatusReceiver.canScreenStatusReceiverPush()
        }
        return canPush
    }


    private fun saveOtherPopupData(where: String, actionId: String) {
        BatteryStatusReceiver.saveBatteryPushedData(where, actionId)
        PackageStatusReceiver.savePackagePushedData(where, actionId)
        ScreenStatusReceiver.saveScreenPushedData(where, actionId)
    }

    fun setActionNotification(context: Context, actionId: String, where: String = "") {
        val bigRemoteViews = RemoteViews(MyApplication.appContext.packageName, R.layout.notification_style_1)
        val smallRemoteViews = RemoteViews(MyApplication.appContext.packageName, R.layout.notification_style_1)


        val intent = Intent(context, SplashActivity::class.java)
        intent.putExtra("actionId", actionId)

        when (actionId) {
            ACTION_1 -> {
                val desc = "Your journey awaits! Share your adventures and reconnect with friends."
                val btnString = "Resume Your Trip"
                bigRemoteViews.setTextViewText(R.id.tv_desc, desc)
                bigRemoteViews.setTextViewText(R.id.tv_btn, btnString)

                smallRemoteViews.setTextViewText(R.id.tv_desc, desc)
                smallRemoteViews.setTextViewText(R.id.tv_btn, btnString)

                testBtn(where, bigRemoteViews, smallRemoteViews)

                sendCustomNotification(context, intent, bigRemoteViews, smallRemoteViews)
            }

            ACTION_2 -> {
                val desc = "Explore new places and create unforgettable moments with us."
                val btnString = "Start Exploring"
                bigRemoteViews.setTextViewText(R.id.tv_desc, desc)
                bigRemoteViews.setTextViewText(R.id.tv_btn, btnString)

                smallRemoteViews.setTextViewText(R.id.tv_desc, desc)
                smallRemoteViews.setTextViewText(R.id.tv_btn, btnString)

                testBtn(where, bigRemoteViews, smallRemoteViews)

                sendCustomNotification(context, intent, bigRemoteViews, smallRemoteViews)
            }

            ACTION_3 -> {
                val desc = "Don't miss out on what your friends are up to. Join the fun!"
                val btnString = "Catch Up Now"
                bigRemoteViews.setTextViewText(R.id.tv_desc, desc)
                bigRemoteViews.setTextViewText(R.id.tv_btn, btnString)

                smallRemoteViews.setTextViewText(R.id.tv_desc, desc)
                smallRemoteViews.setTextViewText(R.id.tv_btn, btnString)

                testBtn(where, bigRemoteViews, smallRemoteViews)

                sendCustomNotification(context, intent, bigRemoteViews, smallRemoteViews)
            }

            ACTION_4 -> {
                val desc = "We've made it easier to share safely. Check out our new privacy features."
                val btnString = "Update Now"
                bigRemoteViews.setTextViewText(R.id.tv_desc, desc)
                bigRemoteViews.setTextViewText(R.id.tv_btn, btnString)

                smallRemoteViews.setTextViewText(R.id.tv_desc, desc)
                smallRemoteViews.setTextViewText(R.id.tv_btn, btnString)

                testBtn(where, bigRemoteViews, smallRemoteViews)

                sendCustomNotification(context, intent, bigRemoteViews, smallRemoteViews)
            }

            ACTION_5 -> {
                val desc = "Celebrate with us! Special events and giveaways are happening now."
                val btnString = "Join the Celebration"
                bigRemoteViews.setTextViewText(R.id.tv_desc, desc)
                bigRemoteViews.setTextViewText(R.id.tv_btn, btnString)

                smallRemoteViews.setTextViewText(R.id.tv_desc, desc)
                smallRemoteViews.setTextViewText(R.id.tv_btn, btnString)

                testBtn(where, bigRemoteViews, smallRemoteViews)

                sendCustomNotification(context, intent, bigRemoteViews, smallRemoteViews)
            }

            ACTION_6 -> {
                val desc = "Based on your travel history, we've found new places just for you."
                val btnString = "Discover New Places"
                bigRemoteViews.setTextViewText(R.id.tv_desc, desc)
                bigRemoteViews.setTextViewText(R.id.tv_btn, btnString)

                smallRemoteViews.setTextViewText(R.id.tv_desc, desc)
                smallRemoteViews.setTextViewText(R.id.tv_btn, btnString)

                testBtn(where, bigRemoteViews, smallRemoteViews)

                sendCustomNotification(context, intent, bigRemoteViews, smallRemoteViews)
            }

            ACTION_7 -> {
                val desc = "Ensure your travels are secure.  Update your privacy settings."
                val btnString = "Secure My Trip"
                bigRemoteViews.setTextViewText(R.id.tv_desc, desc)
                bigRemoteViews.setTextViewText(R.id.tv_btn, btnString)

                smallRemoteViews.setTextViewText(R.id.tv_desc, desc)
                smallRemoteViews.setTextViewText(R.id.tv_btn, btnString)

                testBtn(where, bigRemoteViews, smallRemoteViews)

                sendCustomNotification(context, intent, bigRemoteViews, smallRemoteViews)
            }


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

    private fun testBtn(where: String, vararg remoteViews: RemoteViews) {
        if (BuildConfig.DEBUG) {
            kotlin.runCatching {
                remoteViews[0].setTextViewText(R.id.tv_btn, where)
                remoteViews[1].setTextViewText(R.id.tv_btn, where)
            }
        }
    }

    private fun sendCustomNotification(
        context: Context,
        intent: Intent,
        bigRemoteViews: RemoteViews,
        smallRemoteViews: RemoteViews,
        notificationId: Int = NOTIFICATION_ID
    ) {

        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
            channel.enableVibration(false)
            channel.vibrationPattern = longArrayOf(0)
            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(notificationId, builder.build())
    }

    val looper_actionId = listOf(
        ACTION_1,
        ACTION_2,
        ACTION_3,
        ACTION_4,
        ACTION_5,
        ACTION_6,
        ACTION_7,
    )

    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
    }


    fun sendAllAllowedNotification(context: Context) {
        val bigRemoteViews = RemoteViews(MyApplication.appContext.packageName, R.layout.notification_style_2)
        val smallRemoteViews = RemoteViews(MyApplication.appContext.packageName, R.layout.notification_style_2)

        val intent = Intent(context, MainActivity::class.java).apply {
            putExtra("where", "sendAllAllowedNotification")
        }

        sendCustomNotification(context, intent, bigRemoteViews, smallRemoteViews, 1999)
    }
}