package com.gh.gamecenter.gamedetail.fuli

import android.content.Intent
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.ethanhua.skeleton.Skeleton
import com.ethanhua.skeleton.ViewSkeletonScreen
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.fragment.LazyFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.common.mvvm.Status
import com.gh.gamecenter.common.utils.observeNonNull
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.common.utils.viewModelProviderFromParent
import com.gh.gamecenter.core.iinterface.IScrollable
import com.gh.gamecenter.databinding.FragmentFuliBinding
import com.gh.gamecenter.eventbus.EBTypeChange
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.gamedetail.GameDetailViewModel
import com.gh.gamecenter.gamedetail.GameDetailWrapperFragment
import com.halo.assistant.HaloApp
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class FuLiFragment : LazyFragment(), IScrollable {

    private var mBinding: FragmentFuliBinding? = null

    private var mFuLiViewModel: FuLiViewModel? = null
    private var mGameDetailViewModel: GameDetailViewModel? = null

    private var mAdapter: FuLiAdapter? = null
    private var layoutManager: LinearLayoutManager? = null

    private val GAME_DETAIL_LIBAO_REQUEST = 23

    private var isCanScroll: Boolean = true

    private lateinit var mViewSkeletonScreen: ViewSkeletonScreen

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == GAME_DETAIL_LIBAO_REQUEST) {
            mAdapter!!.notifyDataSetChanged()
        }
    }

    override fun getRealLayoutId() = R.layout.fragment_fuli

    override fun onRealLayoutInflated(inflatedView: View) {
        super.onRealLayoutInflated(inflatedView)

        mBinding = FragmentFuliBinding.bind(inflatedView)
    }

    override fun onFragmentFirstVisible() {
        val gameEntity = arguments?.getParcelable(EntranceConsts.KEY_GAME_ENTITY) as? GameEntity
        val gameDetailFactory =
            GameDetailViewModel.Factory(HaloApp.getInstance().application, gameEntity?.id, gameEntity)

        mGameDetailViewModel = viewModelProviderFromParent(gameDetailFactory, gameEntity?.id ?: "")
        mFuLiViewModel = viewModelProvider()

        super.onFragmentFirstVisible()

        if (gameEntity != null) {
            mFuLiViewModel?.updateGameEntity(gameEntity)
        }

        mFuLiViewModel?.fuFiDataLD?.observe(this) {
            mViewSkeletonScreen.hide()
            mBinding?.loadingContainer?.reuseLlLoading?.visibility = View.GONE

            if (it.status == Status.SUCCESS) {
                mAdapter?.itemList = it.data
                mAdapter?.notifyDataSetChanged()
            } else {
                mBinding?.containerRl?.setBackgroundColor(
                    com.gh.gamecenter.common.R.color.ui_surface.toColor(
                        requireContext()
                    )
                )
                mBinding?.reuseNoneData?.root?.visibility = View.VISIBLE
            }
        }

        mGameDetailViewModel?.zoneLiveData?.observeNonNull(this) {
            mFuLiViewModel?.updateUnifiedGameDetailEntity(it)
        }
    }

    override fun onFragmentResume() {
        super.onFragmentResume()
        startPageTime = System.currentTimeMillis()
    }

    override fun onFragmentPause() {
        super.onFragmentPause()

        val stayTime = (System.currentTimeMillis() - startPageTime) / 1000
        NewLogUtils.logGameDetailTabOrCommentDetailPause(
            "jump_game_detail_special_area_tab",
            stayTime,
            mGameDetailViewModel?.game?.id ?: "",
            mGameDetailViewModel?.game?.gameType ?: ""
        )
    }

    override fun initRealView() {
        super.initRealView()

        mViewSkeletonScreen =
            Skeleton.bind(mBinding?.gameDetailSkeleton).shimmer(false).load(R.layout.fragment_gamedongtai_skeleton)
                .show()
        mAdapter = FuLiAdapter(requireContext(), mFuLiViewModel, mEntrance)
        mBinding?.fmFuliRv?.adapter = mAdapter
        layoutManager = object : LinearLayoutManager(context) {
            override fun canScrollVertically(): Boolean {
                return isCanScroll
            }
        }
        mBinding?.fmFuliRv?.layoutManager = layoutManager
        mBinding?.fmFuliRv?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    EventBus.getDefault().post(EBTypeChange(GameDetailWrapperFragment.EB_SCROLLING, 0))
                }
            }
        })
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(reuse: EBReuse) {
        if ("CalenderDown" == reuse.type) {
            isCanScroll = false
        } else if ("CalenderCancel" == reuse.type) {
            isCanScroll = true
        }
    }

    override fun provideSyncAdapter(): RecyclerView.Adapter<*>? {
        return mAdapter?.answerAdapter
    }

    override fun addSyncPageObserver(): Boolean {
        return true
    }

    override fun scrollToTop() {
        mBinding?.fmFuliRv?.scrollToPosition(0)
    }


    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mBinding?.containerRl?.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_background.toColor(requireContext()))
        mBinding?.fmFuliRv?.recycledViewPool?.clear()
        mAdapter?.notifyItemRangeChanged(0, mAdapter?.itemCount ?: 0)
    }
}