package com.abbidot.tracker.deprecated.ui.activity.profile.recharge

import android.content.Intent
import android.text.TextUtils
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DiffUtil
import com.abbidot.baselibrary.constant.EventName
import com.abbidot.baselibrary.constant.ResultCode
import com.abbidot.baselibrary.eventbus.XEventBus
import com.abbidot.baselibrary.list.BaseRecyclerAdapter
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.bean.CreditCardBean
import com.abbidot.tracker.bean.LKSimSetMealBean
import com.abbidot.tracker.bean.MenuTxtBean
import com.abbidot.tracker.bean.RechargeDeviceBean
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.database.MyDatabase
import com.abbidot.tracker.databinding.ActivitySelectPaymentMethodBinding
import com.abbidot.tracker.deprecated.adapter.SelectPaymentMethodAdapter
import com.abbidot.tracker.deprecated.ui.activity.vm.BraintreePalViewModel
import com.abbidot.tracker.deprecated.ui.activity.vm.StripePalViewModel
import com.abbidot.tracker.diff.PaymentMethodDiffCallBack
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.braintreepayments.api.BraintreeClient
import com.braintreepayments.api.Card
import com.braintreepayments.api.CardClient
import com.braintreepayments.api.PayPalAccountNonce
import com.braintreepayments.api.PayPalClient
import com.braintreepayments.api.PayPalListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * 选择支付方式
 */
class PaymentMethodStripeActivity :
    BaseActivity<ActivitySelectPaymentMethodBinding>(ActivitySelectPaymentMethodBinding::inflate),
    PayPalListener {

    private val mBraintreePalViewModel: BraintreePalViewModel by viewModels()
    private val mStripePalViewModel: StripePalViewModel by viewModels()

    private lateinit var mSelectPaymentMethodAdapter: SelectPaymentMethodAdapter

    //设备
    private var mRechargeDeviceBean: RechargeDeviceBean? = null

    //套餐
    private var mLKSimSetMealBean: LKSimSetMealBean? = null

    //已选中的支付方式下标
    private var mSelectPaymentMethodIndex = 0

    private var mBraintreeClient: BraintreeClient? = null

    //payPal支付
    private var mPayPalClient: PayPalClient? = null

    //信用卡支付
    private var mCardClient: CardClient? = null

    //订单号
    private var mOrderNo = ""
    private var mPartnerCode = ""

    //0待支付 1是支付成功 2是取消支付/失败
    private var mOrderStatus = 0

    //mealType套餐类型
    private var mSetMealIndex = 0

    override fun getTopBar() = mViewBinding.selectPaymentMethodBar.titleTopBar

    override fun initData() {
        super.initData()
        setTopBarTitle(R.string.txt_pay_order_method)

        intent.extras?.apply {
            mRechargeDeviceBean = Util.getParcelableAdaptive(
                intent, ConstantString.RechargeDevice, RechargeDeviceBean::class.java
            )
            mLKSimSetMealBean = Util.getParcelableAdaptive(
                intent, ConstantString.LkSetMeal, LKSimSetMealBean::class.java
            )
            mPartnerCode = getString(ConstantString.PartnerCode).toString()
            mSetMealIndex = getInt(ConstantString.SetMealIndex, 0)

            setData()

            setOnClickListenerViews(mViewBinding.sureSelectPaymentMethodBtn)

            //Stripe普通支付
            if (mLKSimSetMealBean!!.specAndPriceList!![0].autoRenewal == "0") {
                mStripePalViewModel.init(this@PaymentMethodStripeActivity)
            }
        }
    }

    private fun setData() {
        lifecycleScope.launch {

            val paymentMethodList = mutableListOf<MenuTxtBean>()

            withContext(Dispatchers.IO) {
//                ViewUtil.instance.addMenuBean(paymentMethodList, "", "", R.drawable.ico_lay_paypal)

                val list = MyDatabase.creditCardDao().findAll(MyDatabase.CREDIT_CARD_TABLE)
                list?.forEach {
                    val imageId = Util.getCreditCardType(it.cardNumber)
                    ViewUtil.instance.addMenuBean(
                        paymentMethodList, it.cardNumber, it.expirationDate, imageId
                    )
                }

                ViewUtil.instance.addMenuBean(
                    paymentMethodList,
                    getString(R.string.txt_pay_order_add_card),
                    "",
                    R.drawable.ico_lay_newcard
                )
            }

            mSelectPaymentMethodAdapter =
                SelectPaymentMethodAdapter(mContext!!, paymentMethodList, false)
            mSelectPaymentMethodAdapter.setOnItemClickListener(object :
                BaseRecyclerAdapter.OnItemClickListener {
                override fun onItemClick(itemView: View?, pos: Int) {
                    selectPaymentMethod(pos)
                }
            })
            ViewUtil.instance.setRecyclerViewVerticalLinearLayout(
                mContext!!,
                mViewBinding.paymentMethodRecyclerView,
                mSelectPaymentMethodAdapter,
                bottom = 40
            )
        }

    }

    override fun liveDataObserve() {
        /*************************Stripe支付************************************/
        mStripePalViewModel.mStripePayOrderNoLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    val clientSecret = it.getOrNull()
                    clientSecret?.let { secret ->
                        mStripePalViewModel.mPaymentIntentClientSecret = secret
                        launchStripePal()
                    }
                }
            })
        }

//        mStripePalViewModel.mStripeSubscriptionCustomerLiveData.observe(this) {
//            dealRequestResult(it, object : GetResultCallback {
//                override fun onResult(any: Any) {
//                    val data = it.getOrNull()
//                    data?.apply {
//                        mStripePalViewModel.createSubscription(
//                            this@PaymentMethodStripeActivity,
//                            mLKSimSetMealBean!!,
//                            this,
//                            mRechargeDeviceBean!!,
//                            mPartnerCode
//                        )
//                    }
//                }
//            })
//        }

        mStripePalViewModel.mStripeSubscriptionLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    val data = it.getOrNull()!!
                    if (!TextUtils.isEmpty(data)) {
                        payPalSuccess()
                    }
                }
            })
        }

        //Stripe支付结果
        mStripePalViewModel.mStripePayResultLiveData.observe(this) {
            showLoading(false)
            it?.apply {
                when (it) {
                    0 -> payPalSuccess()
                    1 -> payPalFail()
                    -1 -> {
                        showToast(R.string.txt_user_canceled_paypal, true)
                    }
                }
            }
        }
        /*************************Stripe支付************************************/

        mBraintreePalViewModel.mPayPalOrderNoLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    mOrderNo = it.getOrNull()!!.orderNo
                    mBraintreePalViewModel.getBraintreeClientToken(this@PaymentMethodStripeActivity)
                }
            })
        }

        /**
         * 获取Braintree客户端令牌key
         */
        mBraintreePalViewModel.mBraintreeClientTokenLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    val data = it.getOrNull()!!
                    lifecycleScope.launch {
                        withContext(Dispatchers.IO) {
                            if (null == mBraintreeClient) {
                                //显示支付 UI 之前，使用您的令牌化密钥初始化 SDK
                                mBraintreeClient = BraintreeClient(mContext!!, data.tokenId)
                            }
                        }
                        if (null != mBraintreeClient) {
                            if (mSelectPaymentMethodIndex == 0) {
                                launchPayPal()
                            } else {
                                launchCardPay()
                            }
                        } else {
                            showToast(R.string.txt_pay_fail)
                        }
                    }
                }
            }, showLoading = true)
        }

        XEventBus.observe(this, EventName.PayBack) {
            finish()
        }

        /**
         * 更新订单
         */
        mBraintreePalViewModel.mUpdateOrderStatusLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    if (mOrderStatus == 1) {
                        payPalSuccess()
                    } else {
                        payPalFail()
                    }
                }
            })
        }

        //信用卡支付成功
        mBraintreePalViewModel.mCardPaymentResultLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    val data = it.getOrNull()!!
                    if (!TextUtils.isEmpty(data)) {
                        payPalSuccess()
//                        if (data == ErrorCode.CREDIT_CARD_PAY_SUCCESS.toString()) {
//                            payPalSuccess()
//                        } else {
//                            payPalFail()
//                        }
                    }
                }
            })
        }
    }

    override fun onNewIntent(newIntent: Intent) {
        super.onNewIntent(newIntent)
        // required if your activity's launch mode is "singleTop", "singleTask", or "singleInstance"
        intent = newIntent
    }

    /**
     * 选择一种支付方式
     */
    private fun selectPaymentMethod(pos: Int) {
        val oldList = mSelectPaymentMethodAdapter.getData()
        //处理最后一个选项 直接添跳转加信用卡
        if (pos == oldList.size - 1) {
            val intent = Intent(mContext, AddCreditCardActivity::class.java)
            launchActivity(mActivityResultLauncher, intent)
            return
        }
        if (oldList[pos].isSwitch) {
            return
        }

        val newList = mutableListOf<MenuTxtBean>()
        oldList.forEach {
            ViewUtil.instance.addMenuBean(
                newList, it.menuName, it.menuValue, it.imageId, isSwitch = it.isSwitch
            )
        }
        newList[mSelectPaymentMethodIndex].isSwitch = false
        newList[pos].isSwitch = true
        mSelectPaymentMethodIndex = pos
        //更新选中的某个支付方式
        lifecycleScope.launch {
            withContext(Dispatchers.Default) {
                mSelectPaymentMethodAdapter.setData(newList)
                DiffUtil.calculateDiff(PaymentMethodDiffCallBack(oldList, newList), true)
            }.dispatchUpdatesTo(mSelectPaymentMethodAdapter)
        }
    }

    /**
     * 接收添加信用卡返回结果
     */
    private val mActivityResultLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (null != it.data) {
                if (it.resultCode == ResultCode.ResultCode_1) {
                    val card = Util.getParcelableAdaptive(
                        it.data!!, ConstantString.Card, CreditCardBean::class.java
                    )
                    if (null != card) {
                        mBraintreePalViewModel.addCreditCard(
                            this, card, mSelectPaymentMethodAdapter
                        )
                    }
                }
            }
        }


    /**
     * 确认支付
     */
    private fun surePay() {
        val list = mSelectPaymentMethodAdapter.getData()
        var selectPaymentMethodIndex = -1
        for (i in 0 until list.size) {
            if (list[i].isSwitch) {
                selectPaymentMethodIndex = i
                break
            }
        }

        if (selectPaymentMethodIndex == -1) {
            showToast(R.string.txt_select_payment_method)
            return
        }
        mSelectPaymentMethodIndex = selectPaymentMethodIndex

        //判断是Stripe普通支付还是自动订阅
        if (mLKSimSetMealBean!!.specAndPriceList!![0].autoRenewal == "0") {
            //普通支付
            mStripePalViewModel.getStripePayOrderNo(
                this, mLKSimSetMealBean!!, mRechargeDeviceBean!!, mPartnerCode
            )
        } else {
            //自动订阅
            val card = mSelectPaymentMethodAdapter.getData()[mSelectPaymentMethodIndex]
//            mStripePalViewModel.createCustomer(this, card, mSetMealIndex + 1)
        }


//        if (mSelectPaymentMethodIndex == 0) {
//            mBraintreePalViewModel.getPaypalOrderNo(
//                this, mSetMealBean!!, mRechargeDeviceBean!!.deviceId
//            )
//        } else {
//            //信用卡支付不需要订单号
//            mBraintreePalViewModel.getBraintreeClientToken(this@PaymentMethodStripeActivity)
//        }
    }

    /**
     * 开始PayPal支付
     */
    private fun launchPayPal() {
        if (null == mPayPalClient) {
            mPayPalClient = PayPalClient(this, mBraintreeClient!!)
            mPayPalClient!!.setListener(this)
        }
//        mBraintreePalViewModel.launchPayPal(
//            this, mBraintreeClient, mPayPalClient, mSetMealBean, mOrderNo
//        )
    }

    /**
     * 开始信用卡支付
     */
    private fun launchCardPay() {
        lifecycleScope.launch {
            withContext(Dispatchers.IO) {
                if (null == mCardClient) {
                    mCardClient = CardClient(mBraintreeClient!!)
                }
            }
            val creditCardBean = mSelectPaymentMethodAdapter.getData()[mSelectPaymentMethodIndex]
            val card = Card()
            card.number = creditCardBean.menuName
            card.expirationDate = creditCardBean.menuValue
            card.countryCode = "USA"
//            mBraintreePalViewModel.launchCardPay(
//                this@PaymentMethodStripeActivity,
//                mCardClient,
//                card,
//                mSetMealBean,
//                mRechargeDeviceBean!!.deviceId
//            )
        }
    }

    /**
     * 开始Stripe普通支付
     */
    private fun launchStripePal() {
        val card = mSelectPaymentMethodAdapter.getData()[mSelectPaymentMethodIndex]
        mStripePalViewModel.startCheckout(this, card)
    }

    /**
     * 支付成功
     */
    private fun payPalSuccess() {
        val intent = Intent(mContext!!, PaymentResultActivity::class.java)
        intent.putExtra(
            ConstantString.Amount, mLKSimSetMealBean!!.specAndPriceList!![0].discountPriceUSD
        )
        intent.putExtra(ConstantString.Type,  ConstantInt.Type1)
        startActivityFinish(intent)
    }

    /**
     * 支付失败
     */
    private fun payPalFail() {
        val intent = Intent(mContext!!, PaymentResultActivity::class.java)
        intent.putExtra(ConstantString.Type,  ConstantInt.Type2)
        startActivity(intent)
    }

    /**
     * PayPal支付回调
     */
    override fun onPayPalSuccess(payPalAccountNonce: PayPalAccountNonce) {
        LogUtil.e("PayPal支付成功${payPalAccountNonce}")
        mOrderStatus = 1
////        showToast(R.string.txt_pay_success)
//        mBraintreePalViewModel.updateOrderStatus(
//            this, mOrderNo, mOrderStatus, mRechargeDeviceBean!!.deviceId, mSetMealBean!!.days
//        )
    }

    /**
     * PayPal支付回调
     */
    override fun onPayPalFailure(error: Exception) {
        val message = error.message
        mOrderStatus = 2
        LogUtil.e("PayPal支付失败$message")
////        if (message?.contains("cancel") == true) {
////            showToast(R.string.txt_user_canceled_paypal)
////        } else {
////            showToast(R.string.txt_pay_fail)
////        }
//        mBraintreePalViewModel.updateOrderStatus(
//            this, mOrderNo, mOrderStatus, mRechargeDeviceBean!!.deviceId, mSetMealBean!!.days
//        )
    }

    override fun onClick(v: View?) {
        when (v!!) {
            mViewBinding.sureSelectPaymentMethodBtn -> {
                surePay()
            }
        }
    }
}