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.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.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.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.common.entity.LinkEntity

class CommonCollectionDetailFragment : LazyListFragment<LinkEntity, CommonCollectionDetailViewModel>() {

    private var mAdapter: CommonCollectionDetailAdapter? = null
    private var mCollectionStyle: String = ""
    private lateinit var mViewModel: CommonCollectionDetailViewModel
    private var mExposureListener: ExposureListener? = null
    private lateinit var mBinding: FragmentListBaseSkeletonBinding
    private var mBlockId = ""
    private var mBlockName = ""

    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, "")
    }

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

    override fun provideListAdapter(): ListAdapter<*> {
        if (mAdapter == null) {
            mAdapter = CommonCollectionDetailAdapter(
                requireContext(),
                mCollectionStyle,
                mViewModel,
                mBlockId,
                mBlockName,
                mEntrance
            )
        }
        return mAdapter!!
    }

    override fun provideListViewModel(): CommonCollectionDetailViewModel {
        val collectionId = arguments?.getString(EntranceConsts.KEY_COLLECTION_ID) ?: ""
        mViewModel = viewModelProvider(CommonCollectionDetailViewModel.Factory(collectionId))
        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(R.drawable.ic_data_load_exception)
        mSkeletonScreen = Skeleton.bind(mBinding.listSkeleton)
            .shimmer(true)
            .angle(Constants.SHIMMER_ANGLE)
            .color(R.color.skeleton_shimmer_color)
            .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)
                mListRv.layoutManager = mLayoutManager
            }
            mListRv.removeItemDecorationAt(0)
            mListRv.addItemDecoration(itemDecoration)
        }
        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
                    )
                }
            }
        })
    }

    override fun getItemDecoration(): RecyclerView.ItemDecoration {
        return if (mCollectionStyle == "1-2") {
            GridSpacingItemDecoration(2, 8f.dip2px(), false, 16F.dip2px())
        } else {
            VerticalItemDecoration(requireContext(), 16f, true, R.color.background_white)
        }
    }

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