package com.gh.gamecenter.game.commoncollection.detail

import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager.SpanSizeLookup
import androidx.recyclerview.widget.RecyclerView
import com.ethanhua.skeleton.Skeleton
import com.gh.common.exposure.ExposureListener
import com.gh.common.exposure.IExposable
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.R
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.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
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.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.common.view.VerticalItemDecoration
import com.gh.gamecenter.databinding.FragmentListBaseSkeletonBinding
import com.gh.gamecenter.entity.CommonCollectionEntity
import com.gh.gamecenter.home.custom.model.CustomPageItem
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.COMMON_CONTENT_COLLECTION_LAYOUT_HORIZONTAL_SLIDE_BANNER

class CustomCommonCollectionDetailFragment : LazyListFragment<LinkEntity, CustomCommonCollectionDetailViewModel>() {

    private var mAdapter: CustomCommonCollectionDetailAdapter? = null
    private var mCollectionStyle: String = ""
    private lateinit var mViewModel: CustomCommonCollectionDetailViewModel
    private var mExposureListener: ExposureListener? = null
    private lateinit var mBinding: FragmentListBaseSkeletonBinding
    private var mBlockId = ""
    private var mBlockName = ""
    private var mLocation = ""
    private var mTabIndexValue = 0 // 在首页的 tab 位置
    private var mLayout = COMMON_CONTENT_COLLECTION_LAYOUT_HORIZONTAL_SLIDE_BANNER

    override fun getRealLayoutId(): Int = R.layout.fragment_list_base_skeleton

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBlockId = requireArguments().getString(EntranceConsts.KEY_BLOCK_ID, "")
        mBlockName = requireArguments().getString(EntranceConsts.KEY_BLOCK_NAME, "")
        mLocation = requireArguments().getString(EntranceConsts.KEY_LOCATION, "")
        mTabIndexValue = requireArguments().getInt(EntranceConsts.KEY_TAB_INDEX, -1)
        mLayout = requireArguments().getInt(EntranceConsts.KEY_COMMON_CONTENT_COLLECTION_LAYOUT, mLayout)
    }

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

    override fun provideListAdapter(): ListAdapter<*> {
        if (mAdapter == null) {
            val exposureSourceList =
                requireArguments().getParcelableArrayList<ExposureSource>(EntranceConsts.KEY_EXPOSURE_SOURCE_LIST)
            mAdapter = CustomCommonCollectionDetailAdapter(
                requireContext(),
                mCollectionStyle,
                mViewModel,
                mLocation,
                mTabIndexValue,
                mEntrance,
                exposureSourceList
            )
        }
        return mAdapter!!
    }

    override fun provideListViewModel(): CustomCommonCollectionDetailViewModel {
        val collectionId = arguments?.getString(EntranceConsts.KEY_COLLECTION_ID) ?: ""
        mViewModel = viewModelProvider(CustomCommonCollectionDetailViewModel.Factory(collectionId, mLayout))
        return mViewModel
    }

    override fun initRealView() {
        super.initRealView()
        mCachedView.setPadding(16f.dip2px(), 0, 16f.dip2px(), 0)
        mReuseNoData?.findViewById<TextView>(R.id.reuseNoneDataTv)?.text = "内容不见了~"
        mReuseNoData?.findViewById<TextView>(R.id.reuseNoneDataDescTv)?.text = "先去看看其它的内容吧"
        mReuseNoData?.findViewById<TextView>(R.id.reuseResetLoadTv)?.visibility = View.GONE
        mReuseNoData?.findViewById<ImageView>(R.id.reuseNoneDataIv)?.setImageResource(com.gh.gamecenter.common.R.drawable.ic_data_load_exception)
        mSkeletonScreen = Skeleton.bind(mBinding.listSkeleton)
            .shimmer(true)
            .angle(Constants.SHIMMER_ANGLE)
            .color(com.gh.gamecenter.common.R.color.ui_skeleton_highlight)
            .duration(Constants.SHIMMER_DURATION)
            .maskWidth(Constants.MASK_WIDTH)
            .gradientCenterColorWidth(Constants.GRADIENT_CENTER_COLOR_WIDTH)
            .load(R.layout.common_collection_detail_skeleton)
            .show()
    }

    override fun onFragmentFirstVisible() {
        super.onFragmentFirstVisible()
        mExposureListener = ExposureListener(this, provideListAdapter() as IExposable)
        mViewModel.commonCollectionLiveData.observe(viewLifecycleOwner) {
            setNavigationTitle(it.name)
            mCollectionStyle = it.style
            mAdapter?.collectionStyle = mCollectionStyle
            if (mCollectionStyle == "1-2") {
                mLayoutManager = FixGridLayoutManager(requireContext(), 2).apply {
                    spanSizeLookup = object : SpanSizeLookup() {
                        override fun getSpanSize(position: Int): Int {
                            val itemCount = mAdapter?.itemCount ?: 0
                            return if (position == itemCount - 1) {
                                2
                            } else {
                                1
                            }
                        }
                    }
                }
                mListRv?.layoutManager = mLayoutManager
            }
            mListRv?.removeItemDecorationAt(0)
            mListRv?.addItemDecoration(itemDecoration)

            logPageShow(it)
        }
        mListViewModel.loadExceptionLiveData.observe(viewLifecycleOwner) {
            if (it != null && it.code() == 404) {
                toast("内容可能已被删除")
            }
        }
        mListRv?.addOnScrollListener(mExposureListener!!)
        mListRv?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    val commonLinkCollection = mViewModel.commonCollectionLiveData.value
                    var position = mLayoutManager.findLastCompletelyVisibleItemPosition()
                    if (position < 0) position = mLayoutManager.findLastVisibleItemPosition() - 1
                    if (position < 0 || position >= commonLinkCollection?.collectionList?.size ?: 0) return
                    val contentEntity = commonLinkCollection?.collectionList?.get(position)
                    val linkEntity = contentEntity?.linkEntity
                    NewLogUtils.logSlideCommonCollection(
                        commonLinkCollection?.id ?: "",
                        commonLinkCollection?.name ?: "",
                        mBlockId,
                        mBlockName,
                        mEntrance,
                        "合集详情",
                        linkEntity?.title ?: "",
                        contentEntity?.addedContent1 ?: "",
                        contentEntity?.addedContent2 ?: "",
                        position + 1
                    )
                }
            }
        })
    }

    private fun logPageShow(entity: CommonCollectionEntity) {
        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("LinkContentCollectionDetailPageShow", json {
                "link_content_collection_name" to entity.name
                "link_content_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 getItemDecoration(): RecyclerView.ItemDecoration =
        when (mCollectionStyle) {
            "1-2" ->
                if (mViewModel.getLayout() == CustomPageItem.COMMON_CONTENT_COLLECTION_LAYOUT_RECOMMEND_CARD) {
                    GridSpacingItemDecoration(2, 12f.dip2px(), false, 16F.dip2px())
                } else {
                    GridSpacingItemDecoration(2, 8f.dip2px(), false, 16F.dip2px())
                }

            else -> VerticalItemDecoration(requireContext(), 16f, true, com.gh.gamecenter.common.R.color.ui_surface)
        }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        if ((mListRv?.itemDecorationCount ?: 0) > 0) {
            mListRv?.removeItemDecorationAt(0)
            mListRv?.addItemDecoration(itemDecoration)
        }
    }
}