package com.zxdemo.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import com.zxdemo.notity.NotificationUtils
import com.zxdemo.utils.SpUtils
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit

class AppInstallReceiver : BroadcastReceiver() {

    companion object {
        fun registerReceiver(context: Context) {
            val intentFilter = IntentFilter()
            intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED)//卸载
            intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED)//安装
            intentFilter.addDataScheme("package")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                context.registerReceiver(
                    AppInstallReceiver(),
                    intentFilter,
                    Context.RECEIVER_EXPORTED
                )
            } else {
                context.registerReceiver(AppInstallReceiver(), intentFilter)
            }
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onReceive(context: Context, intent: Intent) {
//获取当前时间和上一次推送的时间
        var current = LocalDateTime.now()
        val intervalTime = 1L //间隔时间(分钟)
        val lastTime =
            SpUtils.getInstance().getString("NOTICE_APP_TIME", "")
        var parsedDateTime: LocalDateTime = current
        if (lastTime != "") {
            parsedDateTime =
                LocalDateTime.parse(lastTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"))
        }
        // 计算两个时间点之间的差异
        val minutesBetween = ChronoUnit.MINUTES.between(parsedDateTime, current)
        if (minutesBetween >= intervalTime || minutesBetween.toInt() == 0) {
            intent.action?.let {
                Log.d("TAG", "onReceive:安装卸载推送 ${intent.action}")
                NotificationUtils.sendNotification(context, "showNotification", "receive_app")

                SpUtils.getInstance().putString(
                    "NOTICE_APP_TIME",
                    current.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"))
                )
            }
        }
    }
}
