package com.adealink.weparty.wallet.recharge.viewmodel

import android.widget.Toast
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.adealink.frame.base.IError
import com.adealink.frame.base.Rlt
import com.adealink.frame.log.Log
import com.adealink.frame.mvvm.livedata.ExtMutableLiveData
import com.adealink.frame.mvvm.livedata.OnceMutableLiveData
import com.adealink.frame.mvvm.viewmodel.BaseViewModel
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.module.account.AccountModule
import com.adealink.weparty.module.wallet.data.Currency
import com.adealink.weparty.module.wallet.data.PayChannel
import com.adealink.weparty.wallet.R
import com.adealink.weparty.wallet.data.TAG_WALLET
import com.adealink.weparty.wallet.manager.walletManager
import com.adealink.weparty.wallet.pay.PayRes
import com.adealink.weparty.wallet.pay.payManager
import com.adealink.weparty.wallet.recharge.data.RechargeItemData
import com.adealink.weparty.wallet.recharge.data.RechargeProduct
import kotlinx.coroutines.launch
import java.lang.ref.WeakReference

class RechargeViewModel : BaseViewModel() {

    private val rechargeList = mutableListOf<RechargeItemData>()
    private var selectedItem: RechargeItemData? = null

    val rechargeListRltLD = ExtMutableLiveData<Rlt<Any>>()
    val rechargeListLD = MutableLiveData<List<RechargeItemData>>()

    fun setupPayChannel(channel: PayChannel): LiveData<Rlt<Any>> {
        val liveData = OnceMutableLiveData<Rlt<Any>>()
        viewModelScope.launch {
            liveData.send(payManager.setupPayChannel(channel))
        }
        return liveData
    }

    fun pullRechargeList(channel: PayChannel, currency: Currency) {
        viewModelScope.launch {
            val rlt = payManager.getRechargeList(channel, currency)
            rechargeListRltLD.send(rlt)
            when (rlt) {
                is Rlt.Failed -> {
                    //Ntd.
                }

                is Rlt.Success -> {
                    rechargeList.clear()
                    rechargeList.addAll(rlt.data.map {
                        RechargeItemData(it)
                    })
                    rechargeListLD.send(rechargeList)
                }
            }
        }
    }

    fun getSelectedItem(): RechargeItemData? {
        return selectedItem
    }

    fun selectItem(item: RechargeItemData) {
        for (data in rechargeList) {
            data.selected = data == item
            if (data.selected) {
                selectedItem = data
            }
        }
        rechargeListLD.send(rechargeList)
    }


    fun buyProduct(activity: FragmentActivity, product: RechargeProduct): LiveData<Rlt<Any>> {
        val liveData = OnceMutableLiveData<Rlt<Any>>()
        val activityRef = WeakReference(activity)
        viewModelScope.launch {
            Log.i(TAG_WALLET, "recharge, $product")
            val uid = AccountModule.uid
            if (uid.isNullOrEmpty()) {
                liveData.send(Rlt.Failed(IError("User not login")))
                return@launch
            }
            val activity = activityRef.get() ?: return@launch
            val rlt = payManager.buyProduct(activity, product)
            when (rlt) {
                is Rlt.Failed -> {
                    val resCode = rlt.error.serverCode
                    Log.e(TAG_WALLET, "onBuyFailed, resCode$resCode")
                    when (resCode) {
                        PayRes.PURCHASE_USER_CANCEL -> {
                            showToast(R.string.wallet_recharge_cancel, Toast.LENGTH_SHORT)
                        }
                        PayRes.VERIFY_ORDER_FAILED -> {
                            showToast(R.string.wallet_verify_fail, Toast.LENGTH_LONG)
                        }
                        PayRes.PURCHASE_PENDING -> {
                            showToast(R.string.wallet_pending_tip, Toast.LENGTH_LONG)
                        }
                        else -> {
                            showToast(R.string.wallet_buy_fail, Toast.LENGTH_SHORT)
                        }
                    }
                    liveData.send(rlt)
                }

                is Rlt.Success -> {
                    walletManager.refreshWalletData()
                    showToast(R.string.wallet_recharge_success)
                    liveData.send(rlt)
                }
            }
        }
        return liveData
    }
}