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

import android.content.Context
import android.content.Intent
import android.view.View
import androidx.fragment.app.viewModels
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseFragment
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.FragmentPaypalPaymentBinding
import com.abbidot.tracker.ui.activity.WebViewActivity
import com.abbidot.tracker.ui.activity.subscribe.PaymentMethodActivity
import com.abbidot.tracker.vm.SubscriptionPayViewModel


/**
 * Paypal支付方式
 */
class PaypalPaymentFragment :
    BaseFragment<FragmentPaypalPaymentBinding>(FragmentPaypalPaymentBinding::inflate) {

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

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

    override fun initData() {
        mPaymentMethodActivity = mActivity!! as PaymentMethodActivity
        mViewBinding.apply {
            root.setBackgroundResource(R.color.transparent)
            setOnClickListenerViews(btnSureRedirectPaypal)
        }
    }

    override fun liveDataObserve() {
        mSubscriptionPayViewModel.mCreatePaypalOrderLiveData.observe(viewLifecycleOwner) {
            showNoCancelableLoading(false)
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    it.getOrNull()?.apply {
                        val intent = Intent(mContext, WebViewActivity::class.java)
                        intent.putExtra(
                            ConstantString.Title, getString(R.string.txt_pay_order_payment_title)
                        )
                        intent.putExtra(ConstantString.Url, url)
                        rechargeType = mPaymentMethodActivity.mRechargeType
                        deviceType = mPaymentMethodActivity.mType
                        mPaymentMethodActivity.mOrderBean?.let { o ->
                            deviceId = o.deviceId
                        }
                        intent.putExtra(ConstantString.Amount, this)

                        mPaymentMethodActivity.startActivity(intent)
                    }
                }
            })
        }
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                btnSureRedirectPaypal -> mPaymentMethodActivity.mOrderBean?.let {
                    showNoCancelableLoading(true)
                    mSubscriptionPayViewModel.createPaypalOrder(it)
                }
            }
        }
    }
}