package com.remax.visualnovel.ui.wallet.manager

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.remax.visualnovel.R
import com.remax.visualnovel.api.factory.ServiceFactory
import com.remax.visualnovel.app.base.BaseBindingActivity
import com.remax.visualnovel.entity.request.ChargeProduct
import com.remax.visualnovel.entity.response.Wallet
import com.remax.visualnovel.entity.response.base.parseData
import com.remax.visualnovel.extension.launchFlow
import com.remax.visualnovel.extension.toast
import com.remax.visualnovel.manager.pay.GooglePayManager
import com.remax.visualnovel.repository.api.PayRepository
import com.remax.visualnovel.ui.wallet.dialog.RechargeDialog
import com.pengxr.modular.eventbus.generated.events.EventDefineOfWalletEvents
import com.remax.visualnovel.configs.NovelApplication
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

/**
 * Created by HJW on 2025/9/15
 */
object WalletManager : DefaultLifecycleObserver {

    var balance: Long = 0

    private val walletObserver = Observer<Wallet?> { wallet ->
        balance = wallet?.balance ?: 0L
    }

    override fun onCreate(owner: LifecycleOwner) {
        EventDefineOfWalletEvents.buffBalanceUpdateSucceeded().observeForever(walletObserver)
    }

    override fun onResume(owner: LifecycleOwner) {
            refreshRechargeProducts()
    }

    override fun onDestroy(owner: LifecycleOwner) {
        EventDefineOfWalletEvents.buffBalanceUpdateSucceeded().removeObserver(walletObserver)
    }

    private val payRepository by lazy {
        PayRepository(ServiceFactory.createService())
    }

    fun refreshWallet() {
        MainScope().launch {
            launchFlow(payRepository::getMyWallet).collect()
        }
    }

    private val productList by lazy {
        arrayListOf<ChargeProduct>()
    }

    /**
     * 创建google pay充值订单
     * @param product ChargeProduct 后端返回的实体对象
     */
    fun onCreateOrder(product: ChargeProduct) {
        MainScope().launch {
            launchFlow({
                payRepository.createOrder(product)
            }, {
                (NovelApplication.getCurrentActivity() as? BaseBindingActivity<*>)?.showLoading()
            }) {
                (NovelApplication.getCurrentActivity() as? BaseBindingActivity<*>)?.hideLoading()
            }.collect {
                it.parseData({
                    onSuccess = { res ->
                        res?.run {
                            (NovelApplication.getCurrentActivity() as? BaseBindingActivity<*>)?.let { act ->
                                GooglePayManager.pay(act, product.productId, tradeNo = res.tradeNo) {
                                    act.toast(act.getString(R.string.google_pay_fail_toast))
                                }
                            }
                        }
                    }

                    onFailed = { errorCode, _ ->

                    }
                })
            }
        }
    }

    fun refreshRechargeProducts() {
        GooglePayManager.checkProductDetails()
        MainScope().launch {
            if (productList.isEmpty()) {
                payRepository.getProducts().transformResult({
                    productList.clear()
                    productList.addAll(it?.productList ?: emptyList())
                })
            }
        }
    }

    fun showChargeDialog() {
        if (productList.isNotEmpty()) {
            NovelApplication.getCurrentActivity()?.let { act ->
                productList.forEachIndexed { index, product ->
                    product.selected = index == 0
                }
                RechargeDialog(act).build(productList)
            }
        } else {
            refreshRechargeProducts()
        }
    }
}