package com.ama.core.architecture.util

import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import kotlinx.coroutines.*
import java.util.concurrent.ConcurrentHashMap

object AsyncUtil {
    private val jobMap = ConcurrentHashMap<String, Job>()
    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
    

    fun <T> doGlobalAsync(
        backgroundWork: suspend () -> T,
        onStart: (() -> Unit)? = null,
        onComplete: ((T) -> Unit)? = null,
        onError: ((Exception) -> Unit)? = null
    ): Job {
        return scope.launch {
            onStart?.invoke()
            try {
                val result = withContext(Dispatchers.IO) { backgroundWork() }
                onComplete?.invoke(result)
            } catch (e: Exception) {
                onError?.invoke(e)
            }
        }.also { job ->
            job.invokeOnCompletion { cause ->
                if (cause != null) Log.d("AsyncTaskUtil", "Global task completed with error: $cause")
            }
        }
    }

    /**
     * 绑定组件生命周期的异步任务
     */
    fun <T> doLifecycleAwareAsync(
        lifecycleOwner: LifecycleOwner,
        backgroundWork: suspend () -> T,
        onStart: (() -> Unit)? = null,
        onComplete: ((T) -> Unit)? = null,
        onError: ((Exception) -> Unit)? = null
    ) {
        val key = lifecycleOwner::class.java.simpleName + System.identityHashCode(lifecycleOwner)
        
        // 清理现有任务
        jobMap[key]?.cancel()
        
        val job = scope.launch {
            onStart?.invoke()
            try {
                val result = withContext(Dispatchers.IO) { backgroundWork() }
                if (isActive) onComplete?.invoke(result)
            } catch (e: Exception) {
                if (e is CancellationException) throw e
                if (isActive) onError?.invoke(e)
            }
        }.also { jobMap[key] = it }
        
        // 绑定生命周期
        lifecycleOwner.lifecycle.addObserver(object : LifecycleEventObserver {
            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                when (event) {
                    Lifecycle.Event.ON_DESTROY -> {
                        job.cancel()
                        jobMap.remove(key)
                        lifecycleOwner.lifecycle.removeObserver(this)
                        Log.d("AsyncTaskUtil", "Lifecycle task cleaned up: $key")
                    }
                    else -> {}
                }
            }
        })
    }
    
    /**
     * 取消所有任务（用于应用退出）
     */
    fun shutdown() {
        scope.cancel()
        jobMap.clear()
    }
}



/*

// 1 全局任务 ----------------------
val job = AsyncTaskUtil.doGlobalAsync(
    backgroundWork = {
        // 在IO线程执行
        simulateNetworkRequest()
    },
    onStart = { showProgressBar() },
    onComplete = { result ->
        // 在主线程执行
        updateUI(result)
    },
    onError = { e ->
        showError(e.message ?: "Unknown error")
    }
)

// 手动取消（如果需要）
job.cancel()




// 2 生命周期绑定任务 ----------------------
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 任务自动绑定到Activity生命周期
        AsyncTaskUtil.doLifecycleAwareAsync(
            lifecycleOwner = this,
            backgroundWork = { loadUserData() },
            onComplete = { data -> updateUserInterface(data) },
            onError = { e -> showErrorMessage(e) }
        )
    }
}


// 3 ViewModel中 ----------------------
class MyViewModel : ViewModel() {
    fun loadData() {
        // 使用viewModelScope而非全局Scope
        viewModelScope.launch {
            try {
                val data = withContext(Dispatchers.IO) { fetchData() }
                _uiState.value = SuccessState(data)
            } catch (e: Exception) {
                _uiState.value = ErrorState(e.message)
            }
        }
    }
}

 */