package com.base.scanqr.fcm

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.base.scanqr.bean.NotificationSendBean
import com.base.scanqr.bean.NotificationSendBean.Companion.ACTION_ID_SCAN
import com.base.scanqr.bean.NotificationSendBean.Companion.POPUP_WHERE_FCM
import com.base.scanqr.fcm.notification.MyNotificationManager
import com.base.scanqr.helper.EventUtils.event
import com.base.scanqr.utils.LogEx
import java.util.Calendar
import java.util.TimeZone

class FcmReceiver : BroadcastReceiver() {

    private val TAG = "FcmReceiver"

    override fun onReceive(context: Context, intent: Intent) {
        event("FCM_Received", "FcmReceiver", null)
        LogEx.logDebug(TAG, "FCM FcmReceiver")
        val sendBean = NotificationSendBean(context, POPUP_WHERE_FCM, canSend = { true }, sendSuccess = {})
        if (isWithinTimeRange()) {
            val map = hashMapOf<String, Any>()
            map["AM"] = "Scan today's product information."
            sendBean.valueMap = map
            sendBean.actionId = ACTION_ID_SCAN
        }
        MyNotificationManager.submitSendBean(sendBean)
    }

    private fun isWithinTimeRange(): Boolean {
        // 获取当前时间的Calendar实例
        val now: Calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"))

        // 设置起始时间8:30 AM
        val startTime: Calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
        startTime.set(Calendar.HOUR_OF_DAY, 8)
        startTime.set(Calendar.MINUTE, 30)
        startTime.set(Calendar.SECOND, 0)
        startTime.set(Calendar.MILLISECOND, 0)

        // 设置结束时间10:30 AM
        val endTime: Calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
        endTime.set(Calendar.HOUR_OF_DAY, 10)
        endTime.set(Calendar.MINUTE, 30)
        endTime.set(Calendar.SECOND, 0)
        endTime.set(Calendar.MILLISECOND, 0)

        // 判断当前时间是否在指定时间段内
        return now.after(startTime) && now.before(endTime)
    }
}
