package com.gh.gamecenter.qa.dialog

import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.NewFlatLogUtils
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.SearchActivity
import com.gh.gamecenter.SearchType
import com.gh.gamecenter.common.base.GlobalActivityManager
import com.gh.gamecenter.common.baselist.LazyListFragment
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.SensorsBridge
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.core.utils.HtmlUtils
import com.gh.gamecenter.entity.ForumEntity
import com.gh.gamecenter.forum.detail.ForumDetailActivity
import com.gh.gamecenter.search.viewmodel.SearchTabViewModel

class ChooseForumContainerFragment : LazyListFragment<ForumEntity, ChooseForumContainerViewModel>() {

    private val parentTabViewModel by viewModels<SearchTabViewModel>(
        ownerProducer = { parentFragment ?: this }
    )

    private var mAdapter: ChooseForumContainerAdapter? = null
    private var type: String = ""
    private var mSearchKey: String = ""
    private var mIsFirstIn = true

    private var mSearchType = SearchType.DEFAULT.value
    private var entrance = ""

    private var mIsAutoLoad = true

    override fun onCreate(savedInstanceState: Bundle?) {
        mIsAutoLoad = arguments?.getBoolean(EntranceConsts.KEY_IS_AUTO_LOAD, true) ?: true
        super.onCreate(savedInstanceState)
    }

    override fun onFragmentFirstVisible() {
        type = arguments?.getString(EntranceConsts.KEY_CHOOSE_FORUM_TYPE) ?: ""
        entrance =
            if (type == ChooseForumType.ATTENTION.value) "我的关注tab" else if (type == ChooseForumType.HOT.value) "热门论坛tab" else "搜索结果"
        mReuseNoData?.setBackgroundColor(ContextCompat.getColor(requireContext(), com.gh.gamecenter.common.R.color.ui_surface))
        super.onFragmentFirstVisible()
    }

    override fun provideListAdapter(): ListAdapter<*> {
        return mAdapter ?: ChooseForumContainerAdapter(
            requireContext(),
            type,
            mListViewModel,
            mEntrance,
            childClick = { position, forumEntity, button ->

                NewFlatLogUtils.logSearchBbsClick(
                    mSearchType,
                    mSearchKey,
                    forumEntity.id,
                    position + 1,
                    HtmlUtils.stripHtml(forumEntity.name),
                    button,
                    mListViewModel.sourceEntrance
                )

                SensorsBridge.trackForumSearchResultClick(
                    GlobalActivityManager.getCurrentPageEntity().pageId,
                    GlobalActivityManager.getCurrentPageEntity().pageName,
                    mListViewModel.sourceEntrance,
                    mListViewModel.searchKey,
                    SearchActivity.toTrackSearchType(mSearchType),
                    forumEntity.id,
                    HtmlUtils.stripHtml(forumEntity.name),
                    forumEntity.typeChinese,
                    position
                )
            }
        ) { enity, position ->
            if (requireActivity() is ChooseForumActivity) {
                (requireActivity() as ChooseForumActivity).chooseSuccess(enity)
                val bbsType = if (enity.type == "game_bbs") "游戏论坛" else "综合论坛"
                NewLogUtils.logChooseForumPanelClick("click_select_forum_panel_forum", entrance, enity.id, bbsType)
            } else {
                requireActivity().startActivity(ForumDetailActivity.getIntent(requireContext(), enity.id, "搜索论坛"))
            }
        }.apply {
            mAdapter = this
        }
    }

    override fun provideListViewModel(): ChooseForumContainerViewModel {
        val sourceEntrance = activity?.intent?.getStringExtra(EntranceConsts.KEY_SOURCE_ENTRANCE) ?: ""
        return viewModelProvider(ChooseForumContainerViewModel.Factory(type, mSearchKey, mSearchType, sourceEntrance))
    }

    fun setSearchKeyAndType(searchKey: String, searchType: String) {
        mSearchKey = searchKey
        mSearchType = searchType
        mListViewModel?.setSearchKeyAndRefresh(searchKey, mSearchType)
    }

    override fun initRealView() {
        super.initRealView()
        if (mIsAutoLoad && type == ChooseForumType.SEARCH.value) {
            mListViewModel?.setSearchKeyAndRefresh(mSearchKey, mSearchType)
        }

        parentTabViewModel.searchKeyAndType.observe(viewLifecycleOwner, { (key, type) ->
            setSearchKeyAndType(key, type)
        })
    }

    override fun onChanged(ts: MutableList<ForumEntity>?) {
        super.onChanged(ts)
        if (type == ChooseForumType.ATTENTION.value && mIsFirstIn && ts.isNullOrEmpty()) {
            (requireActivity() as ChooseForumActivity).switchTab(1)
            mIsFirstIn = false
        }
    }

    override fun isAutomaticLoad(): Boolean = type != ChooseForumType.SEARCH.value

    override fun getItemDecoration(): RecyclerView.ItemDecoration? = null

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mReuseNoData?.setBackgroundColor(ContextCompat.getColor(requireContext(), com.gh.gamecenter.common.R.color.ui_surface))
    }

    companion object {

        fun getInstance(type: ChooseForumType): Fragment {
            val bundle = bundleOf(EntranceConsts.KEY_CHOOSE_FORUM_TYPE to type.value)
            return ChooseForumContainerFragment().apply {
                arguments = bundle
            }
        }
    }

    enum class ChooseForumType(val value: String) {
        ATTENTION("attention"),
        HOT("hot"),
        SEARCH("search")
    }

}
