package com.gh.gamecenter.forum.search

import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.NewFlatLogUtils
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.SearchActivity
import com.gh.gamecenter.SearchType
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.EntranceConsts
import com.gh.gamecenter.common.utils.SensorsBridge
import com.gh.gamecenter.common.utils.safelyGetInRelease
import com.gh.gamecenter.common.utils.tryCatchInRelease
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.common.view.divider.HorizontalDividerItemDecoration
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.core.utils.MD5Utils
import com.gh.gamecenter.databinding.FragmentForumContentSearchListBinding
import com.gh.gamecenter.feature.entity.AnswerEntity
import com.gh.gamecenter.forum.home.ForumScrollCalculatorHelper
import com.gh.gamecenter.forum.search.CommunitySearchEventListener.Companion.SEARCH_BUTTON_VIEW_CONTENT_DETAIL
import com.gh.gamecenter.forum.search.ForumOrUserSearchActivity.Companion.LOCATION_COMMUNITY
import com.gh.gamecenter.search.viewmodel.SearchTabViewModel
import com.gh.gamecenter.video.detail.CustomManager
import com.shuyu.gsyvideoplayer.video.base.GSYVideoView

class ForumContentSearchListFragment : LazyListFragment<AnswerEntity, ForumContentSearchListViewModel>(),
    CommunitySearchEventListener {

    private val parentTabViewModel by viewModels<SearchTabViewModel>(
        ownerProducer = {
            parentFragment ?: this
        }
    )

    private var mBbsId = ""
    private var mSearchKey = ""
    private var mSearchType = SearchType.DEFAULT.value
    private var mLocation = ""

    private var mAdapter: ForumContentSearchListAdapter? = null
    private var mBinding: FragmentForumContentSearchListBinding? = null

    private var mScrollCalculatorHelper: ForumScrollCalculatorHelper? = null

    private var mListReachTop = true

    private var mIsAutoLoad = true

    override fun provideListAdapter(): ListAdapter<*> {
        return mAdapter
            ?: ForumContentSearchListAdapter(
                requireContext(),
                mListViewModel,
                "${mEntrance}+(搜索)",
                this
            ).apply {
                mAdapter = this
            }
    }

    override fun provideListViewModel(): ForumContentSearchListViewModel {
        val sourceEntrance = activity?.intent?.getStringExtra(EntranceConsts.KEY_SOURCE_ENTRANCE) ?: ""
        val factory = ForumContentSearchListViewModel.Factory(mBbsId, mLocation)
        val viewModel = viewModelProvider<ForumContentSearchListViewModel>(factory).apply {
            this.sourceEntrance = sourceEntrance
        }
        return viewModel
    }

    override fun getRealLayoutId(): Int {
        return R.layout.fragment_forum_content_search_list
    }

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

    override fun isAutomaticLoad(): Boolean = false

    fun setSearchKeyAndType(searchKey: String, searchType: String) {
        mSearchKey = searchKey
        mSearchType = searchType
        mListViewModel?.updateSearchKeyAndType(mSearchKey, mSearchType)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        mIsAutoLoad = arguments?.getBoolean(EntranceConsts.KEY_IS_AUTO_LOAD, true) ?: true
        super.onCreate(savedInstanceState)
    }

    override fun onFragmentResume() {
        resumeVideo()
        super.onFragmentResume()
    }

    private fun resumeVideo() {
        mScrollCalculatorHelper?.run {
            if (currentPlayer != null
                && currentPosition >= 0
                && currentPosition < mListViewModel?.videoList?.size ?: 0
            ) {
                val video = mListViewModel?.videoList?.safelyGetInRelease(currentPosition)
                if (video != null) {
                    val position = ForumScrollCalculatorHelper.getPlaySchedule(MD5Utils.getContentMD5(video.url))
                    //这里必须要延迟操作，否则会白屏
                    mBaseHandler.postDelayed({
                        tryCatchInRelease {
                            if (position != 0L) {
                                if (currentPlayer?.currentState == GSYVideoView.CURRENT_STATE_PAUSE) {
                                    currentPlayer?.startPlayLogic(true)
                                }
                            } else {
                                currentPlayer?.release()
                            }
                        }
                    }, 50)
                }
            }
        }
    }

    fun refreshScrollHelper() {
        mBaseHandler.postDelayed({
            tryCatchInRelease {
                scroll()
                mScrollCalculatorHelper?.onScrollStateChanged(mListRv, RecyclerView.SCROLL_STATE_IDLE)
            }
        }, 100)
    }

    override fun onFragmentPause() {
        pauseVideo()
        super.onFragmentPause()
    }

    private fun pauseVideo() {
        mScrollCalculatorHelper?.run {
            if (currentPlayer != null
                && currentPosition >= 0
                && currentPosition < mListViewModel?.videoList?.size ?: 0
            ) {
                currentPlayer?.onVideoPause()
                val position = currentPlayer?.getCurrentPosition() ?: 0L
                val video = mListViewModel?.videoList?.safelyGetInRelease(currentPosition)
                if (video != null) {
                    ForumScrollCalculatorHelper.savePlaySchedule(MD5Utils.getContentMD5(video.url), position)
                }
            }
        }
    }

    override fun onRefresh() {
        mScrollCalculatorHelper?.currentPlayer?.release()
        mScrollCalculatorHelper?.reset()

        if (isFilterViewShow()) {
            mBinding?.fixedTopFilterView?.filterView?.visibility = View.GONE
        }
        super.onRefresh()
    }

    override fun onLoadDone() {
        if (isFilterViewShow()) {
            mBinding?.fixedTopFilterView?.filterView?.visibility = View.VISIBLE
        }
        super.onLoadDone()
        mBaseHandler.postDelayed({
            tryCatchInRelease {
                scroll()
                mScrollCalculatorHelper?.onScrollStateChanged(mListRv, RecyclerView.SCROLL_STATE_IDLE)
            }
        }, 100)
    }

    override fun onBackPressed(): Boolean {
        mScrollCalculatorHelper?.currentPlayer?.run {
            return (isIfCurrentIsFullscreen
                    && CustomManager.backFromWindowFull(requireActivity(), getKey()))
        }
        return super.onBackPressed()
    }

    override fun onDestroy() {
        super.onDestroy()
        mScrollCalculatorHelper?.currentPlayer?.release()
    }

    override fun onFragmentFirstVisible() {
        mBbsId = arguments?.getString(EntranceConsts.KEY_BBS_ID) ?: ""
        mLocation = arguments?.getString(EntranceConsts.KEY_LOCATION) ?: LOCATION_COMMUNITY
        super.onFragmentFirstVisible()
        mListRv?.overScrollMode = View.OVER_SCROLL_NEVER
        mListRv?.setBackgroundColor(ContextCompat.getColor(requireContext(), com.gh.gamecenter.common.R.color.ui_surface))
        mReuseNoData?.setBackgroundColor(ContextCompat.getColor(requireContext(), com.gh.gamecenter.common.R.color.ui_surface))
        mBinding?.run {
            fixedTopFilterView.run {
                orderSfv.setItemList(listOf("默认", "最新"), 0)
                commentHintTv.text = "搜索结果"
                divider.visibility = View.GONE
                commentHintCountTv.visibility = View.GONE
                orderSfv.setOnCheckedCallback { position ->
                    val sort = if (position == 0) "" else "latest"
                    mListViewModel?.updateSort(sort)
                }
            }

        }
        if (mEntrance == "论坛首页") {
            mScrollCalculatorHelper = ForumScrollCalculatorHelper(R.id.horizontalVideoView, R.id.verticalVideoView, 0)
            mListRv?.addOnScrollListener(object : RecyclerView.OnScrollListener() {

                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                    mListReachTop = !recyclerView.canScrollVertically(-1)
                    setRefreshingLayoutEnable(mListReachTop)

                    mScrollCalculatorHelper?.onScrollStateChanged(mListRv, newState)

                    if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                        var position = mLayoutManager.findLastCompletelyVisibleItemPosition()
                        if (position == -1) position = mLayoutManager.findLastVisibleItemPosition() - 1
                        NewLogUtils.logForumDetailFeedSlide(position + 1)
                    }
                }

                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    if (dy != 0) scroll()
                }
            })
        }

    }

    private fun scroll() {
        val firstVisibleItem = mLayoutManager?.findFirstVisibleItemPosition() ?: -1
        val lastVisibleItem = mLayoutManager?.findLastVisibleItemPosition() ?: -1
        mScrollCalculatorHelper?.onScroll(mListViewModel?.videoList, firstVisibleItem, lastVisibleItem)
    }

    fun setRefreshingLayoutEnable(listReachTop: Boolean) {
        mBinding?.listRefresh?.isEnabled = listReachTop
    }

    override fun initRealView() {
        super.initRealView()
        if (mIsAutoLoad) {
            mListViewModel?.updateSearchKeyAndType(mSearchKey, mSearchType)
        }
        parentTabViewModel.searchKeyAndType.observe(viewLifecycleOwner) { (key, type) ->
            setSearchKeyAndType(key, type)
        }
    }

    override fun getItemDecoration(): RecyclerView.ItemDecoration? {
        return HorizontalDividerItemDecoration.Builder(requireContext())
            .size(DisplayUtils.dip2px(0.5f))
            .margin(DisplayUtils.dip2px(20f))
            .color(ContextCompat.getColor(requireContext(), com.gh.gamecenter.common.R.color.ui_background)).build()
    }

    private fun isFilterViewShow(): Boolean {
        return mEntrance == "论坛详情"
    }

    override fun addSyncPageObserver(): Boolean = true

    override fun provideSyncAdapter(): ForumContentSearchListAdapter = mAdapter!!

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mListRv?.setBackgroundColor(ContextCompat.getColor(requireContext(), com.gh.gamecenter.common.R.color.ui_surface))
        mReuseNoData?.setBackgroundColor(ContextCompat.getColor(requireContext(), com.gh.gamecenter.common.R.color.ui_surface))
    }

    override fun onItemClick(contentId: String?, itemType: String?, title: String?, sequence: Int) {
        SensorsBridge.trackArticleSearchResultClick(
            GlobalActivityManager.getCurrentPageEntity().pageId,
            GlobalActivityManager.getCurrentPageEntity().pageName,
            mListViewModel.sourceEntrance,
            mSearchKey,
            SearchActivity.toTrackSearchType(mSearchType),
            contentId ?: "",
            title ?: "",
            sequence
        )

        NewFlatLogUtils.logSearchContentClick(
            mLocation,
            mBbsId,
            SearchType.fromString(mSearchType).toChinese(),
            mSearchKey,
            contentId ?: "",
            itemType ?: "",
            title ?: "",
            sequence + 1,
            SEARCH_BUTTON_VIEW_CONTENT_DETAIL
        )

    }

    override fun onItemChildClick(
        contentId: String?,
        itemType: String?,
        title: String?,
        sequence: Int,
        button: String
    ) {
        NewFlatLogUtils.logSearchContentClick(
            mLocation,
            mBbsId,
            SearchType.fromString(mSearchType).toChinese(),
            mSearchKey,
            contentId ?: "",
            itemType ?: "",
            title ?: "",
            sequence + 1,
            button
        )
    }

    override fun onItemExposed(contentId: String?, itemType: String?, title: String?, sequence: Int) {
        NewFlatLogUtils.logSearchContentExposure(
            mLocation,
            mBbsId,
            SearchType.fromString(mSearchType).toChinese(),
            mSearchKey,
            contentId ?: "",
            itemType ?: "",
            title ?: "",
            sequence + 1
        )
    }
}