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.Rlt
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.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.commonui.toast.util.showFailedToast
import com.adealink.weparty.module.account.AccountModule
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.network.data.NoMoreDataError
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.PriceSort
import com.adealink.weparty.playmate.data.StarOption
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.GuestPlaymateListViewModel
import com.adealink.weparty.playmate.viewmodel.PlaymateViewModelFactory
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
import com.adealink.weparty.R as APP_R

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

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

    @BindExtra(Playmate.Common.EXTRA_FIRST_CATEGORY_CODE)
    var firstCategoryCode: String? = null

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

    private val binding by viewBinding(FragmentPlaymateListBinding::bind)
    private val listAdapter by fastLazy { MultiTypeListAdapter<PlaymateListItemData>() }
    private val playmateListViewModel by viewModels<GuestPlaymateListViewModel> { PlaymateViewModelFactory() }

    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 {
            AccountModule.showLoginDialog(activity?.supportFragmentManager)
        }

        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, this))
        binding.vList.adapter = listAdapter
        binding.vList.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
        binding.vList.addItemDecoration(VerticalSpaceItemDecoration(10.dp()))
    }

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


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

    override fun loadData() {
        super.loadData()
        playmateListViewModel.setCategoryCode(firstCategoryCode, category?.code)
        playmateListViewModel.refreshList(true)
    }

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

    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()
            binding.refreshLayout.setEnableLoadMore(playmateListViewModel.hasMoreData())
            if (rlt is Rlt.Failed) {
                if (rlt.error is NoMoreDataError) {
                    return@observe
                }
                showFailedToast(rlt)
            }
        }
        playmateListViewModel.listLD.observe(viewLifecycleOwner) { list ->
            if (list.isNullOrEmpty()) {
                binding.vList.gone()
                binding.vErrorView.show(
                    errorEmptyResId = APP_R.drawable.common_list_empty_ic,
                    title = APP_R.string.commonui_list_empty
                )
            } else {
                binding.vList.show()
                binding.vErrorView.gone()
            }
            listAdapter.submitList(list.map { data ->
                PlaymateListItemData(data)
            })
        }
    }

    override fun goCategoryDetail(data: PlaymateListData) {
        AccountModule.showLoginDialog(activity?.supportFragmentManager)
    }


}