package com.adealink.weparty.order.dialog

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
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.ext.dp
import com.adealink.weparty.commonui.recycleview.adapter.MultiTypeListAdapter
import com.adealink.weparty.commonui.recycleview.itemdecoration.VerticalSpaceItemDecoration
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.module.order.Order
import com.adealink.weparty.module.order.OrderModule
import com.adealink.weparty.module.order.data.getFinalPrice
import com.adealink.weparty.module.profile.ProfileModule
import com.adealink.weparty.module.profile.data.UserPlaymateSkill
import com.adealink.weparty.order.R
import com.adealink.weparty.order.databinding.DialogCreateOrderFromCategoryBinding
import com.adealink.weparty.order.dialog.adapter.CategoryItemViewBinder
import com.adealink.weparty.order.dialog.adapter.CategoryListItemData
import kotlin.math.max

@RouterUri(path = [Order.CreateFromCategory.PATH], desc = "根据用户品列创建订单")
class CreateOrderFromCategoryDialog :
    BottomDialogFragment(R.layout.dialog_create_order_from_category) {

    @BindExtra(Order.CreateFromCategory.EXTRA_TITLE)
    var title: String? = null

    @BindExtra(Order.CreateFromCategory.EXTRA_PLAYMATE_UID)
    var playmateUid: String? = null

    private val binding by viewBinding(DialogCreateOrderFromCategoryBinding::bind)
    private val profileViewModel by fastLazy { ProfileModule.getProfileViewModel(this) }

    private val listAdapter by fastLazy { MultiTypeListAdapter<CategoryListItemData>() }

    private var categoryItems = listOf<CategoryListItemData>()
    private var selectItem: CategoryListItemData? = null
    private var orderCount: Int = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Router.bind(this)
    }

    @SuppressLint("SetTextI18n")
    override fun initViews() {
        super.initViews()
        binding.tvTitle.text = title
        binding.rvCategory.adapter = listAdapter
        binding.rvCategory.layoutManager =
            LinearLayoutManager(context, RecyclerView.VERTICAL, false)
        binding.rvCategory.addItemDecoration(VerticalSpaceItemDecoration(8.dp()))
        listAdapter.register(
            CategoryItemViewBinder(
                this@CreateOrderFromCategoryDialog,
                object : CategoryItemViewBinder.CategoryChooseListener {
                    override fun onChoose(data: CategoryListItemData, positon: Int) {
                        onCategorySelect(data, positon)
                    }
                })
        )

        binding.vNumber.setNumber(orderCount)
        binding.vNumber.setListener(object : NumberIncreaseView.OnNumberChangedListener {
            override fun onNumberChanged(number: Int) {
                orderCount = number
                updateOrderInfo()
            }
        })

        binding.btnOrder.onClick {
            createOrder()
        }
        updateOrderInfo()
    }

    override fun loadData() {
        super.loadData()
        val uid = playmateUid
        if (uid.isNullOrEmpty()) {
            return
        }
        OrderModule.queryDiscountInfo()
        profileViewModel?.pullUserInfoBy(uid, true)?.observe(viewLifecycleOwner) { rlt ->
            when (rlt) {
                is Rlt.Failed -> {
                    showFailedToast(rlt)
                }

                is Rlt.Success -> {
                    updatePlaymateCategory(rlt.data.skills)
                }
            }
        }
    }

    private fun updatePlaymateCategory(category: List<UserPlaymateSkill>?) {
        categoryItems = category?.map {
            CategoryListItemData(it, false)
        } ?: emptyList()
        listAdapter.submitList(categoryItems)
    }

    private fun onCategorySelect(data: CategoryListItemData, positon: Int) {
        for ((index, itemData) in categoryItems.withIndex()) {
            itemData.selected = index == positon
        }
        listAdapter.notifyDataSetChanged()
        selectItem = data
        updateOrderInfo()
    }

    private fun updateOrderInfo() {
        val originPrice = (selectItem?.data?.price ?: 0f)
        val finalPrice = getFinalPrice(originPrice)
        binding.vPrice.setPrice(
            finalPrice.discountPrice + originPrice * max(orderCount - 1, 0),
            null
        )
    }

    private fun createOrder() {
        val act = activity ?: return
        val select = selectItem ?: return
        Router.build(act, Order.Create.PATH)
            .putExtra(Order.Create.EXTRA_PLAYMATE_ID, select.data.id)
            .putExtra(Order.Create.EXTRA_PLAYMATE_COUNT, orderCount)
            .start()
        dismiss()
    }

}