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.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.popup_count
import com.base.locationsharewhite.fcm.PopupConstObject.popup_end
import com.base.locationsharewhite.fcm.PopupConstObject.popup_fcm_interval
import com.base.locationsharewhite.fcm.PopupConstObject.popup_interval
import com.base.locationsharewhite.fcm.PopupConstObject.popup_lock_interval
import com.base.locationsharewhite.fcm.PopupConstObject.popup_start
import com.base.locationsharewhite.fcm.PopupConstObject.popup_status
import com.base.locationsharewhite.fcm.PopupConstObject.popup_timer_interval
import com.base.locationsharewhite.helper.EventUtils
import com.base.locationsharewhite.helper.MyApplication
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 {
        //是否开启推送
        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, where: String = "", id: String? = null) {

        val actionId = id ?: getNextActionId()

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

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

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

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

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

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

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

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

    /**
     * 特定类型的是否可以推送
     */
    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()
        }

        return canPush
    }


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

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

            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(
        "",
    )

    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
    }
}