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

import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.abbidot.baselibrary.constant.MMKVKey
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.baselibrary.util.MMKVUtil
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.bean.LKSimSetMealBean
import com.abbidot.tracker.bean.MenuTxtBean
import com.abbidot.tracker.bean.RechargeDeviceBean
import com.abbidot.tracker.bean.StripeSubscriptionPriceBean
import com.abbidot.tracker.database.MyDatabase
import com.abbidot.tracker.retrofit2.NetworkApi
import com.stripe.android.PaymentConfiguration
import com.stripe.android.model.CardParams
import com.stripe.android.model.ConfirmPaymentIntentParams
import com.stripe.android.model.PaymentMethodCreateParams
import com.stripe.android.payments.paymentlauncher.PaymentLauncher
import com.stripe.android.payments.paymentlauncher.PaymentResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


/**
 *Created  by .yzq on 2023/7/14/014.
 * @link
 * @description:Stripe支付
 */
class StripePalViewModel : ViewModel() {
    //服务器返回的支付凭证
    var mPaymentIntentClientSecret = ""
    private lateinit var mPaymentLauncher: PaymentLauncher

    //获取支付凭证
    val mStripePayOrderNoLiveData = MutableLiveData<Result<String>>()
    val mStripeSubscriptionLiveData = MutableLiveData<Result<String>>()

    //支付结果
    val mStripePayResultLiveData = MutableLiveData<Int>()

    /**
     * Stripe支付初始化
     */
    fun init(activity: AppCompatActivity) {
        val paymentConfiguration = PaymentConfiguration.getInstance(activity.applicationContext)
        mPaymentLauncher = PaymentLauncher.create(
            activity,
            paymentConfiguration.publishableKey,
            paymentConfiguration.stripeAccountId,
            ::onPaymentResult
        )
    }

    /**
     * 开始提交Stripe支付
     */
    fun startCheckout(activity: BaseActivity<*>, card: MenuTxtBean) {
        activity.showLoading(true)
        viewModelScope.launch(Dispatchers.IO) {
            val list = MyDatabase.creditCardDao().findAll(MyDatabase.CREDIT_CARD_TABLE)
            if (null != list) {
                for (it in list) {
                    if (card.menuName == it.cardNumber) {
                        val dates = it.expirationDate.split("/")
                        val name = "${it.lastName} ${it.firstName}"
                        val params = PaymentMethodCreateParams.createCard(
                            CardParams(
                                it.cardNumber, dates[0].toInt(), dates[1].toInt(), it.cvv, name
                            )
                        )
                        val confirmParams =
                            ConfirmPaymentIntentParams.createWithPaymentMethodCreateParams(
                                params, mPaymentIntentClientSecret
                            )
                        mPaymentLauncher.confirm(confirmParams)
                        break
                    }
                }
            }
        }
    }

    /**
     * Stripe支付结果
     */
    private fun onPaymentResult(paymentResult: PaymentResult) {
        var message = ""
        val result = when (paymentResult) {
            is PaymentResult.Completed -> {
                message = "Completed!"
                0
            }

            is PaymentResult.Canceled -> {
                message = "Canceled!"
                -1
            }

            is PaymentResult.Failed -> {
                // This string comes from the PaymentIntent's error message.
                // See here: https://stripe.com/docs/api/payment_intents/object#payment_intent_object-last_payment_error-message
                message = "Failed: " + paymentResult.throwable.message
                1
            }
        }
        LogUtil.e("Stripe支付结果：$message")
        mStripePayResultLiveData.value = result
    }

    /**
     * Stripe支付创建订阅
     */
    fun createSubscription(
        activity: BaseActivity<*>,
        lkSimSetMealBean: LKSimSetMealBean,
        stripeSubscriptionPriceBean: StripeSubscriptionPriceBean,
        rechargeDeviceBean: RechargeDeviceBean,
        partnerCode: String
    ) {
        activity.showLoading(true)
        viewModelScope.launch {
            val userId = MMKVUtil.getString(MMKVKey.UserId)
            val userName = MMKVUtil.getString(MMKVKey.UserName)
            lkSimSetMealBean.let {
                it.specAndPriceList?.run {
                    val spec = get(0)
                    val amount = (spec.discountPriceUSD * 100).toInt()
                    val result = NetworkApi.createSubscription(
                        userId,
                        it.servicePlanShowName,
                        rechargeDeviceBean.deviceId,
                        userName,
                        spec.discountPriceUSD.toString(),
                        stripeSubscriptionPriceBean.priceId,
                        stripeSubscriptionPriceBean.customerId,
                        amount.toString(),
                        partnerCode,
                        it.packageCode,
                        it.servicePlanCode,
                        spec.orderPeriod,
                        it.servicePlanShowName,
                        rechargeDeviceBean.iccid,
                        spec.autoRenewal
                    )
                    mStripeSubscriptionLiveData.value = result
                }

            }
        }
    }

    /**
     * Stripe支付取消订阅
     */
    fun cancelStripeSubscription(
        activity: BaseActivity<*>, mRechargeDeviceBean: RechargeDeviceBean
    ) {
        activity.showLoading(true)
        viewModelScope.launch {
            val result = NetworkApi.cancelStripeSubscription(
                mRechargeDeviceBean.orderId,
                mRechargeDeviceBean.subscriptionsId,
                mRechargeDeviceBean.iccid
            )
            mStripePayOrderNoLiveData.value = result
        }
    }

    /**
     * Stripe支付 Rsa算法解密测试
     */
    fun rsaDecodeTest(encryptedData: String) {
        viewModelScope.launch {
            NetworkApi.rsaDecodeTest(encryptedData)
        }
    }

    /**
     * 获取Stripe支付凭证
     * priceId 套餐的产品ID(订阅时传)
     */
    fun getStripePayOrderNo(
        activity: BaseActivity<*>,
        lkSimSetMealBean: LKSimSetMealBean,
        rechargeDeviceBean: RechargeDeviceBean,
        partnerCode: String,
        priceId: String = ""
    ) {
        activity.showLoading(true)
        viewModelScope.launch {
            val userId = MMKVUtil.getString(MMKVKey.UserId)
            val username = MMKVUtil.getString(MMKVKey.UserName)
            lkSimSetMealBean.let {
                it.specAndPriceList?.run {
                    val spec = get(0)
                    val amount = (spec.discountPriceUSD * 100).toInt()
                    val result = NetworkApi.getStripePayOrder(
                        amount.toString(),
                        userId,
                        it.servicePlanShowName,
                        rechargeDeviceBean.deviceId,
                        username,
                        spec.discountPriceUSD.toString(),
                        priceId,
                        partnerCode,
                        it.packageCode,
                        it.servicePlanCode,
                        spec.orderPeriod,
                        it.servicePlanShowName,
                        rechargeDeviceBean.iccid,
                        spec.autoRenewal
                    )
                    mStripePayOrderNoLiveData.value = result
                }

            }

        }
    }
}