package com.gh.gamecenter.personalhome.home

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.core.AppExecutor
import com.gh.common.util.*
import com.gh.common.util.NewFlatLogUtils
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.*
import com.gh.gamecenter.core.utils.MD5Utils
import com.gh.gamecenter.databinding.FragmentUserPublishBinding
import com.gh.gamecenter.entity.*
import com.gh.gamecenter.feature.entity.ForumVideoEntity
import com.gh.gamecenter.feature.entity.PersonalEntity
import com.gh.gamecenter.forum.home.ForumScrollCalculatorHelper
import com.gh.gamecenter.gamedetail.rating.RatingReplyActivity
import com.gh.gamecenter.qa.article.detail.ArticleDetailActivity
import com.gh.gamecenter.qa.entity.ArticleDetailEntity
import com.gh.gamecenter.qa.entity.QuestionsDetailEntity
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 UserHistoryFragment : ListFragment<PersonalHistoryEntity, UserHistoryViewModel>() {

    private var mUserId: String = ""
    private var mCount = PersonalEntity.Count()
    private var mScene: UserHistoryViewModel.SCENE = UserHistoryViewModel.SCENE.COMMENT

    private var mAdapter: UserHistoryAdapter? = null
    private var mViewModel: UserHistoryViewModel? = null
    private var mBinding: FragmentUserPublishBinding? = null
    private var mCurrentType = UserHistoryViewModel.TYPE.ALL
    private var mScrollCalculatorHelper: ForumScrollCalculatorHelper? = null

    override fun getLayoutId() = 0
    override fun getInflatedLayout() =
        FragmentUserPublishBinding.inflate(layoutInflater).apply { mBinding = this }.root

    override fun onCreate(savedInstanceState: Bundle?) {
        arguments?.apply {
            mUserId = getString(USER_ID, "")
            mScene = getSerializable(SCENE) as UserHistoryViewModel.SCENE
            mCount = getParcelable(COUNT) ?: PersonalEntity.Count()
            mCurrentType = UserHistoryViewModel.TYPE.fromValue(getString(DEFAULT_TYPE))
        }
        super.onCreate(savedInstanceState)
        mScrollCalculatorHelper =
            ForumScrollCalculatorHelper(R.id.horizontalVideoView, R.id.verticalVideoView, 0)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initTypeView()

        mViewModel?.count?.observeNonNull(viewLifecycleOwner) {
            refreshCount(it)
        }

        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()
    }

    fun onScrollStateChanged() {
        mScrollCalculatorHelper?.onScrollStateChanged(mListRv, RecyclerView.SCROLL_STATE_IDLE)
    }

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

    private fun initTypeView() {
        mBinding?.run {
            allType.text = "全部 ${mCount.getTotalCount()}"
            videoType.text = "视频 ${mCount.video}"
            articleType.text = "帖子 ${mCount.communityArticle}"
            questionType.text = "提问 ${mCount.question}"
            answerType.text = "回答 ${mCount.answer}"

            val typePairList = arrayListOf(
                Pair(UserHistoryViewModel.TYPE.ALL, allType),
                Pair(UserHistoryViewModel.TYPE.VIDEO, videoType),
                Pair(UserHistoryViewModel.TYPE.COMMUNITY_ARTICLE, articleType),
                Pair(UserHistoryViewModel.TYPE.QUESTION, questionType),
                Pair(UserHistoryViewModel.TYPE.ANSWER, answerType)
            )

            typePairList.forEachIndexed { index, pair ->
                pair.second.setOnClickListener {
                    updateTypeView(index)
                    if (mCurrentType != pair.first) {
                        mCurrentType = pair.first
                        changeType(pair.first)
                    }
                }

                // 选择默认 type
                if (mCurrentType == pair.first) {
                    pair.second.performClick()
                }
            }
        }
    }

    private fun updateTypeView(index: Int) {
        mBinding?.typeContainer?.run {
            if (index >= childCount) return

            for (i in 0 until childCount) {
                val typeTv = getChildAt(i) as TextView
                typeTv.run {
                    if (i == index) {
                        background = R.drawable.button_round_ebf5ff.toDrawable(requireContext())
                        setTextColor(R.color.theme_font.toColor(requireContext()))
                    } else {
                        background = R.drawable.button_round_fafafa.toDrawable(requireContext())
                        setTextColor(R.color.text_title.toColor(requireContext()))
                    }
                }
            }
        }
    }

    private fun changeType(type: UserHistoryViewModel.TYPE) {
        mScrollCalculatorHelper?.currentPlayer?.release()
        mScrollCalculatorHelper?.reset()
        mViewModel?.changeType(type)
    }

    private fun refreshCount(count: Int) {
        mBinding?.run {
            when (mCurrentType) {
                UserHistoryViewModel.TYPE.ALL -> {
                    allType.text = "全部 $count"
                }
                UserHistoryViewModel.TYPE.VIDEO -> {
                    mCount.video = count
                    videoType.text = "视频 $count"
                }
                UserHistoryViewModel.TYPE.COMMUNITY_ARTICLE -> {
                    mCount.communityArticle = count
                    articleType.text = "帖子 $count"
                }
                UserHistoryViewModel.TYPE.QUESTION -> {
                    mCount.question = count
                    questionType.text = "提问 $count"
                }
                UserHistoryViewModel.TYPE.ANSWER -> {
                    mCount.answer = count
                    answerType.text = "回答 $count"
                }
            }
        }
    }

    override fun provideListViewModel(): UserHistoryViewModel {
        mViewModel = viewModelProvider(
            UserHistoryViewModel.Factory(
                HaloApp.getInstance().application,
                mUserId,
                mScene,
                mCurrentType
            )
        )

        return mViewModel!!
    }

    override fun provideListAdapter(): ListAdapter<*> {
        if (mAdapter == null) {
            mAdapter = UserHistoryAdapter(
                requireContext(),
                mListViewModel,
                mEntrance
            ) { historyEntity, position ->
                if (mScene == UserHistoryViewModel.SCENE.COMMENT) {
                    val intent =
                        RatingReplyActivity.getIntent(
                            requireContext(),
                            historyEntity.comment.game.id,
                            historyEntity.comment.id,
                            mEntrance,
                            PATH_USER_COMMENT
                        )
                    SyncDataBetweenPageHelper.startActivityForResult(this, intent, 100, position)
                } else {
                    if ("community_article" == historyEntity.type || "community_article_vote" == historyEntity.type) {
                        val intent =
                            ArticleDetailActivity.getIntent(
                                requireContext(),
                                historyEntity.community,
                                historyEntity.id,
                                mEntrance,
                                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,
                            PATH_USER_QUESTION_ANSWER
                        )
                        SyncDataBetweenPageHelper.startActivityForResult(
                            this,
                            intent,
                            102,
                            position
                        )
                    } else if (historyEntity.type.contains("question")) {
                        val intent = NewQuestionDetailActivity.getIntent(
                            requireContext(),
                            historyEntity.id,
                            mEntrance,
                            PATH_USER_QUESTION_ANSWER
                        )
                        SyncDataBetweenPageHelper.startActivityForResult(
                            this,
                            intent,
                            103,
                            position
                        )
                    }
                    NewFlatLogUtils.logClickSelfPublish(
                        historyEntity.type,
                        historyEntity.id,
                        historyEntity.user?.id ?: "",
                        getCurrentTabName()
                    )
                }
            }
        }
        return mAdapter!!
    }

    private fun getCurrentTabName(): String {
        return when (mCurrentType) {
            UserHistoryViewModel.TYPE.ALL -> "全部"
            UserHistoryViewModel.TYPE.VIDEO -> "视频"
            UserHistoryViewModel.TYPE.COMMUNITY_ARTICLE -> "帖子"
            UserHistoryViewModel.TYPE.QUESTION -> "提问"
            UserHistoryViewModel.TYPE.ANSWER -> "回答"
        }
    }

    override fun getItemDecoration() = null

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

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

    override fun onLoadEmpty() {
        super.onLoadEmpty()

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

        when (mViewModel?.type) {
            UserHistoryViewModel.TYPE.ALL -> mBinding?.typeScrollView?.visibility = View.GONE
            else -> {
                mBinding?.typeScrollView?.visibility = View.VISIBLE
            }
        }
    }

    override fun onLoadError() {
        super.onLoadError()

        mListRv.visibility = View.VISIBLE
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data != null && resultCode == Activity.RESULT_OK) {
            val dataPosition = data.getIntExtra("DATA_POSITION_TAG", -1)
            if (mAdapter?.entityList?.isEmpty() == true) return
            val historyEntity = mAdapter?.entityList?.get(dataPosition)
            when (requestCode) {
                100 -> {
                    val resultData =
                        data.getParcelableExtra<RatingComment>(RatingComment::class.java.simpleName)
                    historyEntity?.apply {
                        count.vote = resultData?.vote ?: 0
                        count.reply = resultData?.reply ?: 0
                        comment.content = resultData?.content ?: ""
                        comment.star = resultData?.star ?: 0
                        me.isVoted = resultData?.me?.isVoted ?: false
                    }
                }
                101 -> {
                    val resultData =
                        data.getParcelableExtra<ArticleDetailEntity>(ArticleDetailEntity::class.java.simpleName)
                    historyEntity?.apply {
                        count.vote = resultData?.count?.vote ?: 0
                        count.comment = resultData?.count?.comment ?: 0
                        title = resultData?.title ?: ""
                        brief = resultData?.content?.removeVideoContent()?.removeInsertedContent()
                            ?.clearHtmlFormatCompletely()
                            ?: ""
                        me.isCommunityArticleVote = resultData?.me?.isCommunityArticleVote ?: false
                    }
                }
                102 -> {
                    val resultData =
                        data.getParcelableExtra<CommentEntity>(CommentEntity::class.java.simpleName)
                    historyEntity?.apply {
                        count.vote = resultData?.vote ?: 0
                        count.comment = resultData?.reply ?: 0
                        brief = resultData?.content ?: ""
                        me.isAnswerVoted = resultData?.me?.isCommentVoted ?: false
                    }
                }
                103 -> {
                    val resultData =
                        data.getParcelableExtra<QuestionsDetailEntity>(QuestionsDetailEntity::class.java.simpleName)
                    historyEntity?.apply {
                        title = resultData?.title ?: ""
                        resultData?.let {
                            count.answer = it.count.answer - count.reply
                        }
                    }
                }
                104 -> {
                    val resultData =
                        data.getParcelableExtra<ForumVideoEntity>(ForumVideoEntity::class.java.simpleName)
                    historyEntity?.apply {
                        count.vote = resultData?.count?.vote ?: 0
                        count.comment = resultData?.count?.comment ?: 0
                        des = resultData?.des ?: ""
                        title = resultData?.title ?: ""
                        me.isVoted = resultData?.me?.isVoted ?: false
                    }
                }
            }
            mAdapter?.notifyItemChanged(dataPosition)
        }
    }

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

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        initTypeView()
        mBinding?.typeScrollView?.setBackgroundColor(R.color.background_white.toColor(requireContext()))
    }

    companion object {
        const val USER_ID = "user_id"
        const val SCENE = "scene"
        const val COUNT = "count"
        const val DEFAULT_TYPE = "default_type"
        const val PATH_USER_COMMENT = "个人主页-评论"
        const val PATH_USER_QUESTION_ANSWER = "个人主页-问答"
        fun getInstance(
            userId: String,
            scene: UserHistoryViewModel.SCENE,
            count: PersonalEntity.Count,
            defaultType: UserHistoryViewModel.TYPE
        ): UserHistoryFragment {
            return UserHistoryFragment().apply {
                with(
                    bundleOf(
                        USER_ID to userId,
                        SCENE to scene,
                        COUNT to count,
                        DEFAULT_TYPE to defaultType.value
                    )
                )
            }
        }
    }

}