package com.quyunshuo.module.home.fragment.fragment.pay

import android.util.Log
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.module.pay.nayax.CreditCardMessage
import com.module.pay.nayax.CreditCardPresenter
import com.quyunshuo.androidbaseframemvvm.base.utils.RegisterEventBus
import com.quyunshuo.androidbaseframemvvm.base.utils.SpUtils
import com.quyunshuo.androidbaseframemvvm.common.bean.ShoppingCartBean
import com.quyunshuo.androidbaseframemvvm.common.constant.Heartbeat
import com.quyunshuo.androidbaseframemvvm.common.constant.MMKVName
import com.quyunshuo.androidbaseframemvvm.common.constant.MqName
import com.quyunshuo.androidbaseframemvvm.common.constant.PayName
import com.quyunshuo.androidbaseframemvvm.common.constant.event.ApiMessageEvent
import com.quyunshuo.androidbaseframemvvm.common.ui.BaseFragment
import com.quyunshuo.androidbaseframemvvm.common.util.UiUtil
import com.quyunshuo.androidbaseframemvvm.common.util.XLogUtil
import com.quyunshuo.module.home.R
import com.quyunshuo.module.home.databinding.HomeFragmentNayaxCardBinding
import com.quyunshuo.module.home.fragment.vm.BuyFragmentVM
import com.quyunshuo.module.home.utils.OrderNumberGenerator
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Nayax 刷卡支付
 *
 * @author Qu Yunshuo
 * @since 2021/8/1 11:46 下午
 */
@RegisterEventBus
@AndroidEntryPoint
class NayaxCardFragment : BaseFragment<HomeFragmentNayaxCardBinding, BuyFragmentVM>() {

    override val mViewModel: BuyFragmentVM by viewModels()
    override fun createVB() = HomeFragmentNayaxCardBinding.inflate(layoutInflater)
    var cardPresenter = CreditCardPresenter.getCreditCardContract()
    private var selectPro: String? = null//传递过来的购物车内容

    var price = 0.0
    override fun HomeFragmentNayaxCardBinding.initView() {
        //如果没有通讯，先打开通讯
        if (!cardPresenter.is_ready) {
            cardPresenter.startCommunication(4)
        }
        if (cardPresenter.is_ready){
            cardPresenter.startThreadTimer()
        }
        selectPro = arguments?.getString("SELECT_PRO")
        val arrayList: ArrayList<ShoppingCartBean> = Gson().fromJson(
            selectPro,
            object : TypeToken<ArrayList<ShoppingCartBean?>?>() {}.type
        )

        arrayList.forEach {
            price += it.count * it.price
        }
        //发起交易
        cardPresenter.setNameAndPrice(price * 100, 0)
        if (SpUtils.getBoolean(MMKVName.NAYAX_MODE, false)!!) {
            cardPresenter.vendRequest();

        }
        val cardText = SpUtils.getString(MMKVName.CARD_TEXT, "")
        if (cardText != "") {
            tvCardTips1.text = cardText
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
    }

    fun canselPay() {
        //如果是支付成功，那么取消肯定是没有的。
        //取消信用卡的本次操作
        if (cardPresenter.is_ready()) {
            cardPresenter.CanselSession()
        }
    }

    override fun initObserve() {
    }

    override fun initRequestData() {

    }

    /*
    1. 点击取消的时候发送一个event，这样统一一点，因为mdb刷卡器也可以取消，nayax也可以取消。。
    2. 或者内部区分，，no no no no no
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun event(message: ApiMessageEvent) {
        when (message.name) {
            PayName.CANCEL_PAY -> {
                canselPay()
            }

            else -> {}
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun event(message: CreditCardMessage) {
        when (message.type) {
            CreditCardMessage.Type.invalid -> {
                //卡无效或者余额不足的情况。 取消也会调用。
//                payChooseDialogFragment?.dismiss()
            }

            CreditCardMessage.Type.success -> {
                cardPresenter.nayaxCashSale((price * 100).toInt(), 0)
                //支付成功
                //如果支付成功，通知前台。
                EventBus.getDefault().post(
                    ApiMessageEvent(
                        MqName.PAY_SUCCESS, PaySuccessBean(
                            UiUtil.getStringRes(
                                R.string.base_nayax
                            ), OrderNumberGenerator.generateOrderNumber()
                        )
                    )
                )
            }

            else -> {}
        }
    }

}