package com.abbidot.tracker.deprecated.ui.activity.vm

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.DiffUtil
import com.abbidot.baselibrary.constant.MMKVKey
import com.abbidot.baselibrary.list.BaseRecyclerAdapter
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.baselibrary.util.MMKVUtil
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.bean.*
import com.abbidot.tracker.database.MyDatabase
import com.abbidot.tracker.diff.PaymentMethodDiffCallBack
import com.abbidot.tracker.retrofit2.NetworkApi
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.braintreepayments.api.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 *Created  by .yzq on 2022/3/28/028.
 * @link
 * @description:braintree支付
 */
class BraintreePalViewModel : ViewModel() {

    //是否是沙盒环境
    private val isSandbox = true

    /**
     * 标记化密钥 初始化sdk
     */
    //沙盒测试
    private val sandboxTokenizationKey = "sandbox_csgnn5ww_dp75dg57ptvqwz9b"

    //生产正式
    private val productionTokenizationKey = "sandbox_csgnn5ww_dp75dg57ptvqwz9b"

    val mBraintreeClientTokenLiveData = MutableLiveData<Result<PayResultBean>>()
    val mPayPalOrderNoLiveData = MutableLiveData<Result<OrderBean>>()
    val mUpdateOrderStatusLiveData = MutableLiveData<Result<String>>()

    //信用卡支付结果
    val mCardPaymentResultLiveData = MutableLiveData<Result<String>>()


    fun getTokenizationKey(): String {
        if (isSandbox) {
            return sandboxTokenizationKey
        }
        return productionTokenizationKey
    }


    /**
     * 显示添加的信用卡
     */
    fun addCreditCard(activity: BaseActivity<*>,
                      card: CreditCardBean,
                      adapter: BaseRecyclerAdapter<MenuTxtBean>) {
        val oldList = adapter.getData()
        val newList = mutableListOf<MenuTxtBean>()
        newList.addAll(oldList)
        //判断是否卡号一样
        var isSame = false
        for (i in 0 until newList.size) {
            val menuTxtBean = newList[i]
            if (menuTxtBean.menuName == card.cardNumber) {
                isSame = true
                menuTxtBean.menuValue = card.expirationDate
                break
            }
        }
        if (!isSame) {
            newList.removeLast()
            val imageId = Util.getCreditCardType(card.cardNumber)
            ViewUtil.instance.addMenuBean(newList, card.cardNumber, card.expirationDate, imageId)
            ViewUtil.instance.addMenuBean(newList,
                    activity.getString(R.string.txt_pay_order_add_card), "",
                    R.drawable.ico_lay_newcard)
        }

        viewModelScope.launch {
            withContext(Dispatchers.Default) {
                adapter.setData(newList)
                DiffUtil.calculateDiff(PaymentMethodDiffCallBack(oldList, newList), true)
            }.dispatchUpdatesTo(adapter)
        }
    }

    fun getBraintreeClientToken(activity: BaseActivity<*>) {
        activity.showLoading(true)
        viewModelScope.launch {
            val result = NetworkApi.getBraintreeClientToken()
            mBraintreeClientTokenLiveData.value = result
        }
    }

    /**
     * 获取订单号
     */
    fun getPaypalOrderNo(activity: BaseActivity<*>, setMealBean: SetMealBean, deviceId: String) {
        activity.showLoading(true)
        viewModelScope.launch {
//            val result =
//                NetworkApi.getPaypalOrderNo(setMealBean.mealPackage, setMealBean.packageType,
//                        setMealBean.cost.toString(), deviceId)
//            mPayPalOrderNoLiveData.value = result
        }
    }

    /**
     *@param orderStatus:0待支付 1是支付成功 2是取消支付/失败
     */
    fun updateOrderStatus(activity: BaseActivity<*>,
                          orderId: String,
                          orderStatus: Int,//0待支付 1是支付成功 2是取消支付/失败
                          deviceId: String,
                          mealDays: Int) {
        activity.showLoading(true)
        viewModelScope.launch {
            val result = NetworkApi.updateOrderStatus(orderId, orderStatus, deviceId, mealDays)
            mUpdateOrderStatusLiveData.value = result
        }
    }

    /**
     * 信用卡发起支付
     */
    fun cardPayment(activity: BaseActivity<*>,
                    mealName: String,
                    mealDays: Int,
                    totalCost: String,
                    paymentMethodNonce: String,
                    deviceId: String) {
        activity.showLoading(true)
        viewModelScope.launch {
            val result =
                NetworkApi.cardPayment(mealName, mealDays, totalCost, paymentMethodNonce, deviceId)
            mCardPaymentResultLiveData.value = result
        }
    }

    /**
     * 信用卡订阅支付
     */
    private fun cardSubscription(activity: BaseActivity<*>,
                                 userId: String,
                                 paymentMethodNonce: String,
                                 firstName: String,
                                 lastName: String,
                                 username: String,
                                 deviceId: String,
                                 setMealBean: SetMealBean) {
        activity.showLoading(true)
        viewModelScope.launch {
            val result =
                NetworkApi.cardSubscription(userId, paymentMethodNonce, firstName, lastName,
                        username, deviceId, setMealBean)
            mCardPaymentResultLiveData.value = result
        }
    }


    /**
     * 开始调起payPal支付
     */
    fun launchPayPal(activity: BaseActivity<*>,
                     braintreeClient: BraintreeClient?,
                     payPalClient: PayPalClient?,
                     setMealBean: SetMealBean?,
                     orderNo: String) {
        activity.showLoading(true)
        viewModelScope.launch(Dispatchers.IO) {
            braintreeClient?.getConfiguration { _, _ ->
                payPalClient?.apply {
//                    val payPalCheckoutRequest = PayPalCheckoutRequest("${setMealBean!!.cost}")
//                    val payPalLineItem =
//                        PayPalLineItem(PayPalLineItem.KIND_DEBIT, setMealBean.mealPackage, "1",
//                                "${setMealBean.cost}")
//                    payPalLineItem.setProductCode(orderNo)
//                    val payPalLineItems = ArrayList<PayPalLineItem>()
//                    payPalLineItems.add(payPalLineItem)
//                    payPalCheckoutRequest.currencyCode = "USD"
//                    payPalCheckoutRequest.setLineItems(payPalLineItems)
//                    tokenizePayPalAccount(activity, payPalCheckoutRequest)
                }
            }
        }
    }

    /**
     * 开始调起信用卡支付,自动订阅
     */
    fun launchCardPay(activity: BaseActivity<*>,
                      cardClient: CardClient?,
                      card: Card,
                      setMealBean: SetMealBean?,
                      deviceId: String) {
        if (null == setMealBean) return

        activity.apply {
            if (!isShowLoading()) {
                showLoading(true)
            }
        }

        val callback = CardTokenizeCallback { cardNonce, error ->
            LogUtil.e("调起信用卡支付error=${error?.message}")
            if (null != cardNonce) {
                viewModelScope.launch {
                    val nonce = cardNonce.string
                    LogUtil.e("cardNonce:$nonce")
//                    activity.showLoading(true)
//                    cardPayment(activity, setMealBean.mealPackage, setMealBean.days,
//                                setMealBean.cost.toString(), nonce, deviceId)
                    var list: List<CreditCardBean>?
                    withContext(Dispatchers.IO) {
                        list = MyDatabase.creditCardDao().findAll(MyDatabase.CREDIT_CARD_TABLE)
                    }
                    if (null != list) {
                        val userId = MMKVUtil.getString(MMKVKey.UserId)
                        val userName = MMKVUtil.getString(MMKVKey.UserName)
                        for (creditCard in list!!) {
                            if (card.number == creditCard.cardNumber) {
                                //信用卡订阅支付
                                cardSubscription(activity, userId, nonce, creditCard.firstName,
                                        creditCard.lastName, userName, deviceId, setMealBean)
                                break
                            }
                        }
                    }
                }
            } else {
                activity.apply {
                    showToast(R.string.txt_pay_fail)
                    showLoading(false)
                }
            }
        }

        viewModelScope.launch(Dispatchers.IO) {
            cardClient?.tokenize(card, callback)
        }
    }
}