package com.gh.gamecenter.game.columncollection.detail

import android.os.Bundle
import android.view.View
import androidx.core.view.isVisible
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.GlobalActivityManager
import com.gh.gamecenter.common.baselist.LazyListFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.constant.EntranceConsts.KEY_SHOW_SUBJECT_TAB
import com.gh.gamecenter.common.entity.LinkEntity
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.observeNonNull
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.common.utils.viewModelProviderFromParent
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.databinding.FragmentColumnCollectionDetailBinding
import com.gh.gamecenter.entity.GameColumnCollection
import com.gh.gamecenter.entity.SubjectData
import com.gh.gamecenter.subject.tab.SubjectTabFragment

class ColumnCollectionDetailFragment : LazyListFragment<LinkEntity, ColumnCollectionDetailViewModel>() {

    private var mAdapter: ColumnCollectionDetailAdapter? = null
    private var mBinding: FragmentColumnCollectionDetailBinding? = null
    private var mFragment: SubjectTabFragment? = null

    private var mTabIndex = -1
    private var mBasicExposureSourceList: ArrayList<ExposureSource>? = null

    private var mLocation = ""
    private var mBlockId = ""
    private var mBlockName = ""

    private var showSubjectTab = false

    override fun getItemDecoration() = null

    override fun getRealLayoutId() = R.layout.fragment_column_collection_detail

    override fun onRealLayoutInflated(inflatedView: View) {
        super.onRealLayoutInflated(inflatedView)
        mBinding = FragmentColumnCollectionDetailBinding.bind(inflatedView)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mTabIndex = arguments?.getInt(EntranceConsts.KEY_TAB_INDEX) ?: -1
        mLocation = arguments?.getString(EntranceConsts.KEY_LOCATION, "") ?: ""
        mBlockId = requireArguments().getString(EntranceConsts.KEY_BLOCK_ID, "")
        mBlockName = requireArguments().getString(EntranceConsts.KEY_BLOCK_NAME, "")
        mBasicExposureSourceList = arguments?.getParcelableArrayList(EntranceConsts.KEY_EXPOSURE_SOURCE_LIST)
        showSubjectTab = arguments?.getBoolean(KEY_SHOW_SUBJECT_TAB, false) ?: false
    }

    override fun onFragmentFirstVisible() {
        super.onFragmentFirstVisible()

        if (mIsFromMainWrapper) {
            DisplayUtils.setLightStatusBar(requireActivity(), !mIsDarkModeOn)
            mBinding?.statusBar?.isVisible = true
        }

        mListViewModel.getGameColumnCollection()
        mListViewModel.columnCollection.observeNonNull(this) {
            setNavigationTitle(it.name)
            mCachedView?.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_surface.toColor(requireContext()))
            logPageShow(it)
        }
    }

    private fun logPageShow(entity: GameColumnCollection) {
        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("ColumnCollectionDetailPageShow", json {
                "column_collection_name" to entity.name
                "column_collection_id" to entity.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 onChanged(list: MutableList<LinkEntity>?) {
        if (!list.isNullOrEmpty()) {
            showSubjectTab(list)
        }
    }

    private fun showSubjectTab(linkEntityList: MutableList<LinkEntity>) {
        if (!isVisible) return

        val subjectDataList = arrayListOf<SubjectData>()

        for (link in linkEntityList) {
            val subjectType = when(link.type) {
                TYPE_QQ_MINI_GAME_COLUMN -> SubjectData.SubjectType.QQ_GAME
                TYPE_WECHAT_MINI_GAME_COLUMN -> SubjectData.SubjectType.WECHAT_GAME
                else -> SubjectData.SubjectType.NORMAL
            }
            subjectDataList.add(
                SubjectData(
                    subjectId = link.link,
                    subjectName = link.name,
                    subjectStyle = link.style,
                    isOrder = false,
                    requireUpdateSetting = true,
                    filter = "type:全部", // 默认显示大图
                    subjectType = subjectType,
                    customLimit = link.customLimit
                )
            )
        }

        mFragment = childFragmentManager.findFragmentByTag(SubjectTabFragment::class.java.name) as? SubjectTabFragment
            ?: SubjectTabFragment()
        val bundle = arguments
        mListViewModel.columnCollection.value?.let {
            bundle?.putString(EntranceConsts.KEY_COLUMN_COLLECTION_ID, it.id)
            bundle?.putString(EntranceConsts.KEY_COLUMN_COLLECTION_NAME, it.name)
            bundle?.putString(EntranceConsts.KEY_COLUMN_COLLECTION_STYLE, it.style)
            bundle?.putBoolean(EntranceConsts.KEY_COLUMN_COLLECTION_CUSTOM, it.custom)
            bundle?.putInt(EntranceConsts.KEY_COLUMN_COLLECTION_CUSTOM_SIZE, it.customSize)
        }
        bundle?.putParcelableArrayList(EntranceConsts.KEY_DATA, subjectDataList)
        bundle?.putBoolean(EntranceConsts.KEY_IS_COLUMN_COLLECTION, true)

        mFragment!!.arguments = bundle
        mBinding?.placeholder?.visibility = View.VISIBLE
        childFragmentManager.beginTransaction().replace(R.id.placeholder, mFragment!!, SubjectTabFragment::class.java.name)
            .commitAllowingStateLoss()
    }

    override fun provideListAdapter(): ColumnCollectionDetailAdapter {
        if (mAdapter == null) {
            mAdapter = ColumnCollectionDetailAdapter(
                requireContext(),
                mListViewModel,
                mTabIndex,
                mBasicExposureSourceList,
                mEntrance,
                mBlockId,
                mBlockName,
                arguments?.getString(EntranceConsts.KEY_COLUMN_COLLECTION_STYLE, "") ?: ""
            )
        }
        return mAdapter!!
    }

    override fun onLoadEmpty() {
        super.onLoadEmpty()
        toast(com.gh.gamecenter.common.R.string.content_delete_toast)
    }

    override fun isAutomaticLoad(): Boolean {
        return false
    }

    override fun provideListViewModel(): ColumnCollectionDetailViewModel {
        val factory = ColumnCollectionDetailViewModel.Factory(
            arguments?.getString(EntranceConsts.KEY_COLLECTION_ID)
                ?: ""
        )
        return viewModelProviderFromParent(factory, arguments?.getString(EntranceConsts.KEY_COLLECTION_ID) ?: "")
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        if (mIsFromMainWrapper) {
            DisplayUtils.setLightStatusBar(requireActivity(), !mIsDarkModeOn)
        }
    }

    override fun onBackPressed(): Boolean = mFragment?.onBackPressed() ?: false

    companion object {
        const val TYPE_QQ_MINI_GAME_COLUMN = "qq_mini_game_column"
        const val TYPE_WECHAT_MINI_GAME_COLUMN = "wechat_mini_game_column"
    }

}