package com.adealink.weparty.order

import android.os.Bundle
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.base.fastLazy
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.widget.BottomDialogFragment
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.discountLD
import com.adealink.weparty.module.order.data.getFinalPrice
import com.adealink.weparty.module.playmate.PlaymateModule
import com.adealink.weparty.module.playmate.data.PlaymateDetailData
import com.adealink.weparty.order.databinding.ActivityCreateOrderBinding
import com.adealink.weparty.order.dialog.EditRemarkDialog
import com.adealink.weparty.order.viewmodel.OrderViewModel
import com.adealink.weparty.order.viewmodel.OrderViewModelFactory
import com.adealink.weparty.util.applyImmersive
import com.adealink.weparty.util.formatNumber
import com.adealink.weparty.util.formatStar
import kotlin.math.max
import com.adealink.weparty.R as APP_R

@RouterUri(path = [Order.Create.PATH], desc = "创建订单")
class CreateOrderActivity : BaseActivity() {

    private val binding by viewBinding(ActivityCreateOrderBinding::inflate)

    private val playmateViewModel by fastLazy { PlaymateModule.getPlaymateViewModel(this) }
    private val viewModel by viewModels<OrderViewModel> { OrderViewModelFactory() }

    @BindExtra(Order.Create.EXTRA_PLAYMATE)
    var playmateData: PlaymateDetailData? = null

    @BindExtra(Order.Create.EXTRA_PLAYMATE_ID)
    var playmateId: String? = null

    @BindExtra(Order.Create.EXTRA_PLAYMATE_COUNT)
    var orderCount = 1

    private var remark: String? = 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
                updatePlaymateInfo()
            }
        })
        binding.tvRemarkInput.hint =
            getCompatString(R.string.order_remark_hint, ORDER_REMARK_MAX_LENGTH.toString())
        binding.tvRemarkInput.onClick {
            showEditRemarkDialog()
        }
        binding.vBottom.btnOrder.onClick {
            createOrder()
        }
    }

    override fun observeViewModel() {
        super.observeViewModel()
        viewModel.onOrderCreatedLD.observeWithoutCache(this) {
            finish()
        }
        discountLD.observe(this) {
            updatePrice()
        }
    }

    override fun loadData() {
        super.loadData()
        OrderModule.queryDiscountInfo()
        val playmateData = playmateData
        val playmateId = playmateId
        if (playmateData != null) {
            updatePlaymateInfo()
        } else if (!playmateId.isNullOrEmpty()) {
            playmateViewModel?.loadPlaymateDetail(playmateId)?.observe(this) { rlt ->
                when (rlt) {
                    is Rlt.Failed -> {
                        showFailedToast(rlt)
                    }

                    is Rlt.Success -> {
                        this@CreateOrderActivity.playmateData = rlt.data
                        updatePlaymateInfo()
                    }
                }
            }
        }
    }

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

        //陪玩信息
        binding.ivCategory.setImageUrl(playmateData?.categoryIcon)
        binding.tvCategory.text = playmateData?.categoryName
        binding.vPrice.setPrice(
            playmateData?.price ?: 0f,
            playmateData?.unit ?: ""
        )

        updatePrice()
    }

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

    private fun showEditRemarkDialog() {
        EditRemarkDialog().apply {
            setRemark(binding.tvRemarkInput.text?.toString())
            setCallback(object : EditRemarkDialog.IEditRemarkCallback {
                override fun onEditRemark(remark: String?) {
                    this@CreateOrderActivity.remark = remark
                    binding.tvRemarkInput.text = remark
                }
            })
        }.show(supportFragmentManager, "EditRemarkDialog")

    }

    private fun createOrder() {
        val playmateData = playmateData ?: return
        Router.getRouterInstance<BottomDialogFragment>(Order.CreateDialog.PATH)?.let {
            it.arguments = Bundle().apply {
                putParcelable(Order.CreateDialog.EXTRA_PLAYMATE, playmateData)
                putBoolean(Order.CreateDialog.EXTRA_MODIFY, false)
                putBoolean(Order.CreateDialog.EXTRA_SHOW_REMARK, false)
                putInt(Order.CreateDialog.EXTRA_ORDER_COUNT, binding.vNumber.getNumber())
                putString(
                    Order.CreateDialog.EXTRA_ORDER_REMARK,
                    remark
                )
            }
            it.show(supportFragmentManager, "OrderConfirmDialog")
        }
    }

}