package com.adealink.weparty.order.qrcode

import android.annotation.SuppressLint
import androidx.fragment.app.viewModels
import com.adealink.frame.aab.util.getCompatString
import com.adealink.frame.base.Rlt
import com.adealink.frame.base.fastLazy
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.router.Router
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.commonui.widget.BottomDialogFragment
import com.adealink.weparty.module.im.IM
import com.adealink.weparty.module.order.OrderModule
import com.adealink.weparty.module.order.data.QRCodeOrder
import com.adealink.weparty.module.order.data.QRCodeOrderDetail
import com.adealink.weparty.module.order.data.getFinalPrice
import com.adealink.weparty.module.wallet.WalletModule
import com.adealink.weparty.module.wallet.data.Currency
import com.adealink.weparty.order.R
import com.adealink.weparty.order.databinding.DialogQrcodeCreateOrderBinding
import com.adealink.weparty.order.viewmodel.OrderViewModelFactory
import com.adealink.weparty.order.viewmodel.QRCodeOrderViewModel
import com.adealink.weparty.util.formatNumber
import com.adealink.weparty.util.formatNumberStr
import kotlin.math.max
import com.adealink.weparty.R as APP_R

class QRCodeOrderDialog : BottomDialogFragment(R.layout.dialog_qrcode_create_order) {

    private var orderData: QRCodeOrderDetail? = null

    private var orderCount: Int? = null

    private var remark: String? = null

    private val binding by viewBinding(DialogQrcodeCreateOrderBinding::bind)

    private val qrCodeViewModel by viewModels<QRCodeOrderViewModel> { OrderViewModelFactory() }
    private val walletViewModel by fastLazy { WalletModule.getWalletViewModel(requireActivity()) }


    fun setData(
        orderData: QRCodeOrderDetail?,
        orderCount: Int?,
        remark: String?
    ) {
        this.orderData = orderData
        this.orderCount = orderCount
        this.remark = remark
    }

    @SuppressLint("SetTextI18n")
    override fun initViews() {
        super.initViews()
        binding.tvCategory.text = orderData?.categoryName
        binding.ivAvatar.setImageUrl(orderData?.avatar)
        binding.tvName.text = orderData?.nickname

        binding.tvPrice.text =
            "${formatNumberStr((orderData?.price ?: 0f), false)}/${orderData?.unit ?: ""}"
        binding.tvCount.show()
        binding.tvCount.text = orderCount.toString()

        binding.tvRemarkInput.setText(remark)
        binding.btnPay.onClick {
            pay()
        }
        updatePrice()
    }

    private fun updatePrice(){

        val finalPrice = getFinalPrice(orderData?.price)
        if (finalPrice.hasDiscount()) {
            binding.clDiscount.show()
            binding.vDiscount.text = getCompatString(
                APP_R.string.common_price_discount_new_only,
                formatNumber(finalPrice.discountPercent, true)
            )
            binding.vPriceDiscount.setDiscount(
                -finalPrice.discount, null
            )
            //首单第一个免费
            binding.tvTotalDetail.text = formatNumberStr(
                finalPrice.discountPrice +
                        (orderData?.price ?: 0f) * max((orderCount ?: 0) - 1, 0), false
            )

        } else {
            binding.clDiscount.gone()
            binding.tvTotalDetail.text = formatNumberStr(
                (orderData?.price ?: 0f) * (orderCount ?: 0), false
            )
        }
    }

    override fun observeViewModel() {
        super.observeViewModel()
        walletViewModel?.coinLD?.observe(viewLifecycleOwner) {
            binding.tvWalletCoin.text = formatNumberStr(it, false)
        }
    }

    override fun loadData() {
        super.loadData()
        OrderModule.queryDiscountInfo()
        walletViewModel?.refreshWalletData()
    }

    private fun pay() {
        val playmateData = orderData ?: return
        val orderType = QRCodeOrder.map(playmateData.type) ?: return
        //检查余额
        val coinBalance = WalletModule.getBalance(Currency.COIN)
        val totalPrice = playmateData.price * (orderCount ?: 0)
        if (coinBalance < totalPrice) {
            //余额不足
            WalletModule.showRechargeDialog(childFragmentManager, Currency.COIN)
            return
        }
        showLoading()
        qrCodeViewModel.pay(
            playmateData.qrCode,
            orderType,
            orderCount,
            remark
        ).observe(this) { rlt ->
            dismissLoading()
            when (rlt) {
                is Rlt.Failed -> {
                    showToast(rlt)
                }

                is Rlt.Success -> {
                    handleOrderSuccess(playmateData)
                }
            }
        }
    }

    private fun handleOrderSuccess(data: QRCodeOrderDetail) {
        val activity = activity ?: return
        Router.build(activity, IM.Session.PATH)
            .putExtra(IM.Session.EXTRA_CHAT_ID, data.uid)
            .start()
        activity.finish()
    }

}