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.module.pay.strategy.PaySendDataFactory
import com.module.pay.strategy.StrategyType
import com.quyunshuo.androidbaseframemvvm.base.ktx.setVisible
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.HomeFragmentMdbCardBinding
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.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

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

    override val mViewModel: BuyFragmentVM by viewModels()
    override fun createVB() = HomeFragmentMdbCardBinding.inflate(layoutInflater)
    private var selectPro:String?= null//传递过来的购物车内容
    var createStrategy = PaySendDataFactory.createStrategy(StrategyType.MDB)
    var productNumber ="0"
    var price = 0.0

    override fun HomeFragmentMdbCardBinding.initView() {
        selectPro = arguments?.getString("SELECT_PRO")
        val arrayList: ArrayList<ShoppingCartBean> = Gson().fromJson(
            selectPro,
            object : TypeToken<ArrayList<ShoppingCartBean?>?>() {}.type
        )

        arrayList.forEach {
            price+= it.count * it.price
            productNumber = it.index.toString()
        }
        //发起交易
        createStrategy.creditCardPay(price,productNumber)
        XLogUtil.d("发起交易：$price")

        tvReset.setOnClickListener {
            createStrategy.creditCardPay(price,productNumber)
            tvReset.setVisible(false)
            ivCardIcon.setVisible(true)
            tvCardTips1.setVisible(true)
            tvCardTips2.setVisible(true)

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

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

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

    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()
            }
            PayName.MDB_CARD_SUCCESS->{
                CoroutineScope(Dispatchers.IO).launch {
                    createStrategy.creditCardVendSuccess(productNumber)
                    delay(500)
                    createStrategy.creditCardSessionComplete()
                    delay(500)
                    createStrategy.creditCardCashSale(price,productNumber)
                    EventBus.getDefault().post(ApiMessageEvent(MqName.PAY_SUCCESS, PaySuccessBean(
                        UiUtil.getStringRes(
                            R.string.base_mdb_no_cash
                        ), OrderNumberGenerator.generateOrderNumber()
                    )))

                }

            }
            PayName.MDB_CARD_DENIED->{
                mBinding.tvReset.setVisible(true)
                mBinding.ivCardIcon.setVisible(false)
                mBinding.tvCardTips1.setVisible(false)
                mBinding.tvCardTips2.setVisible(false)
            }
            else -> {}
        }
    }


}