package com.quyunshuo.module.home.utils

import android.content.Context
import androidx.work.BackoffPolicy
import androidx.work.CoroutineWorker
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import com.module.database.room.SZDatabase
import com.module.database.room.dao.LocalOrderDao
import com.module.database.room.entity.LocalOrderBean
import com.module.pay.service.HomeApiService
import com.quyunshuo.androidbaseframemvvm.base.BaseApplication
import com.quyunshuo.androidbaseframemvvm.common.constant.Heartbeat
import com.quyunshuo.module.home.service.GlobalServiceRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import java.io.IOException
import java.util.concurrent.TimeUnit
import javax.inject.Inject

class UploadWorker(
) {
    lateinit var orderDao: LocalOrderDao
    var orderService: HomeApiService? = null

    private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())

    // 最大重试次数配置
    companion object {
        private const val MAX_RETRY = 3

        @Volatile
        private var instance: UploadWorker? = null
        fun getInstance(

        ): UploadWorker {
            return instance ?: synchronized(this) {
                instance ?: UploadWorker().also {
                    instance = it
                    it.startAutoSync() // 初始化时自动启动同步
                }
            }
        }
    }

    fun init(
        context: Context, orderDao: LocalOrderDao,
        api: HomeApiService
    ) {
        this.orderDao = orderDao
        orderService = api
    }

    // 启动同步
    fun startAutoSync() {
        scope.launch {
            while (true) {
                delay(30_000) // 每30秒检查一次
                processPendingOrders()
            }
        }
    }

    private suspend fun processPendingOrders() {
        val unsyncedOrders = orderDao?.getUnsyncedData()
        unsyncedOrders?.forEach { order ->
            var retryCount = 0
            var success = false

            while (retryCount < MAX_RETRY && !success) {
                try {
                    val body: RequestBody =
                        RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(), "")
                    val response = orderService?.uploadOrder(body)
                    if (response != null) {
                        if (response.isSuccessful) {
                            order.syncStatus = 2
                            orderDao.update(order)
                            orderDao?.markAsSynced(order.id) // 仅标记成功项
                            success = true
                        } else {
                            retryCount++
                            delay(1000L * retryCount) // 指数退避
                        }
                    }
                } catch (e: Exception) {
                    retryCount++
                    delay(1000L * retryCount)
                }
            }
        }
    }

    // 新增订单
    suspend fun addNewOrder(order: LocalOrderBean) {
        orderDao?.insert(order)
        processPendingOrders() // 立即尝试上传
    }

    // 释放资源
    fun release() {
        scope.cancel()
    }


}