package com.base.appzxhy.push.work

import android.content.Context
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.base.appzxhy.bean.push.NotificationSendBean
import com.base.appzxhy.bean.push.NotificationSendBean.Companion.POPUP_WHERE_WORK_MANAGER
import com.base.appzxhy.bean.config.PopupConfigBean
import com.base.appzxhy.business.helper.EventUtils
import com.base.appzxhy.business.push.notification.MyNotificationManager
import java.util.concurrent.TimeUnit

class RepeatingWorker(val appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) {

    override fun doWork(): Result {
        // 这里执行你的任务
        // 例如，更新UI，发送网络请求等
        EventUtils.event("workManager_live")
        try {
            if (PopupConfigBean.popupConfigBean.workS) {
                MyNotificationManager.submitSendBean(NotificationSendBean(appContext, POPUP_WHERE_WORK_MANAGER))
            }
        } catch (e: Exception) {
            EventUtils.event("WorkManager Error")
        }
        return Result.success()
    }

    companion object {
        const val TAG = "uniqueWorkName"

        fun schedulePeriodicWork(context: Context) {
            WorkManager.getInstance(context).cancelAllWorkByTag(TAG)

            val request = PeriodicWorkRequestBuilder<RepeatingWorker>(15, TimeUnit.MINUTES)
                .setConstraints(
                    Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
                )
                .build()

            WorkManager.getInstance(context).enqueueUniquePeriodicWork(
                TAG, ExistingPeriodicWorkPolicy.KEEP, request
            )
        }

    }
}