package com.gh.gamecenter.mypost

import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.NewFlatLogUtils
import com.gh.common.util.SyncDataBetweenPageHelper
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.baselist.ListFragment
import com.gh.gamecenter.common.utils.safelyGetInRelease
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.common.utils.tryCatchInRelease
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.core.AppExecutor
import com.gh.gamecenter.core.utils.MD5Utils
import com.gh.gamecenter.entity.PersonalHistoryEntity
import com.gh.gamecenter.forum.home.ForumScrollCalculatorHelper
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.personalhome.home.UserHistoryFragment
import com.gh.gamecenter.personalhome.home.UserHistoryViewModel
import com.gh.gamecenter.qa.article.detail.ArticleDetailActivity
import com.gh.gamecenter.qa.questions.newdetail.NewQuestionDetailActivity
import com.gh.gamecenter.qa.video.detail.ForumVideoDetailActivity
import com.gh.gamecenter.video.detail.CustomManager
import com.halo.assistant.HaloApp
import com.shuyu.gsyvideoplayer.video.base.GSYVideoView

class MyPostFragment : ListFragment<PersonalHistoryEntity, UserHistoryViewModel>() {

    private var mCurrentType = UserHistoryViewModel.TYPE.QUESTION
    private var mAdapter: MyPostAdapter? = null
    private var mViewModel: UserHistoryViewModel? = null
    private var mScrollCalculatorHelper: ForumScrollCalculatorHelper? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        mCurrentType = UserHistoryViewModel.TYPE.fromValue(requireArguments().getString(TYPE) ?: "")
        super.onCreate(savedInstanceState)
        mScrollCalculatorHelper = ForumScrollCalculatorHelper(R.id.horizontalVideoView, R.id.verticalVideoView, 0)
        mListRv.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_surface.toColor(requireContext()))
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mListRv?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                mScrollCalculatorHelper?.onScrollStateChanged(mListRv, newState)
            }

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

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

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

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

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

    private fun resumeVideo() {
        mScrollCalculatorHelper?.run {
            if (currentPlayer != null) {
                val video = mViewModel?.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)
                }
            }
        }
    }

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

    override fun provideListViewModel(): UserHistoryViewModel {
        mViewModel = viewModelProvider(
            UserHistoryViewModel.Factory(
                HaloApp.getInstance().application,
                UserManager.getInstance().userId,
                UserHistoryViewModel.SCENE.QUESTION_ANSWER,
                mCurrentType
            )
        )

        return mViewModel!!
    }

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

    override fun onLoadDone() {
        super.onLoadDone()
        AppExecutor.uiExecutor.executeWithDelay({
            tryCatchInRelease {
                scroll()
                mScrollCalculatorHelper?.onScrollStateChanged(
                    mListRv,
                    RecyclerView.SCROLL_STATE_IDLE
                )
            }
        }, 100)
    }

    override fun onLoadEmpty() {
        super.onLoadEmpty()

        // RecyclerView 被隐藏的话会导致不能 AppBar 不能滑动
        mListRv.visibility = View.VISIBLE
    }

    override fun onLoadError() {
        super.onLoadError()

        mListRv.visibility = View.VISIBLE
    }

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

    override fun provideListAdapter(): ListAdapter<*> {
        if (mAdapter == null) {
            mAdapter = MyPostAdapter(requireContext(), mListViewModel, mEntrance) { historyEntity, position ->
                NewFlatLogUtils.logHaloSelfPublishContent(
                    when (mCurrentType) {
                        UserHistoryViewModel.TYPE.COMMUNITY_ARTICLE -> "帖子"
                        UserHistoryViewModel.TYPE.QUESTION -> "提问"
                        UserHistoryViewModel.TYPE.VIDEO -> "视频"
                        else -> ""
                    }, "卡片内容"
                )
                if ("community_article" == historyEntity.type || "community_article_vote" == historyEntity.type) {
                    val intent =
                        ArticleDetailActivity.getIntent(
                            requireContext(),
                            historyEntity.community,
                            historyEntity.id,
                            mEntrance,
                            UserHistoryFragment.PATH_USER_QUESTION_ANSWER
                        )
                    SyncDataBetweenPageHelper.startActivityForResult(
                        this,
                        intent,
                        101,
                        position
                    )
                } else if (historyEntity.type.contains("video")) {
                    val intent = ForumVideoDetailActivity.getIntent(
                        requireContext(),
                        historyEntity.id,
                        historyEntity.community.id
                    )
                    SyncDataBetweenPageHelper.startActivityForResult(
                        this,
                        intent,
                        104,
                        position
                    )
                } else if (!historyEntity.type.contains("question")) {
                    val intent = NewQuestionDetailActivity.getSpecifiedCommentIntent(
                        requireContext(),
                        historyEntity.question.id,
                        historyEntity.id,
                        mEntrance,
                        UserHistoryFragment.PATH_USER_QUESTION_ANSWER
                    )
                    SyncDataBetweenPageHelper.startActivityForResult(
                        this,
                        intent,
                        102,
                        position
                    )
                } else if (historyEntity.type.contains("question")) {
                    val intent = NewQuestionDetailActivity.getIntent(
                        requireContext(),
                        historyEntity.id,
                        mEntrance,
                        UserHistoryFragment.PATH_USER_QUESTION_ANSWER
                    )
                    SyncDataBetweenPageHelper.startActivityForResult(
                        this,
                        intent,
                        103,
                        position
                    )
                }
            }
        }
        return mAdapter!!
    }

    override fun getItemDecoration() = null

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mListRv.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_surface.toColor(requireContext()))
    }

    companion object {
        private const val TYPE = "type"

        fun getInstance(type: UserHistoryViewModel.TYPE): MyPostFragment {
            return MyPostFragment().apply {
                with(
                    bundleOf(
                        TYPE to type.value
                    )
                )
            }
        }
    }
}