package com.adealink.weparty.order.qrcode

import androidx.activity.viewModels
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.updateLayoutParams
import com.adealink.frame.aab.util.getCompatString
import com.adealink.frame.base.Rlt
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.router.Router
import com.adealink.frame.router.annotation.BindExtra
import com.adealink.frame.router.annotation.RouterUri
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.BaseActivity
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.commonui.toast.util.showFailedToast
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.commonui.widget.NumberIncreaseView
import com.adealink.weparty.constant.ORDER_REMARK_MAX_LENGTH
import com.adealink.weparty.module.order.Order
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.discountLD
import com.adealink.weparty.module.order.data.getFinalPrice
import com.adealink.weparty.module.playmate.Playmate
import com.adealink.weparty.order.R
import com.adealink.weparty.order.databinding.ActivityQrcodeOrderBinding
import com.adealink.weparty.order.viewmodel.OrderViewModelFactory
import com.adealink.weparty.order.viewmodel.QRCodeOrderViewModel
import com.adealink.weparty.util.applyImmersive
import com.adealink.weparty.util.formatNumber
import com.adealink.weparty.util.formatNumberStr
import com.adealink.weparty.util.formatStar
import kotlin.math.max
import com.adealink.weparty.R as APP_R

@RouterUri(
    path = [
        Order.QRCode.PATH,
    ], desc = "二维码订单"
)
class QRCodeOrderActivity : BaseActivity() {

    private val binding by viewBinding(ActivityQrcodeOrderBinding::inflate)

    private val orderViewModel by viewModels<QRCodeOrderViewModel> { OrderViewModelFactory() }

    @BindExtra(Order.QRCode.EXTRA_CATEGORY_ID)
    var categoryId: String? = null

    @BindExtra(Order.QRCode.EXTRA_QR_CODE)
    var qrCode: String? = null

    private var orderCount = 1
    private var orderDetail: QRCodeOrderDetail? = null

    override fun onBeforeCreate() {
        super.onBeforeCreate()
        Router.bind(this)
    }

    override fun initViews() {
        super.initViews()
        setContentView(binding.root)
        applyImmersive { top ->
            binding.topBar.updateLayoutParams<ConstraintLayout.LayoutParams> {
                topMargin = top
            }
        }
        binding.vNumber.setNumber(orderCount)
        binding.vNumber.setListener(object : NumberIncreaseView.OnNumberChangedListener {
            override fun onNumberChanged(number: Int) {
                orderCount = number
                updateOrderInfo()
            }
        })
        binding.etRemarkInput.hint = getCompatString(R.string.order_remark_hint, ORDER_REMARK_MAX_LENGTH.toString())
        binding.vBottom.btnOrder.onClick {
            createOrder()
        }
    }

    override fun observeViewModel() {
        super.observeViewModel()
        discountLD.observe(this) {
            updatePrice()
        }
    }

    override fun loadData() {
        super.loadData()
        OrderModule.queryDiscountInfo()
        val qrCode = qrCode
        if (qrCode.isNullOrEmpty()) {
            showToast(R.string.order_qrcode_invalid)
            return
        }
        orderViewModel.loadQRCodeOrderDetail(qrCode).observe(this) { rlt ->
            when (rlt) {
                is Rlt.Failed -> {
                    showFailedToast(rlt)
                    goCategoryId()
                }

                is Rlt.Success -> {
                    val orderType = QRCodeOrder.map(rlt.data.type)
                    if (orderType == null) {
                        showToast(R.string.order_qrcode_invalid)
                        return@observe
                    }
                    orderDetail = rlt.data
                    updateOrderInfo()
                }
            }
        }
    }

    private fun updateOrderInfo() {
        //用户信息
        binding.ivAvatar.setImageUrl(orderDetail?.avatar)
        binding.tvUserName.text = orderDetail?.nickname
        binding.tvStar.text = formatStar(orderDetail?.star)

        //陪玩信息
        binding.ivCategory.setImageUrl(orderDetail?.categoryIcon)
        binding.tvCategory.text = orderDetail?.categoryName
        binding.tvPrice.text = formatNumberStr(orderDetail?.price ?: 0f, false)

        orderCount = orderDetail?.purchaseQty ?: 1
        if (orderDetail?.type == QRCodeOrder.COMMON_QRCODE.type) {
            binding.vNumber.gone()
            binding.tvNumber.show()
            binding.tvNumber.text = orderCount.toString()
        } else {
            binding.vNumber.show()
            binding.vNumber.setNumber(orderCount)
            binding.tvNumber.gone()
        }
        updatePrice()
    }

    private fun updatePrice(){
        val finalPrice = getFinalPrice(orderDetail?.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.vBottom.vPrice.setPrice(
                finalPrice.discountPrice + (orderDetail?.price ?: 0f) * max(orderCount - 1, 0),
                null
            )
        } else {
            binding.clDiscount.gone()
            binding.vBottom.vPrice.setPrice(
                (orderDetail?.price ?: 0f) * orderCount,
                null
            )
        }
    }

    private fun goCategoryId() {
        val categoryId = categoryId
        if (categoryId.isNullOrEmpty()) {
            return
        }
        Router.build(this, Playmate.Detail.PATH)
            .putExtra(Playmate.Detail.EXTRA_PLAYMATE_ID, categoryId)
            .start()
        finish()
    }

    private fun createOrder() {
        val orderType = QRCodeOrder.map(orderDetail?.type) ?: return
        QRCodeOrderDialog().apply {
            setData(
                orderDetail,
                if (orderType == QRCodeOrder.SPECIAL_QRCODE) {
                    orderDetail?.purchaseQty
                } else {
                    1
                },
                binding.etRemarkInput.text?.trim()?.toString()
            )
            show(supportFragmentManager, "QRCodeOrderDialog")
        }
    }

}