package com.gh.gamecenter.gamedetail.fuli

import android.content.Intent
import android.view.View
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
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.*
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.GameDetailFragment
import com.gh.gamecenter.gamedetail.GameDetailViewModel
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 var isCanShowKaiFuHint: Boolean = false
    private var shouldScroolToLibao: Boolean = false

    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(GameEntity.TAG) as? GameEntity
        val gameDetailFactory =
            GameDetailViewModel.Factory(HaloApp.getInstance().application, gameEntity?.id, gameEntity)
        shouldScroolToLibao = arguments?.getBoolean(EntranceConsts.KEY_SCROLL_TO_LIBAO) ?: false

        mGameDetailViewModel = viewModelProviderFromParent(gameDetailFactory)
        mFuLiViewModel = viewModelProvider()

        super.onFragmentFirstVisible()

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

        mGameDetailViewModel?.gameDetailLiveData?.value?.data?.zone?.let {
            mFuLiViewModel?.updateUnifiedGameDetailEntity(it)
        }

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

            if (it.status == Status.SUCCESS) {
                mAdapter?.itemList = it.data
                mAdapter?.notifyDataSetChanged()
            } else {
                mBinding?.containerRl?.setBackgroundColor(
                    ContextCompat.getColor(
                        requireContext(),
                        R.color.background_white
                    )
                )
                mBinding?.reuseNoneData?.root?.visibility = View.VISIBLE
            }
        })

        mGameDetailViewModel?.unifiedGameDetailWithUserRelatedInfoForChildLiveData?.observeNonNull(this) { entity ->
            entity.zone?.let {
                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 : androidx.recyclerview.widget.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(GameDetailFragment.EB_SCROLLING, 0))
                }
            }
        })
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(reuse: EBReuse) {
        if ("CalenderDown" == reuse.type) {
            isCanScroll = false
        } else if ("CalenderCancel" == reuse.type) {
            isCanScroll = true
        } else if ("canShowKaifuHint" == reuse.type) {
            mBaseHandler.postDelayed({
                val itemCount = mAdapter?.itemCount ?: return@postDelayed
                for (i in 0 until itemCount) {
                    if (mAdapter?.getItemViewType(i) != FuLiAdapter.SERVER) continue
                    val view = layoutManager?.findViewByPosition(i)
                    if (view != null) {
                        val location = IntArray(2)
                        view.getLocationInWindow(location)
                        val coordinateY = location[1]
                        // 60:detail_ll_bottom height 10: margin
                        if (resources.displayMetrics.heightPixels - coordinateY - 60F.dip2px() > 10F.dip2px()) return@postDelayed
                    }
                    isCanShowKaiFuHint = true
                    EventBus.getDefault().post(EBReuse("showKaifuHint"))
                }
            }, 200)
        }
    }

    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(R.color.background.toColor(requireContext()))
        mBinding?.fmFuliRv?.recycledViewPool?.clear()
        mAdapter?.notifyItemRangeChanged(0, mAdapter?.itemCount ?: 0)
    }
}