package com.base.scanqrclear.fcm

import android.annotation.SuppressLint
import com.base.scanqrclear.bean.NotificationSendBean
import com.base.scanqrclear.bean.NotificationSendBean.Companion.ACTION_ID_SCAN
import com.base.scanqrclear.bean.NotificationSendBean.Companion.POPUP_WHERE_FCM
import com.base.scanqrclear.fcm.notification.MyNotificationManager
import com.base.scanqrclear.helper.EventUtils.event
import com.base.scanqrclear.utils.LogEx
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import org.json.JSONObject
import java.util.Calendar
import java.util.TimeZone

@SuppressLint("MissingFirebaseInstanceTokenRefresh")
class MessagingService : FirebaseMessagingService() {
    private val TAG = "MessagingService"
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        super.onMessageReceived(remoteMessage)
        val data = JSONObject(remoteMessage.data.toString())
        event("FCM_Received", "MessagingService", data)
        LogEx.logDebug(TAG, "FCM MessagingService")
        val sendBean = NotificationSendBean(this, 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)
    }
}