package com.gh.gamecenter.gamecollection.hotlist

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.exposure.ExposureListener
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.common.base.GlobalActivityManager
import com.gh.gamecenter.common.baselist.ListFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.common.json.json
import com.gh.gamecenter.common.utils.SensorsBridge
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.common.view.FixGridLayoutManager
import com.gh.gamecenter.common.view.GridSpacingItemDecoration
import com.gh.gamecenter.core.utils.TimeElapsedHelper
import com.gh.gamecenter.entity.GameCollectionListEntity
import com.gh.gamecenter.gamecollection.square.GameCollectionListItemData

class GameCollectionHotListFragment : ListFragment<GameCollectionListItemData, GameCollectionHotListViewModel>() {
    private lateinit var mBasicExposureSourceList: ArrayList<ExposureSource>
    private lateinit var mExposureListener: ExposureListener
    private lateinit var mViewModel: GameCollectionHotListViewModel
    private var mAdapter: GameCollectionHotListAdapter? = null
    private var mGameCollectionListEntity: GameCollectionListEntity? = null
    private val mElapsedHelper by lazy { TimeElapsedHelper() }
    private var mCanShowList = false
    private var mPosition = -1

    override fun provideListAdapter(): GameCollectionHotListAdapter {
        if (mAdapter == null) {
            mAdapter = GameCollectionHotListAdapter(
                requireContext(),
                mPosition,
                mGameCollectionListEntity,
                mViewModel,
                requireActivity() is GameCollectionListDetailActivity,
                mEntrance,
                arguments?.getString(EntranceConsts.KEY_PATH) ?: "",
                mBasicExposureSourceList
            )
        }
        return mAdapter as GameCollectionHotListAdapter
    }

    override fun provideListViewModel(): GameCollectionHotListViewModel {
        mViewModel = viewModelProvider(GameCollectionHotListViewModel.Factory(mGameCollectionListEntity?.id ?: ""))
        return mViewModel
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        mCanShowList = requireActivity() is GameCollectionListDetailActivity
        mGameCollectionListEntity = requireArguments().getParcelable(GameCollectionListEntity::class.java.simpleName)
        mPosition = requireArguments().getInt(EntranceConsts.KEY_POSITION)
        mBasicExposureSourceList = requireArguments().getParcelableArrayList(EntranceConsts.KEY_EXPOSURE_SOURCE_LIST) ?: arrayListOf()
        if (requireActivity() is GameCollectionListDetailActivity) {
            mBasicExposureSourceList.add(ExposureSource("游戏单合集", mGameCollectionListEntity?.id ?: ""))
            mBasicExposureSourceList.add(ExposureSource("合集详情", ""))
            logPageShow()
        } else {
            mBasicExposureSourceList.add(ExposureSource("游戏单热榜", ""))
            mBasicExposureSourceList.add(ExposureSource("游戏单合集", mGameCollectionListEntity?.id ?: ""))
        }
        super.onCreate(savedInstanceState)
        if (requireActivity() is GameCollectionListDetailActivity) {
            setNavigationTitle(mGameCollectionListEntity?.name)
        }
    }

    private fun logPageShow() {
        val tabIndex = arguments?.getInt(EntranceConsts.KEY_TAB_INDEX, -1) ?: -1
        val tabName = arguments?.getString(EntranceConsts.KEY_TAB_NAME, "") ?: ""
        val multiTabNavId = arguments?.getString(EntranceConsts.KEY_MULTI_TAB_NAV_ID, "") ?: ""
        val multiTabNavName = arguments?.getString(EntranceConsts.KEY_MULTI_TAB_NAV_NAME, "") ?: ""
        val bottomTabName = arguments?.getString(EntranceConsts.KEY_BOTTOM_TAB_NAME, "") ?: ""
        mBaseHandler.postDelayed({
            SensorsBridge.trackEvent("GameListCollectionDetailPageShow", json {
                "game_list_collection_name" to mGameCollectionListEntity?.name
                "game_list_collection_id" to mGameCollectionListEntity?.id
                "page_name" to GlobalActivityManager.getCurrentPageEntity().pageName
                "page_id" to GlobalActivityManager.getCurrentPageEntity().pageId
                "page_business_id" to GlobalActivityManager.getCurrentPageEntity().pageBusinessId
                "last_page_name" to GlobalActivityManager.getLastPageEntity().pageName
                "last_page_id" to GlobalActivityManager.getLastPageEntity().pageId
                "last_page_business_id" to GlobalActivityManager.getLastPageEntity().pageBusinessId
                "bottom_tab" to bottomTabName
                "several_tab_page_name" to multiTabNavName
                "several_tab_page_id" to multiTabNavId
                "position" to tabIndex
                "tab_content" to tabName
                "source_entrance" to mEntrance
            })
        }, 3000L)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        if (mListRefresh != null) {
            mListRefresh!!.setColorSchemeResources(com.gh.gamecenter.common.R.color.primary_theme)
            mListRefresh!!.setOnRefreshListener(this)
        }
        mLayoutManager = FixGridLayoutManager(requireContext(), 2)
        mListRv.setPadding(16F.dip2px(), 0, 16F.dip2px(), 0)
        (mListRv.itemAnimator as DefaultItemAnimator?)!!.supportsChangeAnimations = false
        mListRv.layoutManager = mLayoutManager
        mListRv.adapter = provideListAdapter()
        mExposureListener = ExposureListener(this, provideListAdapter())
        mListRv.addOnScrollListener(mExposureListener)

        if (mReuseNoConn != null) mReuseNoConn!!.setOnClickListener { view1: View? -> onLoadRefresh() }
    }

    override fun getItemDecoration(): RecyclerView.ItemDecoration {
        return GridSpacingItemDecoration(
            2,
            8F.dip2px(),
            false,
            0,
            if (mGameCollectionListEntity?.explain.isNullOrEmpty()) 0 else 1
        )
    }

    override fun onPause() {
        super.onPause()
        mElapsedHelper.pauseCounting()
        if (mElapsedHelper.elapsedTime >= 3) {
            NewFlatLogUtils.logGameCollectionHotListTabView(
                mElapsedHelper.elapsedTime,
                mGameCollectionListEntity?.name ?: "",
                mGameCollectionListEntity?.id ?: "",
                mGameCollectionListEntity?.name ?: ""
            )
            SensorsBridge.trackEvent("ViewGameCollectHotRankTab", json {
                "stay_length" to mElapsedHelper.elapsedTime
                "position" to mPosition
                "tab_content" to mGameCollectionListEntity?.name
                "game_list_collection_name" to mGameCollectionListEntity?.name
                "game_list_collection_id" to mGameCollectionListEntity?.id
            })
        }
    }

    override fun onResume() {
        super.onResume()
        mElapsedHelper.resetCounting()
        mElapsedHelper.resumeCounting()

        if (!mCanShowList) {
            mCanShowList = true
            mViewModel.obsListData.value?.let { onChanged(it) }
        }
    }

    override fun onChanged(ts: MutableList<GameCollectionListItemData>?) {
        if (ts != null && mCanShowList) {
            super.onChanged(ts)
        }
    }

    fun setListRefreshEnable(enable: Boolean) {
        mListRefresh?.isEnabled = enable
    }
}