package com.abbidot.tracker.ui.fragment.subscribe

import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.viewModels
import com.abbidot.baselibrary.constant.ResultCode
import com.abbidot.baselibrary.list.BaseRecyclerAdapter
import com.abbidot.baselibrary.util.AppUtils
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.tracker.R
import com.abbidot.tracker.adapter.CreditCardAdapter
import com.abbidot.tracker.base.BaseFragment
import com.abbidot.tracker.bean.CreditCardBean
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.FragmentCreditCardPaymentBinding
import com.abbidot.tracker.ui.activity.subscribe.AddCreditCardPaymentActivity
import com.abbidot.tracker.ui.activity.subscribe.PaymentMethodActivity
import com.abbidot.tracker.ui.activity.subscribe.PaymentSuccessActivity
import com.abbidot.tracker.util.ThirdPartyUtil
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.vm.SubscriptionPayViewModel
import com.stripe.android.ApiResultCallback
import com.stripe.android.Stripe
import com.stripe.android.model.PaymentMethod
import com.stripe.android.model.PaymentMethodCreateParams


/**
 * 选择信用卡支付
 */
class CreditCardPaymentFragment : BaseFragment<FragmentCreditCardPaymentBinding>(
    FragmentCreditCardPaymentBinding::inflate
) {

    private val mSubscriptionPayViewModel: SubscriptionPayViewModel by viewModels()
    private lateinit var mCreditCardAdapter: CreditCardAdapter

    companion object {
        @JvmStatic
        fun newInstance(context: Context) = CreditCardPaymentFragment().apply {
            mContext = context
        }
    }

    override fun initData() {
        mViewBinding.apply {
            root.setBackgroundResource(R.color.transparent)
            mCreditCardAdapter = CreditCardAdapter(mContext!!, null).apply {
                setOnAgainClickListener(object : BaseRecyclerAdapter.OnAgainClickListener {
                    override fun onAgainListener() {
                        val intent = Intent(mContext, AddCreditCardPaymentActivity::class.java)
                        launchActivity(mActivity!!, mActivityResultLauncher, intent)
                    }
                })

                setOnItemClickListener(object : BaseRecyclerAdapter.OnItemClickListener {
                    override fun onItemClick(itemView: View?, pos: Int) {
                        val card = getData()[pos]
                        //卡管理 不需要点击效果
                        if (null == getHostActivity(PaymentMethodActivity::class.java)?.mOrderBean) {
                            goEditCard(card)
                        } else {
                            if (card.checked) return
                            for (i in 0 until getData().size) {
                                val data = getData()[i]
                                if (data.checked) {
                                    data.checked = false
                                    notifyItemChanged(i)
                                    break
                                }
                            }
                            getData()[pos].checked = true
                            notifyItemChanged(pos)
                        }
                    }
                })
            }
            ViewUtil.instance.setRecyclerViewVerticalLinearLayout(
                mContext!!, rvCreditCardPaymentList, mCreditCardAdapter, top = AppUtils.dpToPx(10)
            )

            ilCreditCardPaymentNoData.btnSureSubscribePlan1Continue.visibility = View.GONE
            setOnClickListenerViews(btnCreditCardPaymentAdd, btnMakePaymentCreditCard)
        }
//        getCardData()
    }

    fun getCardData(stripeMethodInfo: CreditCardBean) {
        if (TextUtils.isEmpty(stripeMethodInfo.lastFourNumber)) {
//            viewLifecycleOwner.lifecycleScope.launch(Dispatchers.IO) {
//                val list = MyDatabase.creditCardDao().findAll(MyDatabase.CREDIT_CARD_TABLE)
//                list?.let {
//                    mActivity?.runOnUiThread {
//                        val sortedByList =
//                            list.sortedByDescending { l -> l.isPrimary }.toMutableList()
//                        setCheckAndPrimaryState(sortedByList)
//                        mCreditCardAdapter.setData(sortedByList, true)
//                    }
//                }
//            }
            //没有卡，显示无卡提示 不用去添加卡
            mViewBinding.apply {
                if (null == getHostActivity(PaymentMethodActivity::class.java)?.mOrderBean) {
                    ilCreditCardPaymentNoData.root.visibility = View.VISIBLE
                    rvCreditCardPaymentList.visibility = View.GONE
                } else {
                    ilCreditCardPaymentNoData.root.visibility = View.GONE
                    rvCreditCardPaymentList.visibility = View.VISIBLE
                }
            }

        } else {
            stripeMethodInfo.apply {
                expirationDate = "$expMonth/$expYear"
                cardNumber = lastFourNumber
                cardName = "****"
                cvv = "****"
            }
            mViewBinding.apply {
                tvCreditCardPaymentChoose.visibility = View.VISIBLE
                btnCreditCardPaymentAdd.visibility = View.INVISIBLE
                //卡管理 不需要点击效果
                if (null == getHostActivity(PaymentMethodActivity::class.java)?.mOrderBean) {
                    btnMakePaymentCreditCard.visibility = View.GONE
                } else {
                    stripeMethodInfo.checked = true
                    btnMakePaymentCreditCard.visibility = View.VISIBLE
                }
            }
            mutableListOf<CreditCardBean>().apply {
                add(stripeMethodInfo)
                mCreditCardAdapter.setData(this, true)
            }
            mViewBinding.ilCreditCardPaymentNoData.root.visibility = View.GONE
            ViewUtil.instance.viewShow(mViewBinding.rvCreditCardPaymentList)
        }
    }

    fun goEditCard(cardBean: CreditCardBean) {
        Intent(mContext, AddCreditCardPaymentActivity::class.java).let {
            it.putExtra(ConstantString.Card, cardBean)
            it.putExtra(ConstantString.Edit, true)
            //是否存在PaymentMethodID
            var isHavePaymentMethodID = false
            getHostActivity(PaymentMethodActivity::class.java)?.let { h ->
                isHavePaymentMethodID =
                    !(null == h.mPaymentIDBean || TextUtils.isEmpty(h.mPaymentIDBean?.stripeMethodInfo?.lastFourNumber))
            }
            it.putExtra(ConstantString.isCheck, isHavePaymentMethodID)
            launchActivity(mActivity!!, mActivityResultLauncher, it)
        }
    }

    override fun liveDataObserve() {
        mSubscriptionPayViewModel.apply {
            mSubscriptionCustomerLiveData.observe(viewLifecycleOwner) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        it.getOrNull()?.let { o ->
                            getHostActivity(PaymentMethodActivity::class.java)?.mOrderBean?.apply {
                                customerId = o.customerId
                                mSubscriptionPayViewModel.createStripeOrder(this)
                            }
                        }
                    }

                    override fun onRequestError(exceptionCode: String?) {
                        showNoCancelableLoading(false)
                    }
                }, isShowNetCodeMsg = true)
            }

            mCreateStripeOrderLiveData.observe(viewLifecycleOwner) {
                showNoCancelableLoading(false)
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        it.getOrNull()?.apply {
                            getHostActivity(PaymentMethodActivity::class.java)?.let { p ->
                                val intent = Intent(mContext, PaymentSuccessActivity::class.java)
                                rechargeType = p.mRechargeType
                                p.mOrderBean?.let { o ->
                                    deviceId = o.deviceId
                                }
                                deviceType = p.mType
                                intent.putExtra(ConstantString.Amount, this)
                                startActivity(intent)
                            }
                        }
                    }
                })
            }
        }
    }

    private fun setCheckAndPrimaryState(list: MutableList<CreditCardBean>) {
        if (list.size == 0) {
            mViewBinding.apply {
                tvCreditCardPaymentChoose.visibility = View.GONE
                btnCreditCardPaymentAdd.visibility = View.GONE
            }
            return
        }
        //卡管理 不需要点击效果
        if (null == getHostActivity(PaymentMethodActivity::class.java)?.mOrderBean) {
            mViewBinding.btnMakePaymentCreditCard.visibility = View.GONE
        } else {
            var haveCheck = false
            for (l in list) {
                if (l.checked) {
                    haveCheck = true
                    break
                }
            }
            if (!haveCheck) {
                list[0].checked = true
            }
            mViewBinding.btnMakePaymentCreditCard.visibility = View.VISIBLE
        }
        mViewBinding.apply {
            tvCreditCardPaymentChoose.visibility = View.VISIBLE
            btnCreditCardPaymentAdd.visibility = View.INVISIBLE
        }
    }

    /**
     * 接收添加信用卡返回结果
     */
    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) {
//                        val list = mCreditCardAdapter.getData()
//                        if (card.isPrimary) {
//                            for (l in list) {
//                                if (l.isPrimary) l.isPrimary = false
//                                if (l.checked) l.checked = false
//                            }
//                        }
//                        list.add(card)
//                        val sortedByList =
//                            list.sortedByDescending { l -> l.isPrimary }.toMutableList()
//                        setCheckAndPrimaryState(sortedByList)
//                        mCreditCardAdapter.setData(sortedByList, true)
//                    }
//                }
//            }
            if (it.resultCode == ResultCode.ResultCode_1) {
//                getCardData()
                if (null != it.data) {
                    val card = Util.getParcelableAdaptive(
                        it.data!!, ConstantString.Card, CreditCardBean::class.java
                    )
                    if (null != card) {
                        val list = mutableListOf<CreditCardBean>()
                        list.add(card)
                        setCheckAndPrimaryState(list)
                        mCreditCardAdapter.setData(list, true)
                    } else getHostActivity(PaymentMethodActivity::class.java)?.getUserPaymentMethodID()
                } else {
                    getHostActivity(PaymentMethodActivity::class.java)?.getUserPaymentMethodID()
                }
            }
        }

//    fun showCard(stripeMethodInfo: CreditCardBean){
//        stripeMethodInfo.apply {
//            expirationDate="$expMonth/$expYear"
//            cardNumber=lastFourNumber
//        }
//        mutableListOf<CreditCardBean>().apply {
//
//        }
//        mCreditCardAdapter.setData(sortedByList, true)
//    }

    private fun startCreditCardPayment() {
        getHostActivity(PaymentMethodActivity::class.java)?.let {
            val list = mCreditCardAdapter.getData()
            for (card in list) {
                if (card.checked) {
                    showNoCancelableLoading(true)
                    if (null == it.mPaymentIDBean || TextUtils.isEmpty(it.mPaymentIDBean?.stripeMethodInfo?.lastFourNumber)) {
                        val dates = card.expirationDate.split("/")
                        // 用 PaymentMethodCreateParams 封装银行卡，不再直接new Card
                        val cardParams =
                            PaymentMethodCreateParams.Card.Builder().setNumber(card.cardNumber)
                                .setExpiryMonth(dates[0].toInt()).setExpiryYear(dates[1].toInt())
                                .setCvc(card.cvv).build()
                        val paymentMethodParams = PaymentMethodCreateParams.create(cardParams)
                        val stripeKey = ThirdPartyUtil.instance.getStripeKey(mContext!!)
                        LogUtil.e("支付stripeKey=$stripeKey")
                        Stripe(mContext!!, stripeKey).createPaymentMethod(
                            paymentMethodParams,
                            callback = object : ApiResultCallback<PaymentMethod> {
                                override fun onError(e: Exception) {
                                    var message = e.message
                                    if (null == message || TextUtils.isEmpty(message)) message =
                                        getString(R.string.txt_missing_param)
                                    showToast(message)
                                    showNoCancelableLoading(false)
                                    LogUtil.e("ApiResultCallback,${e.message}")
                                }

                                override fun onSuccess(result: PaymentMethod) {
                                    LogUtil.e(result.toString())
                                    val paymentMethodID = "${result.id}"
                                    mSubscriptionPayViewModel.createCustomer(card, paymentMethodID)
                                }
                            })
                    } else {
                        mSubscriptionPayViewModel.createCustomer(card, "")
                    }
                    break
                }
            }

        }
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                btnCreditCardPaymentAdd -> {
                    val intent = Intent(mContext, AddCreditCardPaymentActivity::class.java)
                    launchActivity(mActivity!!, mActivityResultLauncher, intent)
                }

                btnMakePaymentCreditCard -> startCreditCardPayment()
            }
        }
    }
}