package com.adealink.weparty.order.center.comp

import androidx.lifecycle.LifecycleOwner
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.router.Router
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.BaseViewComponent
import com.adealink.weparty.commonui.ext.dp
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.commonui.recycleview.adapter.MultiTypeListAdapter
import com.adealink.weparty.commonui.recycleview.itemdecoration.VerticalSpaceItemDecoration
import com.adealink.weparty.module.playmate.Playmate
import com.adealink.weparty.module.playmate.PlaymateModule
import com.adealink.weparty.order.center.adapter.OrderSkillItemViewBinder
import com.adealink.weparty.order.center.data.OrderSkillItem
import com.adealink.weparty.order.databinding.LayoutOrderCenterSkillsBinding

class OrderCenterSkillComp(
    lifecycleOwner: LifecycleOwner,
    val binding: LayoutOrderCenterSkillsBinding
) : BaseViewComponent(lifecycleOwner) {
    private val skillAdapter by fastLazy { MultiTypeListAdapter<OrderSkillItem>() }
    private val playmateViewModel by fastLazy { PlaymateModule.getPlaymateViewModel(requireActivity()) }

    override fun initViews() {
        super.initViews()
        binding.root.onClick {
            goSkillSetting()
        }
        skillAdapter.register(OrderSkillItemViewBinder {
            goSkillSetting()
        })
        binding.rvSkills.adapter = skillAdapter
        binding.rvSkills.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
        binding.rvSkills.addItemDecoration(
            VerticalSpaceItemDecoration(8.dp())
        )
    }

    override fun onResume() {
        super.onResume()
        playmateViewModel?.getSkillSettingList(true)?.observe(viewLifecycleOwner) { rlt ->
            submitSkills(
                (rlt as? Rlt.Success)?.data?.map {
                    OrderSkillItem(it)
                }
            )
        }
    }


    private fun submitSkills(items: List<OrderSkillItem>?) {
        if (items.isNullOrEmpty()) {
            binding.rvSkills.gone()
        } else {
            binding.rvSkills.show()
            skillAdapter.submitList(items)
        }
    }

    private fun goSkillSetting() {
        val act = activity ?: return
        Router.build(act, Playmate.SkillSetting.PATH).start()
    }

}