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

import androidx.fragment.app.viewModels
import com.elvishew.xlog.XLog
import com.quyunshuo.androidbaseframemvvm.base.utils.RegisterEventBus
import com.quyunshuo.androidbaseframemvvm.common.constant.Heartbeat
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.HomeFragmentBillCoinBinding
import com.quyunshuo.module.home.fragment.vm.BuyFragmentVM
import com.quyunshuo.module.home.utils.OrderNumberGenerator
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.math.BigDecimal

/**
 * 纸币 硬币支付对话框
 *
 * @author Qu Yunshuo
 * @since 2021/8/1 11:46 下午
 */
@RegisterEventBus
@AndroidEntryPoint
class BillCoinFragment : BaseFragment<HomeFragmentBillCoinBinding, BuyFragmentVM>() {

    override val mViewModel: BuyFragmentVM by viewModels()
    override fun createVB() = HomeFragmentBillCoinBinding.inflate(layoutInflater)
    var sumPrice: BigDecimal? = null

    override fun HomeFragmentBillCoinBinding.initView() {
        sumPrice = BigDecimal(arguments?.getDouble("PRICE", 0.0)!!)
        XLogUtil.d("price:" + sumPrice + Heartbeat.acceptBill)
        settlement()
    }

    override fun initObserve() {
    }

    override fun initRequestData() {
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun event(message: ApiMessageEvent) {
        when (message.name) {
            PayName.ACCEPT_BILL -> {
                settlement()

            }

            else -> {}
        }
    }

    //金额结算
    private fun settlement() {
        var price = sumPrice?.subtract(Heartbeat.acceptBill)
        if (price!!.toDouble() <= 0.0) {
            //如果支付成功，通知前台。
            EventBus.getDefault().post(ApiMessageEvent(MqName.PAY_SUCCESS, PaySuccessBean(
                UiUtil.getStringRes(
                    R.string.base_bill_coin
                ), OrderNumberGenerator.generateOrderNumber()
            )))
            return
        }
        mBinding.tvRequiredPrice.text = price.toString()
    }

    //硬币也需要进行计算。
}