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

import android.content.Context
import android.content.Intent
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.abbidot.baselibrary.constant.ResultCode
import com.abbidot.baselibrary.list.BaseRecyclerAdapter
import com.abbidot.baselibrary.util.AppUtils
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.database.MyDatabase
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.ViewUtil
import com.abbidot.tracker.vm.SubscriptionPayViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


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

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

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

    override fun initData() {
        mViewBinding.apply {
            mPaymentMethodActivity = mActivity!! as PaymentMethodActivity
            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 == mPaymentMethodActivity.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)
            )

            setOnClickListenerViews(btnCreditCardPaymentAdd, btnMakePaymentCreditCard)
        }
        getCardData()
    }

    private fun getCardData() {
        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)
                }
            }
        }
    }

    fun goEditCard(cardBean: CreditCardBean) {
        Intent(mContext, AddCreditCardPaymentActivity::class.java).let {
            it.putExtra(ConstantString.Card, cardBean)
            it.putExtra(ConstantString.Edit, true)
            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 ->
                            mPaymentMethodActivity.mOrderBean?.apply {
                                customerId = o.customerId
                                mSubscriptionPayViewModel.createStripeOrder(this)
                            }
                        }
                    }

                    override fun onRequestError(exceptionCode: String?) {
                        showNoCancelableLoading(false)
                    }
                })
            }

            mCreateStripeOrderLiveData.observe(viewLifecycleOwner) {
                showNoCancelableLoading(false)
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        it.getOrNull()?.apply {
                            val intent = Intent(mContext, PaymentSuccessActivity::class.java)
                            rechargeType = mPaymentMethodActivity.mRechargeType
                            mPaymentMethodActivity.mOrderBean?.let { o ->
                                deviceId = o.deviceId
                            }
                            deviceType = mPaymentMethodActivity.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 == mPaymentMethodActivity.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.VISIBLE
        }
    }

    /**
     * 接收添加信用卡返回结果
     */
    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()
            }
        }

    private fun startCreditCardPayment() {
        val list = mCreditCardAdapter.getData()
        for (card in list) {
            if (card.checked) {
                showNoCancelableLoading(true)
                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()
            }
        }
    }
}