package com.adealink.weparty.playmate.list

import android.os.Bundle
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.adealink.frame.base.fastLazy
import com.adealink.frame.ext.isViewBindingValid
import com.adealink.frame.log.Log
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.BaseFragment
import com.adealink.weparty.commonui.ext.dp
import com.adealink.weparty.commonui.recycleview.adapter.MultiTypeListAdapter
import com.adealink.weparty.commonui.recycleview.diffutil.BaseListDiffUtil
import com.adealink.weparty.commonui.recycleview.itemdecoration.VerticalSpaceItemDecoration
import com.adealink.weparty.commonui.toast.util.showFailedToast
import com.adealink.weparty.module.playmate.Playmate
import com.adealink.weparty.module.playmate.data.PlaymateCategoryData
import com.adealink.weparty.module.playmate.data.TAG_PLAYMATE_LIST
import com.adealink.weparty.playmate.R
import com.adealink.weparty.playmate.data.PlaymateListData
import com.adealink.weparty.playmate.data.PlaymateListItemData
import com.adealink.weparty.playmate.data.PlaymateListPriceSort
import com.adealink.weparty.playmate.data.PlaymateListStarSort
import com.adealink.weparty.playmate.databinding.FragmentPlaymateListBinding
import com.adealink.weparty.playmate.list.adapter.PlaymateListItemViewBinder
import com.adealink.weparty.playmate.list.comp.PlaymateListFilterComp
import com.adealink.weparty.playmate.list.viewmodel.PlaymateListViewModel
import com.adealink.weparty.playmate.viewmodel.PlaymateViewModelFactory
import com.adealink.weparty.ui.main.MainFragment
import com.adealink.weparty.ui.main.viewmodel.MainBottomPage
import com.adealink.weparty.ui.main.viewmodel.MainPageViewModel
import com.adealink.weparty.viewmodel.parentFragmentViewModels
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.tencent.qcloud.tuikit.tuichat.component.audio.AudioPlayer

@RouterUri(path = [Playmate.List.PATH], desc = "陪玩列表")
class PlaymateListFragment : BaseFragment(R.layout.fragment_playmate_list),
    PlaymateListItemViewBinder.OnPlaymateListListener {

    override val isLazyInit: Boolean = true
    override val isLazyLoad: Boolean = true

    @BindExtra(Playmate.Common.EXTRA_CATEGORY)
    var category: PlaymateCategoryData? = null

    @BindExtra(Playmate.Common.EXTRA_LAST_ITEM_BOTTOM)
    var lastItemBottom: Int? = null

    private val binding by viewBinding(FragmentPlaymateListBinding::bind)
    private val listAdapter by fastLazy { MultiTypeListAdapter(BaseListDiffUtil()) }
    private val playmateListViewModel by viewModels<PlaymateListViewModel> { PlaymateViewModelFactory() }
    private val mainPageViewModel by parentFragmentViewModels<MainPageViewModel, MainFragment>(
        MainFragment::class.java
    )

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

    override fun onPause() {
        super.onPause()
        AudioPlayer.getInstance().stopPlay()
    }

    override fun initViews() {
        super.initViews()
        if (category == null) {
            Log.i(TAG_PLAYMATE_LIST, "PlaymateListFragment init fail, for categoryCode is null")
        }
        binding.vListFilter.clFindPartner.onClick {
            findPartner()
        }

        binding.refreshLayout.setEnableRefresh(true)
        binding.refreshLayout.setEnableLoadMore(true)
        binding.refreshLayout.setEnableAutoLoadMore(true)
        binding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                refreshPlaymateList()
            }


            override fun onLoadMore(refreshLayout: RefreshLayout) {
                loadMorePlaymateList()
            }
        })

        listAdapter.register(PlaymateListItemViewBinder(this))
        binding.vList.adapter = listAdapter
        binding.vList.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
        binding.vList.addItemDecoration(
            VerticalSpaceItemDecoration(
                10.dp(),
                lastSpaceHeight = lastItemBottom ?: 0
            )
        )
    }

    override fun initComponents() {
        super.initComponents()
        PlaymateListFilterComp(
            this,
            binding.vListFilter,
            playmateListViewModel.starRankLD.value ?: PlaymateListStarSort.DEFAULT,
            playmateListViewModel.priceRankLD.value ?: PlaymateListPriceSort.DEFAULT,
            {
                playmateListViewModel.changeStarSort()
            },
            {
                playmateListViewModel.changePriceSort()
            }
        ).attach()
    }

    private fun findPartner() {
        mainPageViewModel.showBottomPage(MainBottomPage.FIND_PARTNER)
    }

    fun updateCategory(category: PlaymateCategoryData?) {
        if (!isViewBindingValid()) {
            return
        }
        this@PlaymateListFragment.category = category
        playmateListViewModel.setCategoryCode(category?.code)
        refreshPlaymateList()
    }

    override fun loadData() {
        super.loadData()
        refreshPlaymateList()
    }

    private fun refreshPlaymateList() {
        playmateListViewModel.refreshList()
    }

    private fun loadMorePlaymateList() {
        playmateListViewModel.loadMoreList()
    }

    override fun observeViewModel() {
        super.observeViewModel()
        playmateListViewModel.starRankLD.observeWithoutCache(viewLifecycleOwner) {
            binding.refreshLayout.autoRefresh()
        }
        playmateListViewModel.priceRankLD.observeWithoutCache(viewLifecycleOwner) {
            binding.refreshLayout.autoRefresh()
        }
        playmateListViewModel.listRltLD.observe(viewLifecycleOwner) { rlt ->
            binding.refreshLayout.finishRefresh()
            binding.refreshLayout.finishLoadMore()
            showFailedToast(rlt)
        }
        playmateListViewModel.listLD.observe(viewLifecycleOwner) { list ->
            listAdapter.submitList(list.map { data ->
                PlaymateListItemData(data)
            })
        }
    }

    override fun goCategoryDetail(data: PlaymateListData) {
        activity?.let { act ->
            Router.build(act, Playmate.Detail.PATH)
                .putExtra(Playmate.Detail.EXTRA_PLAYMATE_ID, data.id)
                .putExtra(Playmate.Detail.EXTRA_PLAYMATE_NAME, data.categoryName)
                .start()
        }
    }


}