package com.gh.gamecenter.qa.questions.newdetail

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.lifecycle.Lifecycle
import androidx.recyclerview.widget.RecyclerView
import com.ethanhua.skeleton.Skeleton
import com.gh.common.util.BbsReportHelper
import com.gh.common.util.LogUtils
import com.gh.common.util.NewLogUtils
import com.gh.common.util.SyncDataBetweenPageHelper
import com.gh.gamecenter.ImageViewerActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.baselist.LoadType
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.entity.AdditionalParamsEntity
import com.gh.gamecenter.common.entity.CommunityEntity
import com.gh.gamecenter.common.entity.NormalShareEntity
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.databinding.FragmentArticleDetailBinding
import com.gh.gamecenter.entity.MenuItemEntity
import com.gh.gamecenter.eventbus.EBDeleteDetail
import com.gh.gamecenter.feature.entity.Permissions
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.qa.article.detail.CommentItemData
import com.gh.gamecenter.qa.comment.CommentActivity
import com.gh.gamecenter.qa.comment.base.BaseCommentAdapter
import com.gh.gamecenter.qa.comment.base.BaseCommentFragment
import com.gh.gamecenter.qa.comment.base.BaseCommentViewModel
import com.gh.gamecenter.qa.dialog.MoreFunctionPanelDialog
import com.gh.gamecenter.qa.editor.FullScreenVideoActivity
import com.gh.gamecenter.qa.entity.QuestionsDetailEntity
import com.gh.gamecenter.qa.questions.edit.QuestionEditActivity
import com.gh.gamecenter.qa.questions.invite.QuestionsInviteActivity
import com.halo.assistant.HaloApp
import org.greenrobot.eventbus.EventBus

class NewQuestionDetailFragment :
    BaseCommentFragment<CommentItemData, NewQuestionDetailViewModel>() {
    private var mScrollToCommentArea: Boolean = false
    private var mIsRecommendsContent: Boolean = false
    private lateinit var mViewModel: NewQuestionDetailViewModel
    private var mAdapter: NewQuestionDetailAdapter? = null
    private lateinit var mBinding: FragmentArticleDetailBinding
    private var mAttentionMenu: MenuItem? = null
    private var mIsToolbarUserShow = false

    override fun getLayoutId() = 0

    override fun getInflatedLayout(): View {
        return FragmentArticleDetailBinding.inflate(
            LayoutInflater.from(requireContext()),
            null,
            false
        ).apply {
            mBinding = this
        }.root
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        mViewModel = provideListViewModel()
        super.onCreate(savedInstanceState)

        mScrollToCommentArea =
            arguments?.getBoolean(EntranceConsts.KEY_SCROLL_TO_COMMENT_AREA, false)
                ?: false
        mIsRecommendsContent = arguments?.getBoolean(EntranceConsts.KEY_RECOMMENDS_CONTENTS, false)
            ?: false
        NewLogUtils.logQuestionDetailClick("view_question_detail")
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initToolbar()
        initObserver()

        mViewModel.getQuestionDetail()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK || data == null) return
        if (requestCode == QUESTIONS_EDIT_REQUEST) {
            data.getParcelableExtra<QuestionsDetailEntity>(QuestionsDetailEntity::class.java.simpleName)
                ?.let {
                    mViewModel.questionDetail = it
                    mAdapter?.questionDetailVH?.bindView(it)
                    updateView()
                }
            mReuseNoConn?.performClick() //重新刷新
        } else if (requestCode == ImageViewerActivity.REQUEST_FOR_VIEWED_IMAGE && resultCode == Activity.RESULT_OK) {
            val imageSet = data.extras?.get(ImageViewerActivity.VIEWED_IMAGE) as HashSet<Integer>
            mAdapter?.questionDetailVH?.run {
                if (questionImgUrlList.size > 0) {
                    if (imageSet.size == questionImgUrlList.size) {
                        binding.richEditor.replaceAllDfImage()
                    } else {
                        for (i in imageSet) {
                            val url = questionImgUrlList[i.toInt()]
                            binding.richEditor.replaceDfImageByUrl(url)
                        }
                    }
                }
            }
        } else if (requestCode == CommentActivity.REQUEST_CODE) {
            val commentCount = data.getIntExtra(CommentActivity.COMMENT_COUNT, 0)
            val commentId = data.getStringExtra(EntranceConsts.KEY_COMMENT_ID)
            if (commentCount != 0) {
                // 因为answer赋值会默认加上reply数量，所以要减去reply数量才能得出真实的answer数量
                mViewModel.questionDetail?.count?.answer =
                    commentCount - (mViewModel.questionDetail?.count?.reply
                        ?: 0)
                mViewModel.commentCount = commentCount
                mBinding.inputContainer.bottomCommentTv.text = mViewModel.getCommentText(
                    mViewModel.questionDetail?.count?.answer
                        ?: 0, "回答"
                )
                updateFilterView()
                if (EntranceConsts.ENTRANCE_WELCOME == mEntrance) {
                    LogUtils.uploadCommentFromWelcomeDialog()
                }
                if (!commentId.isNullOrEmpty()) {
                    mViewModel.getSingleCommentDetail(commentId)
                } else {
                    mViewModel.load(LoadType.REFRESH)
                }
            }
        } else if (requestCode == MoreFunctionPanelDialog.REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            mViewModel.questionDetail?.run {
                getItemClickCallback(this).invoke(data.getParcelableExtra(EntranceConsts.KEY_DATA))
            }
        } else if (requestCode == FullScreenVideoActivity.REQUEST_CODE) {
            if (isAdded) {
                val url = data.extras?.getString(EntranceConsts.KEY_URL)
                val position = data.extras?.getInt(EntranceConsts.KEY_POSITION, -1) ?: -1
                if (!url.isNullOrEmpty() && position != -1) {
                    mAdapter?.questionDetailVH?.onVideoPlayedCallback(url, position)
                }
            }
        }
    }

    private fun initToolbar() {
        mBinding.toolbar.inflateMenu(R.menu.menu_article_detail)
        mBinding.toolbar.setNavigationOnClickListener {
            onBackPressed()
        }
        mBinding.toolbar.menu.findItem(R.id.menu_more).setOnMenuItemClickListener {
            consume {
                showMoreItemDialog()
                NewLogUtils.logQuestionDetailClick("click_question_detail_more")
                NewLogUtils.logShareEnter("提问详情页")
            }
        }
        mAttentionMenu = mBinding.toolbar.menu.findItem(R.id.menu_follow)
        mAttentionMenu?.isVisible = false
    }

    private fun initView() {
        mBinding.reuseNoneData.reuseNoneDataTv.text = getString(R.string.content_delete_hint)
        ViewCompat.setOnApplyWindowInsetsListener(mBinding.toolbar) { _, insets ->
            (mBinding.toolbar.layoutParams as ViewGroup.MarginLayoutParams).topMargin =
                insets.systemWindowInsetTop
            insets.consumeSystemWindowInsets()
        }
        mBinding.root.setBackgroundColor(R.color.background_white.toColor(requireContext()))
        mSkeletonScreen = Skeleton.bind(skeletonView)
            .shimmer(true)
            .angle(Constants.SHIMMER_ANGLE)
            .color(R.color.skeleton_shimmer_color)
            .duration(Constants.SHIMMER_DURATION)
            .maskWidth(Constants.MASK_WIDTH)
            .gradientCenterColorWidth(Constants.GRADIENT_CENTER_COLOR_WIDTH)
            .load(R.layout.fragment_article_detail_skeleton)
            .show()

        val bbsType = if (mViewModel.questionDetail?.type == "game_bbs") "游戏论坛" else "综合论坛"
        mBinding.inputContainer.replyTv.text = "说点什么吧"
        mBinding.inputContainer.replyTv.setRoundedColorBackground(R.color.background_space_2, 19F)
        mBinding.inputContainer.replyTv.setDebouncedClickListener {
            clickToastByStatus(mViewModel.questionDetail?.status ?: "") {
                startCommentActivity()
                NewLogUtils.logCommentClick(
                    "click_comment_area_comment_input_box", mViewModel.questionDetail?.user?.id
                        ?: "", "提问帖", mViewModel.questionDetail?.id
                        ?: "", mViewModel.questionDetail?.community?.id ?: "", bbsType
                )
            }
        }
        mBinding.inputContainer.bottomCommentTv.text = "回答"
        mBinding.inputContainer.bottomLikeTv.text = "邀请"
        mBinding.inputContainer.bottomLikeIv.setImageDrawable(
            R.drawable.ic_question_detail_invite.toDrawable(
                requireContext()
            )
        )
        updateStartButton()
        mBinding.inputContainer.bottomLikeIv.setOnClickListener {
            mViewModel.questionDetail?.let {
                clickToastByStatus(mViewModel.questionDetail?.status ?: "") {
                    startActivity(
                        QuestionsInviteActivity.getIntent(
                            requireContext(),
                            it,
                            "$mEntrance+(问题详情)"
                        )
                    )
                }
            }
        }
        mBinding.inputContainer.bottomLikeTv.setOnClickListener { mBinding.inputContainer.bottomLikeIv.performClick() }
        mBinding.inputContainer.bottomStarIv.setOnClickListener {
            debounceActionWithInterval(it.id) {
                ifLogin("问题详情") {
                    clickToastByStatus(mViewModel.questionDetail?.status ?: "") {
                        mViewModel.postFavoriteQuestion()
                        NewLogUtils.logCommentClick(
                            "click_comment_area_collect", mViewModel.questionDetail?.user?.id
                                ?: "", "提问帖", mViewModel.questionDetail?.id
                                ?: "", mViewModel.questionDetail?.community?.id ?: "", bbsType
                        )
                    }
                }
            }
        }
        mBinding.inputContainer.bottomStarTv.setOnClickListener { mBinding.inputContainer.bottomStarIv.performClick() }
        mBinding.inputContainer.bottomCommentIv.setOnClickListener {
            // 避免由于正文内容没有加载完成导致滚不到具体位置，这里要滚两次
            mListRv.scrollToPosition(1)
            mListRv.post {
                mListRv.smoothScrollToPosition(1)
            }
            NewLogUtils.logCommentAreaEnter("提问帖")
        }
        mBinding.inputContainer.bottomCommentTv.setOnClickListener { mBinding.inputContainer.bottomCommentIv.performClick() }

        mReuseNoConn?.setOnClickListener {
            mReuseNoConn?.visibility = View.GONE
            mListLoading?.visibility = View.VISIBLE
            mViewModel.getQuestionDetail()
        }
    }

    private fun initObserver() {
        mViewModel.loadResultLiveData.observeNonNull(this) {
            when (it) {
                BaseCommentViewModel.LoadResult.SUCCESS -> {
                    showSkeleton(false)
                    mBinding.root.setBackgroundColor(Color.TRANSPARENT)
                    updateView()
                }
                else -> {
                    if (it == BaseCommentViewModel.LoadResult.DELETED) {
                        mReuseNoConn?.visibility = View.GONE
                        mReuseNoData?.visibility = View.VISIBLE
                        if (mIsRecommendsContent) {
                            val data = Intent()
                            data.putExtra(EntranceConsts.KEY_ANSWER_ID, mViewModel.questionId)
                            requireActivity().setResult(Activity.RESULT_OK, data)
                            DialogHelper.showDialog(
                                requireContext(),
                                "提示",
                                "很抱歉，内容可能已被删除",
                                "关闭",
                                "",
                                { requireActivity().finish() },
                                extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                            )
                        } else {
                            toast(R.string.content_delete_toast)
                        }

                        mBinding.toolbar.menu?.run {
                            for (i in 0 until size()) {
                                getItem(i).isVisible = false
                            }
                        }
                    } else {
                        mReuseNoConn?.visibility = View.VISIBLE
                        mReuseNoData?.visibility = View.GONE
                        mReuseNoConn?.setOnClickListener {
                            mViewModel.getQuestionDetail()
                            mReuseNoConn?.visibility = View.GONE
                            showSkeleton(true)
                            mBinding.root.setBackgroundColor(Color.WHITE)
                        }
                    }

                    mListLoading?.visibility = View.GONE
                    mBinding.inputContainer.bottomContainer.visibility = View.GONE
                    mBinding.bottomShadowView.visibility = View.GONE
                    showSkeleton(false)
                    mBinding.root.setBackgroundColor(Color.TRANSPARENT)
                }
            }
        }

        mViewModel.questionRenderedLiveData.observeNonNull(this) {
            showSkeleton(false)
            mBinding.root.setBackgroundColor(Color.TRANSPARENT)
            if (mViewModel.questionDetail?.images.isNullOrEmpty()
                && mViewModel.questionDetail?.videos.isNullOrEmpty()
                && mScrollToCommentArea
            ) {
                mBinding.inputContainer.bottomCommentIv.postDelayed({
                    mBinding.inputContainer.bottomCommentIv.performClick()
                }, 200)
                mScrollToCommentArea = false
            }
        }
        mViewModel.questionPageFinishedLiveData.observeNonNull(this) {
            if (mScrollToCommentArea) {
                mBinding.inputContainer.bottomCommentIv.postDelayed({
                    mBinding.inputContainer.bottomCommentIv.performClick()
                }, 200)
                mScrollToCommentArea = false
            }
        }

        mViewModel.followLiveData.observeNonNull(this) { isFollowed ->
            if (isFollowed) {
                toast(R.string.concern_success)
                mAdapter?.questionDetailVH?.updateFollowBtn(true)
            } else {
                mAdapter?.questionDetailVH?.updateFollowBtn(false)
            }
            updateFollowMenu(
                isFollowed,
                mViewModel.questionDetail?.user?.id == UserManager.getInstance().userId
            )
        }
        mViewModel.moderatorsHideLiveData.observeNonNull(this) {
            mViewModel.questionDetail?.run {
                if (me.isModerator) {
                    if (me.moderatorPermissions.hideQuestion == Permissions.REPORTER) {
                        toast("提交成功")
                    } else {
                        toast("已隐藏")
                        EventBus.getDefault().post(EBDeleteDetail(id))
                    }
                } else {
                    toast("已删除")
                    EventBus.getDefault().post(EBDeleteDetail(id))
                }
                requireActivity().finish()
            }

        }
        mViewModel.favoriteLiveData.observeNonNull(this) {
            if (it) {
                updateStartButton()
            }
        }
        mViewModel.updateDetailLiveData.observeNonNull(this) {
            mAdapter?.questionDetailVH?.bindView(it)
        }
    }

    private fun updateStartButton() {
        mBinding.inputContainer.bottomStarIv.setImageDrawable(
            if (mViewModel.questionDetail?.me?.isFavorite == true)
                R.drawable.ic_article_detail_stared_bottom_bar.toDrawable(requireContext()) else R.drawable.ic_article_detail_star_bottom_bar.toDrawable(
                requireContext()
            )
        )
        mBinding.inputContainer.bottomStarTv.setTextColor(
            if (mViewModel.questionDetail?.me?.isFavorite == true)
                R.color.theme_font.toColor(requireContext()) else R.color.text_subtitle.toColor(requireContext())
        )
        mBinding.inputContainer.bottomStarTv.text =
            if (mViewModel.questionDetail?.me?.isFavorite == true) "已收藏" else "收藏"
    }

    private fun updateView() {
        val questionDetail = mViewModel.questionDetail ?: return
        updateStartButton()
        updateFollowMenu(
            questionDetail.me.isFollower,
            questionDetail.user.id == UserManager.getInstance().userId
        )

        mReuseNoConn?.visibility = View.GONE
        mListLoading?.visibility = View.GONE

        mBinding.inputContainer.bottomContainer.visibility = View.VISIBLE
//        mBinding.bottomShadowView.visibility = View.VISIBLE
        mBinding.inputContainer.bottomCommentTv.text =
            mViewModel.getCommentText(questionDetail.count.answer, "回答")

        ImageUtils.display(mBinding.userAvatar, questionDetail.user.icon)
        mBinding.userNameTv.text = questionDetail.community.name

        mListRv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                if (!mIsToolbarUserShow && mListRv.computeVerticalScrollOffset() > 56F.dip2px()) {
                    mBinding.userAvatar.visibility = View.VISIBLE
                    mAttentionMenu?.isVisible = questionDetail.user.id != UserManager.getInstance().userId
                    mBinding.userNameTv.visibility = View.VISIBLE
                    mBinding.userNameTv.text = questionDetail.user.name
                    mIsToolbarUserShow = true
                } else if (mIsToolbarUserShow && mListRv.computeVerticalScrollOffset() <= 56F.dip2px()) {
                    mBinding.userAvatar.visibility = View.GONE
                    mAttentionMenu?.isVisible = false
                    mBinding.userNameTv.visibility = View.GONE
                    mIsToolbarUserShow = false
                }
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    val filterView = mLayoutManager.findViewByPosition(1)
                    NewLogUtils.logSlideArticleOrQuestionDetail(
                        "提问帖详情", "slide_question_detail_page",
                        (filterView?.top ?: 0) > 0
                    )
                    if ((filterView?.top ?: 0) > 0) {
                        NewLogUtils.logCommentAreaEnter("提问帖")
                    }
                }
            }
        })
    }

    private fun updateFollowMenu(isFollow: Boolean, isOwner: Boolean) {
        mAttentionMenu?.let {
            if (isOwner) {
                it.isVisible = false
                return@let
            }
            it.isVisible = mIsToolbarUserShow
            val followBtn = it.actionView?.findViewById<TextView>(R.id.followBtn)
            followBtn?.setOnClickListener { mAdapter?.questionDetailVH?.binding?.followBtn?.performClick() }
            if (isFollow) {
                followBtn?.text = "已关注"
                followBtn?.setRoundedColorBackground(R.color.background, 999F)
                followBtn?.setTextColor(R.color.text_subtitleDesc.toColor(requireContext()))
            } else {
                followBtn?.text = "关注"
                followBtn?.setRoundedColorBackground(R.color.text_EEF5FB, 999F)
                followBtn?.setTextColor(R.color.theme_font.toColor(requireContext()))
            }
        }
    }

    private fun startCommentActivity() {
        mViewModel.questionDetail?.let {
            val intent = CommentActivity.getQuestionCommentIntent(
                requireContext(),
                it.id ?: "",
                it.count.answer,
                true,
                it.community.id,
                true
            )
            startActivityForResult(intent, CommentActivity.REQUEST_CODE)
        }
    }

    override fun provideListViewModel(): NewQuestionDetailViewModel {
        return viewModelProvider(
            NewQuestionDetailViewModel.Factory(
                HaloApp.getInstance().application,
                arguments?.getString(EntranceConsts.KEY_QUESTIONS_ID) ?: "",
                arguments?.getParcelable<CommunityEntity>(EntranceConsts.KEY_COMMUNITY_DATA)?.id ?: "",
                arguments?.getString(EntranceConsts.KEY_ANSWER_ID) ?: "",
                arguments?.getString(EntranceConsts.KEY_RECOMMEND_ID) ?: "",
                arguments?.getString(EntranceConsts.KEY_TOP_COMMENT_ID) ?: "",
            )
        )
    }

    override fun provideListAdapter(): ListAdapter<*> {
        return mAdapter
            ?: NewQuestionDetailAdapter(
                requireContext(),
                mViewModel,
                BaseCommentAdapter.AdapterType.COMMENT,
                mEntrance
            ).apply {
                mAdapter = this
            }
    }

    override fun onBackPressed(): Boolean {
        if (SyncDataBetweenPageHelper.setResultAndFinish(
                requireContext(),
                if (mViewModel.topCommentId.isNotBlank()) {
                    mViewModel.getFirstAnswer()
                } else {
                    mViewModel.questionDetail
                }
            )
        ) {
            return true
        }

        requireActivity().finish()
        return super.onBackPressed()
    }

    override fun addSyncPageObserver() = true

    override fun provideSyncAdapter() = mAdapter

    private fun showMoreItemDialog() {
        if (lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
            mViewModel.questionDetail?.let { questionEntity ->
                val entities = ArrayList<MenuItemEntity>()
                val moderatorPermissions = questionEntity.me.moderatorPermissions
                if (questionEntity.user.id != UserManager.getInstance().userId) {
                    entities.add(MenuItemEntity("投诉", R.drawable.icon_gamedetail_copyright))
                }
                if (questionEntity.user.id == UserManager.getInstance().userId && questionEntity.status == "pass") {
                    entities.add(
                        MenuItemEntity(
                            if (!questionEntity.finish) "解决" else "已解决",
                            R.drawable.icon_more_panel_solve
                        )
                    )
                }
                if ((questionEntity.me.isModerator || questionEntity.user.id == UserManager.getInstance().userId) && questionEntity.status == "pass") {
                    entities.add(MenuItemEntity("编辑", R.drawable.icon_more_panel_edit))
                }
                if (questionEntity.me.isModerator &&
                    moderatorPermissions.hideQuestion > Permissions.GUEST
                ) {
                    entities.add(MenuItemEntity("隐藏", R.drawable.icon_more_panel_delete))
                } else {
                    if (questionEntity.user.id == UserManager.getInstance().userId) {
                        entities.add(MenuItemEntity("删除", R.drawable.icon_more_panel_delete))
                    }
                }

                MoreFunctionPanelDialog.showMoreDialog(
                    requireActivity() as AppCompatActivity, entities, questionEntity.title
                        ?: "", getShareEntity(questionEntity), questionEntity.status, tag ?: ""
                )
            }
        }
    }

    private fun getShareEntity(questionEntity: QuestionsDetailEntity): NormalShareEntity {
        val params = AdditionalParamsEntity().apply {
            contentType = "提问帖"
            contentId = mViewModel.questionDetail?.id ?: ""
            bbsId = mViewModel.questionDetail?.community?.id ?: ""
            bbsType = if (mViewModel.questionDetail?.community?.type == "game_bbs") "游戏论坛" else "综合论坛"
            refUserId = UserManager.getInstance().userId
        }
        return NormalShareEntity(
            id = questionEntity.id ?: "",
            shareUrl = if (isPublishEnv()) {
                getString(R.string.share_questions_url, questionEntity.id)
            } else {
                getString(R.string.share_questions_url_dev, questionEntity.id)
            },
            shareIcon = if (questionEntity.images.isNotEmpty()) {
                questionEntity.images[0]
            } else {
                getString(R.string.share_ghzs_logo)
            },
            shareTitle = questionEntity.title ?: "",
            shareSummary = if (TextUtils.isEmpty(questionEntity.description)) {
                getString(R.string.ask_share_default_summary)
            } else {
                questionEntity.description!!
            },
            shareEntrance = ShareUtils.ShareEntrance.askNormal,
            additionalParams = params
        )
    }

    private fun getItemClickCallback(questionEntity: QuestionsDetailEntity): (menuItem: MenuItemEntity?) -> Unit {
        return {
            val bbsType = if (mViewModel.questionDetail?.type == "game_bbs") "游戏论坛" else "综合论坛"
            when (it?.text) {
                "投诉" -> {
                    ifLogin("提问贴") {
                        BbsReportHelper.showReportDialog(
                            mViewModel.questionDetail?.id
                                ?: ""
                        )
                    }
                    NewLogUtils.logSharePanelClick(
                        "click_report", mViewModel.questionDetail?.user?.id
                            ?: "", "提问帖", mViewModel.questionDetail?.id
                            ?: "", mViewModel.questionDetail?.community?.id
                            ?: "", bbsType
                    )
                }
                "编辑" -> {
                    val intent = if (questionEntity.me.isModerator) {
                        QuestionEditActivity.getManagerIntent(
                            requireContext(),
                            questionEntity
                        )
                    } else {
                        QuestionEditActivity.getIntent(requireContext(), questionEntity)
                    }
                    startActivityForResult(
                        intent,
                        QUESTIONS_EDIT_REQUEST
                    )
                    NewLogUtils.logSharePanelClick(
                        "click_modification_question", mViewModel.questionDetail?.user?.id
                            ?: "", "提问帖", mViewModel.questionDetail?.id
                            ?: "", mViewModel.questionDetail?.community?.id ?: "", bbsType
                    )
                }

                "删除", "隐藏" -> {
                    DialogHelper.showDialog(
                        requireContext(),
                        "提示",
                        "${it.text}问题后，其中的所有回答都将被${it.text}",
                        it.text,
                        "取消",
                        { mListViewModel.moderatorsHideQuestion() },
                        extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                    )
                    NewLogUtils.logSharePanelClick(
                        "click_delete", mViewModel.questionDetail?.user?.id
                            ?: "", "提问帖", mViewModel.questionDetail?.id
                            ?: "", mViewModel.questionDetail?.community?.id ?: "", bbsType
                    )
                }
                "解决", "已解决" -> {
                    val content =
                        if (!questionEntity.finish) "该问题确定标记已解决？" else "该问题确定标记未解决？"
                    DialogHelper.showDialog(requireContext(), "提示", content, "确定", "取消", {
                        mListViewModel.postSolveQuestion(!questionEntity.finish)
                    }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true))
                    NewLogUtils.logSharePanelClick(
                        if (!questionEntity.finish) "click_solve" else "click_resolved",
                        mViewModel.questionDetail?.user?.id
                            ?: "",
                        "提问帖",
                        mViewModel.questionDetail?.id
                            ?: "",
                        mViewModel.questionDetail?.community?.id ?: "",
                        bbsType
                    )
                }
            }
        }
    }

    override fun onStop() {
        super.onStop()
        val stayTime = (System.currentTimeMillis() - startPageTime) / 1000
        val bbsType = if (mViewModel.questionDetail?.type == "game_bbs") "游戏论坛" else "综合论坛"
        NewLogUtils.logActivityPause(
            "提问帖详情", "jump_question_detail", stayTime,
            mViewModel.questionDetail?.community?.id ?: "", bbsType, "提问帖",
            mViewModel.questionDetail?.id ?: ""
        )
    }

    override fun onLoadRefresh() {
        super.onLoadRefresh()
        mBinding.root.setBackgroundColor(Color.WHITE)
    }

    override fun onLoadDone() {
        super.onLoadDone()
        mBinding.root.setBackgroundColor(Color.TRANSPARENT)
    }

    override fun onLoadError() {
        super.onLoadError()
        mBinding.root.setBackgroundColor(Color.TRANSPARENT)
    }

    override fun onLoadEmpty() {
        super.onLoadEmpty()
        mBinding.root.setBackgroundColor(Color.TRANSPARENT)
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mAdapter?.let { it.notifyItemRangeChanged(0, it.itemCount) }
        mBinding.fixedTopFilterView.orderSfv.run {
            setContainerBackground(R.drawable.button_round_f5f5f5.toDrawable(requireContext()))
            setIndicatorBackground(R.drawable.bg_game_collection_sfv_indicator.toDrawable(requireContext()))
            setTextColor(
                R.color.text_subtitle.toColor(requireContext()),
                R.color.text_subtitleDesc.toColor(requireContext())
            )
        }
    }

    companion object {
        const val QUESTIONS_EDIT_REQUEST = 111
    }
}