package com.gh.gamecenter.qa.article.detail

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.lifecycle.Lifecycle
import androidx.recyclerview.widget.RecyclerView
import com.ethanhua.skeleton.Skeleton
import com.gh.common.history.HistoryHelper
import com.gh.common.util.*
import com.gh.common.util.LogUtils
import com.gh.common.util.NewLogUtils
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.eventbus.EBReuse
import com.gh.gamecenter.common.syncpage.SyncDataEntity
import com.gh.gamecenter.common.syncpage.SyncFieldConstants
import com.gh.gamecenter.common.syncpage.SyncPageRepository
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.databinding.FragmentArticleDetailBinding
import com.gh.gamecenter.entity.*
import com.gh.gamecenter.eventbus.EBDeleteCommentDetail
import com.gh.gamecenter.eventbus.EBDeleteDetail
import com.gh.gamecenter.feature.entity.ArticleDraftEntity
import com.gh.gamecenter.feature.entity.Permissions
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.qa.article.edit.ArticleEditActivity
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.ChooseActivityDialogFragment
import com.gh.gamecenter.qa.dialog.MoreFunctionPanelDialog
import com.gh.gamecenter.qa.editor.FullScreenVideoActivity
import com.gh.gamecenter.qa.entity.ArticleDetailEntity
import com.halo.assistant.HaloApp
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*

class ArticleDetailFragment : BaseCommentFragment<CommentItemData, ArticleDetailViewModel>() {
    private var mElapsedHelper: TimeElapsedHelper? = null
    private var mScrollToCommentArea: Boolean = false
    private var mIsRecommendsContent: Boolean = false
    private var mSpecialColumn: SpecialColumn? = null
    private var mAdapter: ArticleDetailAdapter? = null
    private var mAttentionMenu: MenuItem? = null
    private lateinit var mViewModel: ArticleDetailViewModel
    private lateinit var mBinding: FragmentArticleDetailBinding
    private var mIsToolbarUserShow = false

    override fun getLayoutId() = 0

    override fun getInflatedLayout(): View {
        return FragmentArticleDetailBinding.inflate(layoutInflater, 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.logArticleDetailClick("view_article_detail")
    }

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

        initView()
        initToolbar()
        initObserver()

        mViewModel.getArticleDetail()

        mElapsedHelper = TimeElapsedHelper(this)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == ArticleDetailActivity.ARTICLE_PATCH_REQUEST && resultCode == Activity.RESULT_OK) {
            data?.getParcelableExtra<ArticleDetailEntity>(ArticleDetailEntity::class.java.simpleName)
                ?.let {
                    mViewModel.detailEntity = it
                    mAdapter?.articleDetailVH?.bindView(it)
                    updateView()
                }
            data?.getParcelableExtra<ArticleDraftEntity>(ArticleDraftEntity::class.java.simpleName)
                ?.let {
                    mViewModel.detailEntity?.me?.articleDraft = it
                }
            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?.articleDetailVH?.run {
                if (articleImgUrlList.size > 0) {
                    if (imageSet.size == articleImgUrlList.size) {
                        binding.richEditor.replaceAllDfImage()
                    } else {
                        for (i in imageSet) {
                            val url = articleImgUrlList[i.toInt()]
                            binding.richEditor.replaceDfImageByUrl(url)
                        }
                    }
                }
            }
        } else if (requestCode == CommentActivity.REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            val commentCount = data?.getIntExtra(CommentActivity.COMMENT_COUNT, 0)
            val commentId = data?.getStringExtra(EntranceConsts.KEY_COMMENT_ID)
            if (commentCount != 0 && commentCount != null) {
                mViewModel.detailEntity?.count?.comment = commentCount
                mViewModel.commentCount = commentCount
                mBinding.inputContainer.bottomCommentTv.text = mViewModel.getCommentText(
                    mViewModel.detailEntity?.count?.comment
                        ?: 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) {
            getItemClickCallback().invoke(data?.getParcelableExtra(EntranceConsts.KEY_DATA))
        } else if (requestCode == ChooseActivityDialogFragment.REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            getChooseSelectCallback().invoke(data?.getParcelableExtra(EntranceConsts.KEY_DATA))
        } else if (requestCode == FullScreenVideoActivity.REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            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?.articleDetailVH?.onVideoPlayedCallback(url, position)
                }
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        if (mViewModel.detailEntity != null) {
            HistoryHelper.insertArticleEntity(mViewModel.detailEntity!!)

            val elapsedTime = mElapsedHelper?.elapsedTime ?: 0

            LogUtils.uploadCommunityArticle(
                mEntrance,
                mViewModel.articleId,
                mViewModel.detailEntity?.title,
                elapsedTime,
                mViewModel.detailEntity?.community,
                mSpecialColumn
            )
        }
    }

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

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

    override fun onBackPressed(): Boolean {
        if (SyncDataBetweenPageHelper.setResultAndFinish(requireContext(), mViewModel.detailEntity)) {
            return true
        }

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

    @SuppressLint("AddJavascriptInterface")
    private fun initView() {
        mBinding.reuseNoneData.reuseNoneDataTv.setText(R.string.content_delete_hint)

        ViewCompat.setOnApplyWindowInsetsListener(mBinding.toolbar) { _, insets ->
            (mBinding.toolbar.layoutParams as ViewGroup.MarginLayoutParams).topMargin =
                insets.systemWindowInsetTop
            insets.consumeSystemWindowInsets()
        }
        mBinding.root.setBackgroundColor(Color.WHITE)
        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()

        mBinding.inputContainer.bottomLikeIv.setOnClickListener {
            requireContext().ifLogin("帖子详情-赞同") {
                if (mViewModel.detailEntity?.me?.isCommunityArticleVote == false) {
                    clickToastByStatus(mViewModel.detailEntity?.status ?: "") {
                        mViewModel.likeArticle()
                    }
                    if (EntranceConsts.ENTRANCE_WELCOME == mEntrance) {
                        LogUtils.uploadLikeFromWelcomeDialog()
                    }
                } else {
                    mViewModel.cancelLikeArticle()
                }
            }
        }
        val bbsType = if (mViewModel.detailEntity?.type == "game_bbs") "游戏论坛" else "综合论坛"
        mBinding.inputContainer.bottomLikeTv.setOnClickListener { mBinding.inputContainer.bottomLikeIv.performClick() }
        mBinding.inputContainer.bottomStarIv.setOnClickListener {
            requireContext().ifLogin(entrance = "帖子详情-收藏") {
                clickToastByStatus(mViewModel.detailEntity?.status ?: "") {
                    mViewModel.collectionCommand(
                        mViewModel.detailEntity?.me?.isFavorite == false,
                        callback = {
                            mViewModel.detailEntity?.me?.isFavorite = it
                            updateCollectView(it)
                        })
                }
                NewLogUtils.logCommentClick(
                    "click_comment_area_collect", mViewModel.detailEntity?.user?.id
                        ?: "", "帖子", mViewModel.detailEntity?.id
                        ?: "", mViewModel.detailEntity?.community?.id ?: "", bbsType
                )
            }
        }
        mBinding.inputContainer.bottomStarTv.setOnClickListener { mBinding.inputContainer.bottomStarIv.performClick() }

        mBinding.inputContainer.replyTv.text = "说点什么吧"
        mBinding.inputContainer.replyTv.setRoundedColorBackground(R.color.background_space_2, 19F)
        mBinding.inputContainer.replyTv.setDebouncedClickListener {
            NewLogUtils.logCommentClick(
                "click_comment_area_comment_input_box", mViewModel.detailEntity?.user?.id
                    ?: "", "帖子", mViewModel.detailEntity?.id
                    ?: "", mViewModel.detailEntity?.community?.id ?: "", bbsType
            )
            clickToastByStatus(mViewModel.detailEntity?.status ?: "") {
                startCommentActivity()
            }
        }

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

        mBinding.inputContainer.bottomCommentIv.setOnClickListener {
            // 避免由于正文内容没有加载完成导致滚不到具体位置，这里要滚两次
            mListRv.scrollToPosition(1)
            mListRv.post {
                mListRv.smoothScrollToPosition(1)
            }
            NewLogUtils.logCommentAreaEnter("帖子")
        }
        mBinding.inputContainer.bottomCommentTv.setOnClickListener { mBinding.inputContainer.bottomCommentIv.performClick() }
    }

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

                        HistoryHelper.deleteArticleEntity(mViewModel.articleId)

                        mReuseNoConn?.visibility = View.GONE
                        mReuseNoData?.visibility = View.GONE
                        mReuseDataException?.visibility = View.VISIBLE
                        if (mIsRecommendsContent) {
                            val data = Intent()
                            data.putExtra(EntranceConsts.KEY_ANSWER_ID, mViewModel.articleId)
                            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 {
                        mReuseDataException?.visibility = View.GONE
                        mReuseNoConn?.visibility = View.VISIBLE
                        mReuseNoData?.visibility = View.GONE
                        mReuseNoConn?.setOnClickListener {
                            mViewModel.getArticleDetail()
                            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.articleRenderedLiveData.observeNonNull(this) {
            showSkeleton(false)
            mBinding.root.setBackgroundColor(Color.TRANSPARENT)
            if (mViewModel.detailEntity?.images.isNullOrEmpty()
                && mViewModel.detailEntity?.videos.isNullOrEmpty()
                && mScrollToCommentArea
            ) {
                mBinding.inputContainer.bottomCommentIv.postDelayed({
                    mBinding.inputContainer.bottomCommentIv.performClick()
                }, 200)
                mScrollToCommentArea = false
            }
        }
        mViewModel.articlePageFinishedLiveData.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?.articleDetailVH?.updateFollowBtn(true)
            } else {
                mAdapter?.articleDetailVH?.updateFollowBtn(false)
            }
            updateFollowMenu(
                isFollowed,
                mViewModel.detailEntity?.user?.id == UserManager.getInstance().userId
            )
        }

        mViewModel.like.observeNonNull(this) {
            if (mViewModel.detailEntity!!.me.isCommunityArticleVote) {
                ToastUtils.showToast("已赞同")
            } else {
                ToastUtils.showToast("取消赞同")
            }
            updateLikeView(
                mViewModel.detailEntity!!.me.isCommunityArticleVote,
                mViewModel.detailEntity!!.count.vote
            )
        }

        mViewModel.highlight.observeNonNull(this) { isHighlighted ->
            if (isHighlighted) {
                if (mViewModel.detailEntity!!.me.moderatorPermissions.highlightCommunityArticle == Permissions.REPORTER) {
                    toast("提交成功")
                    mViewModel.detailEntity?.choicenessStatus = "apply"
                } else {
                    toast("操作成功")
                    mViewModel.detailEntity?.choicenessStatus = "pass"
                    mViewModel.updateDetailLiveData.postValue(mViewModel.detailEntity)
                }
            } else {
                toast("权限错误，请刷新后重试")
            }
        }
        mViewModel.cancelHighlight.observeNonNull(this) {
            if (it) {
                if (mViewModel.detailEntity!!.me.moderatorPermissions.cancelHighlightCommunityArticle == Permissions.REPORTER) {
                    toast("提交成功")
                } else {
                    toast("操作成功")
                    mViewModel.detailEntity?.choicenessStatus = "cancel"
                    mViewModel.updateDetailLiveData.postValue(mViewModel.detailEntity)
                }
            } else {
                toast("权限错误，请刷新后重试")
            }
        }
        mViewModel.applyHighlight.observeNonNull(this) {
            if (it) {
                toast("提交成功")
                mViewModel.detailEntity?.choicenessStatus = "apply"
            } else {
                toast("提交失败")
            }
        }
        mViewModel.hide.observeNonNull(this) { isHidden ->
            if (isHidden) {
                mViewModel.detailEntity?.run {
                    if (me.isModerator) {
                        if (me.moderatorPermissions.hideCommunityArticle == Permissions.REPORTER) {
                            toast("提交成功")
                        } else {
                            toast("已隐藏")
                            EventBus.getDefault().post(EBDeleteDetail(id))
                        }
                    } else {
                        toast("已删除")
                        EventBus.getDefault().post(EBDeleteDetail(id))
                    }
                    requireActivity().finish()
                }
            } else {
                toast("权限错误，请刷新后重试")
            }
        }

        mViewModel.dislike.observeNonNull(this) { disliked ->
            if (disliked) {
                toast("已反对")
                updateLikeView(false, mViewModel.detailEntity!!.count.vote)
            } else {
                toast("取消反对")
            }
        }
        mViewModel.updateDetailLiveData.observeNonNull(this) {
            mAdapter?.articleDetailVH?.bindView(it)
        }
    }

    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 {
                mViewModel.detailEntity?.let {
                    showMoreItemDialog()
                    NewLogUtils.logArticleDetailClick("click_article_detail_more")
                    NewLogUtils.logShareEnter("帖子详情页")
                }
            }
        }
        mAttentionMenu = mBinding.toolbar.menu.findItem(R.id.menu_follow)
        mAttentionMenu?.isVisible = false
    }

    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?.articleDetailVH?.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 showMoreItemDialog() {
        if (lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED) || mViewModel.detailEntity != null) {
            val entities = ArrayList<MenuItemEntity>()
            if (mViewModel.detailEntity?.user?.id == UserManager.getInstance().userId && !mViewModel.detailEntity?.me!!.isModerator && mViewModel.detailEntity?.status == "pass") {
                val isEnable =
                    mViewModel.detailEntity?.getSimplifyChoicenessStatus() != "pass"
                entities.add(
                    MenuItemEntity(
                        "申请加精",
                        if (isEnable)
                            R.drawable.icon_more_panel_essence else R.drawable.icon_more_panel_essence_unenable,
                        isEnable = isEnable
                    )
                )
            }
            if (mViewModel.detailEntity?.user?.id == UserManager.getInstance().userId && mViewModel.detailEntity?.status == "pass") {
                entities.add(MenuItemEntity("修改", R.drawable.icon_more_panel_edit))
            }
            if (mViewModel.detailEntity?.user?.id != UserManager.getInstance().userId) {
                entities.add(MenuItemEntity("投诉", R.drawable.icon_gamedetail_copyright))
            }
            val moderatorPermissions = mViewModel.detailEntity?.me?.moderatorPermissions
            if (mViewModel.detailEntity?.me?.isModerator == true && mViewModel.detailEntity?.status == "pass") {
                if (mViewModel.detailEntity?.getSimplifyChoicenessStatus() == "pass") {
                    if ((moderatorPermissions?.cancelHighlightCommunityArticle
                            ?: Permissions.GUEST) > Permissions.GUEST
                    ) {
                        entities.add(MenuItemEntity("取消精选", R.drawable.icon_more_panel_essence_cancel))
                    }
                } else {
                    if ((moderatorPermissions?.highlightCommunityArticle
                            ?: Permissions.GUEST) > Permissions.GUEST
                    ) {
                        entities.add(MenuItemEntity("加精选", R.drawable.icon_more_panel_essence))
                    }
                }
            }
            if (mViewModel.detailEntity?.me?.isModerator == true &&
                (moderatorPermissions?.updateArticleActivityTag
                    ?: Permissions.GUEST) > Permissions.GUEST &&
                mViewModel.detailEntity?.status == "pass"
            ) {
                entities.add(MenuItemEntity("修改活动标签", R.drawable.icon_more_panel_modify_label))
            }
            if (mViewModel.detailEntity?.me?.isModerator == true &&
                (moderatorPermissions?.hideCommunityArticle
                    ?: Permissions.GUEST) > Permissions.GUEST
            ) {
                entities.add(MenuItemEntity("隐藏", R.drawable.icon_more_panel_delete))
            } else {
                if (mViewModel.detailEntity?.user?.id == UserManager.getInstance().userId) {
                    entities.add(MenuItemEntity("删除", R.drawable.icon_more_panel_delete))
                }
            }

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

    private fun getShareEntity(): NormalShareEntity {
        val params = AdditionalParamsEntity().apply {
            contentType = "帖子"
            contentId = mViewModel.detailEntity?.id ?: ""
            bbsId = mViewModel.detailEntity?.community?.id ?: ""
            bbsType = if (mViewModel.detailEntity?.community?.type == "game_bbs") "游戏论坛" else "综合论坛"
            refUserId = UserManager.getInstance().userId
        }
        return NormalShareEntity(
            id = mViewModel.detailEntity?.id ?: "",
            shareUrl = requireContext().getString(
                R.string.share_community_article_url,
                mViewModel.detailEntity?.shortId
            ),
            shareIcon = if (mViewModel.detailEntity?.images?.isNotEmpty() == true) {
                mViewModel.detailEntity?.images!![0]
            } else {
                requireContext().getString(R.string.share_ghzs_logo)
            },
            shareTitle = mViewModel.detailEntity?.title ?: "",
            shareSummary = HtmlUtils.stripHtml(mViewModel.detailEntity?.content),
            shareEntrance = ShareUtils.ShareEntrance.communityArticle,
            additionalParams = params
        )
    }

    private fun getItemClickCallback(): (menuItem: MenuItemEntity?) -> Unit {
        return {
            val bbsType = if (mViewModel.detailEntity?.type == "game_bbs") "游戏论坛" else "综合论坛"
            when (it?.text) {
                "修改" -> {
                    startActivityForResult(
                        ArticleEditActivity.getPatchIntent(
                            requireContext(),
                            mViewModel.detailEntity!!
                        ), ArticleDetailActivity.ARTICLE_PATCH_REQUEST
                    )
                    NewLogUtils.logSharePanelClick(
                        "click_modification", mViewModel.detailEntity?.user?.id
                            ?: "", "帖子", mViewModel.detailEntity?.id
                            ?: "", mViewModel.detailEntity?.community?.id ?: "", bbsType
                    )
                }
                "投诉" -> {
                    ifLogin("帖子详情") {
                        BbsReportHelper.showReportDialog(mViewModel.detailEntity?.id ?: "")
                    }
                    NewLogUtils.logSharePanelClick(
                        "click_report", mViewModel.detailEntity?.user?.id
                            ?: "", "帖子", mViewModel.detailEntity?.id
                            ?: "", mViewModel.detailEntity?.community?.id ?: "", bbsType
                    )
                }
                "申请加精" -> {
                    if (mViewModel.detailEntity?.getSimplifyChoicenessStatus() == "apply") {
                        ToastUtils.showToast("申请加精审核中")
                    } else {
                        mViewModel.doApplyHighlightThisArticle(mViewModel.articleId)
                        NewLogUtils.logSharePanelClick(
                            "click_apply_essence", mViewModel.detailEntity?.user?.id
                                ?: "", "帖子", mViewModel.detailEntity?.id
                                ?: "", mViewModel.detailEntity?.community?.id ?: "", bbsType
                        )
                    }
                }
                "加精选" -> {
                    if (mViewModel.detailEntity?.getSimplifyChoicenessStatus() == "apply") {
                        ToastUtils.showToast("加精审核中")
                    } else {
                        showHighlightDialog(true)
                        NewLogUtils.logSharePanelClick(
                            "click_essence", mViewModel.detailEntity?.user?.id
                                ?: "", "帖子", mViewModel.detailEntity?.id
                                ?: "", mViewModel.detailEntity?.community?.id ?: "", bbsType
                        )
                    }
                }
                "取消精选" -> {
                    showHighlightDialog(false)
                }
                "修改活动标签" -> {
                    ChooseActivityDialogFragment.show(
                        requireActivity() as AppCompatActivity,
                        ChooseActivityDialogFragment.ActivityLabelLocation.BBS_ARTICLE,
                        mViewModel.detailEntity?.community?.id ?: "",
                        mViewModel.detailEntity?.tagActivityId,
                        tag ?: ""
                    )
                }
                "删除", "隐藏" -> {
                    DialogHelper.showDialog(
                        requireContext(),
                        "提示",
                        "${it.text}帖子后，其中的所有评论及回复都将被${it.text}",
                        it.text,
                        "取消",
                        confirmClickCallback = {
                            mViewModel.doHideThisArticle(mViewModel.articleId)
                        }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                    )
                    NewLogUtils.logSharePanelClick(
                        "click_delete", mViewModel.detailEntity?.user?.id
                            ?: "", "帖子", mViewModel.detailEntity?.id
                            ?: "", mViewModel.detailEntity?.community?.id ?: "", bbsType
                    )
                }
            }
        }
    }

    private fun getChooseSelectCallback(): (entity: ActivityLabelEntity?) -> Unit {
        val bbsType = if (mViewModel.detailEntity?.type == "game_bbs") "游戏论坛" else "综合论坛"
        return { label ->
            showUpdateLabelDialog(mViewModel.detailEntity!!, label, bbsType)
        }
    }

    private fun showUpdateLabelDialog(article: ArticleDetailEntity, label: ActivityLabelEntity?, bbsType: String) {
        var hintContent = ""
        val permissions = article.me.moderatorPermissions
        if (permissions.updateArticleActivityTag > Permissions.GUEST) {
            hintContent =
                if (permissions.updateArticleActivityTag == Permissions.REPORTER) {
                    "你的操作将提交给小编审核，确定提交吗？"
                } else {
                    "你的操作将立即生效，确定提交吗？"
                }
        }
        DialogHelper.showDialog(
            requireContext(),
            "修改活动标签",
            hintContent,
            "确定",
            "取消",
            {
                mViewModel.modifyArticleActivityTag(
                    mViewModel.articleId,
                    label
                )
                NewLogUtils.logSharePanelClick(
                    "click_modification_activity_tag",
                    mViewModel.detailEntity?.user?.id ?: "",
                    "帖子",
                    mViewModel.detailEntity?.id ?: "",
                    mViewModel.detailEntity?.community?.id ?: "",
                    bbsType
                )
            }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
        )
    }

    private fun showHighlightDialog(isHighlight: Boolean) {
        if (mViewModel.detailEntity == null) return
        val article = mViewModel.detailEntity!!
        var highlightDialogHintContent = ""
        val permissions = article.me.moderatorPermissions
        if ((isHighlight && permissions.highlightCommunityArticle > Permissions.GUEST) ||
            (!isHighlight && permissions.cancelHighlightCommunityArticle > Permissions.GUEST)
        ) {
            highlightDialogHintContent =
                if ((isHighlight && permissions.highlightCommunityArticle == Permissions.REPORTER) ||
                    (!isHighlight && permissions.cancelHighlightCommunityArticle == Permissions.REPORTER)
                ) {
                    "你的操作将提交给小编审核，确定提交吗？"
                } else {
                    "你的操作将立即生效，确定提交吗？"
                }
        }
        val title = if (isHighlight) "加精帖子" else "取消精选"
        DialogHelper.showDialog(
            requireContext(),
            title,
            highlightDialogHintContent,
            "确定",
            "取消",
            {
                if (isHighlight) {
                    mViewModel.doHighlightThisArticle(mViewModel.articleId)
                } else {
                    mViewModel.cancelHighlightThisArticle(mViewModel.articleId)
                }
            }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
        )
    }

    private fun updateView() {
        val articleDetail = mViewModel.detailEntity ?: return
        updateFollowMenu(
            articleDetail.me.isFollower,
            articleDetail.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(
            mViewModel.detailEntity?.count?.comment ?: 0, "评论"
        )

        ImageUtils.display(mBinding.userAvatar, articleDetail.user.icon)

        if (!mEntrance.contains("论坛详情")) {
            mBinding.forumContainer.visibility = View.VISIBLE
            mBinding.userContainer.visibility = View.GONE
        }

        val icon =
            if (!articleDetail.community.icon.isNullOrEmpty()) articleDetail.community.icon else articleDetail.community.game?.getIcon()
        val iconSubscript =
            if (!articleDetail.community.iconSubscript.isNullOrEmpty()) articleDetail.community.iconSubscript else articleDetail.community.game?.iconSubscript
        mBinding.forumIv.displayGameIcon(icon, iconSubscript, articleDetail.community.game?.iconFloat)
        mBinding.forumNameTv.text = articleDetail.community.name
        mBinding.forumContainer.setOnClickListener {
            DirectUtils.directForumDetail(requireContext(), articleDetail.community.id, "帖子详情")
        }

        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 = articleDetail.user.id != UserManager.getInstance().userId
                    mBinding.userNameTv.visibility = View.VISIBLE
                    mBinding.userNameTv.text = articleDetail.user.name
                    mIsToolbarUserShow = true
                    if (!mEntrance.contains("论坛详情")) {
                        mBinding.forumContainer.visibility = View.GONE
                        mBinding.userContainer.visibility = View.VISIBLE
                    }
                } else if (mIsToolbarUserShow && mListRv.computeVerticalScrollOffset() <= 56F.dip2px()) {
                    mBinding.userAvatar.visibility = View.GONE
                    mAttentionMenu?.isVisible = false
                    mBinding.userNameTv.visibility = View.GONE
                    mIsToolbarUserShow = false
                    if (!mEntrance.contains("论坛详情")) {
                        mBinding.forumContainer.visibility = View.VISIBLE
                        mBinding.userContainer.visibility = View.GONE
                    }
                }
            }

            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_article_detail_page", (filterView?.top ?: 0) > 0
                    )
                    if ((filterView?.top ?: 0) > 0) {
                        NewLogUtils.logCommentAreaEnter("帖子")
                    }
                }
            }
        })

        updateLikeView(articleDetail.me.isCommunityArticleVote, articleDetail.count.vote)
        updateCollectView(articleDetail.me.isFavorite)
    }

    @SuppressLint("SetTextI18n")
    private fun updateLikeView(alreadyLiked: Boolean, likeCount: Int) {
        mBinding.inputContainer.bottomLikeTv.text = mViewModel.getLikeText(likeCount)
        mViewModel.detailEntity?.me?.isCommunityArticleVote = alreadyLiked
        if (alreadyLiked) {
            mBinding.inputContainer.bottomLikeIv.setImageResource(R.drawable.ic_article_detail_liked_bottom_bar)
            mBinding.inputContainer.bottomLikeTv.setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    R.color.theme_font
                )
            )
        } else {
            mBinding.inputContainer.bottomLikeIv.setImageResource(R.drawable.ic_article_detail_like_bottom_bar)
            mBinding.inputContainer.bottomLikeTv.setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    R.color.text_subtitle
                )
            )
        }
    }

    private fun updateCollectView(isCollected: Boolean) {
        if (isCollected) {
            mBinding.inputContainer.bottomStarTv.text = "已收藏"
            mBinding.inputContainer.bottomStarIv.setImageResource(R.drawable.ic_article_detail_stared_bottom_bar)
            mBinding.inputContainer.bottomStarTv.setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    R.color.theme_font
                )
            )
        } else {
            mBinding.inputContainer.bottomStarTv.text = "收藏"
            mBinding.inputContainer.bottomStarIv.setImageResource(R.drawable.ic_article_detail_star_bottom_bar)
            mBinding.inputContainer.bottomStarTv.setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    R.color.text_subtitle
                )
            )
        }
    }

    override fun addSyncPageObserver() = true

    override fun provideSyncAdapter() = mAdapter

    private fun startCommentActivity(commentEntity: CommentEntity? = null) {
        mViewModel.detailEntity?.let {
            val intent = CommentActivity.getArticleCommentIntent(
                requireContext(),
                mViewModel.articleId,
                it.count.comment,
                true,
                it.community.id,
                commentEntity,
                true
            )
            startActivityForResult(intent, CommentActivity.REQUEST_CODE)
        }
    }

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

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(reuse: EBReuse) {
        if (reuse.type == Constants.LOGIN_TAG) { // 登入
            mViewModel.getArticleDetail()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(entity: EBDeleteCommentDetail) {
        //刷新 ITEM_FILTER
        mViewModel.commentCount -= 1
        mAdapter?.notifyItemChanged(1)

        //同步上级列表数据
        SyncPageRepository.postSyncData(
            SyncDataEntity(
                mViewModel.articleId,
                SyncFieldConstants.ARTICLE_COMMENT_COUNT,
                mViewModel.commentCount,
                checkFieldEntity = true
            )
        )

        //删除列表数据
        val findEntity =
            mAdapter?.entityList?.find { it.commentNormal != null && it.commentNormal?.id == entity.id }
        val index = mAdapter?.entityList?.indexOf(findEntity)
        if (findEntity != null) {
            mAdapter?.entityList?.remove(findEntity)
            mAdapter?.notifyItemRemoved(index!!)
        }

        //同步底部评论数据
        mViewModel.detailEntity?.count?.comment = (mViewModel.detailEntity?.count?.comment ?: 0) - 1
        mViewModel.loadResultLiveData.postValue(BaseCommentViewModel.LoadResult.SUCCESS)
    }

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

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mAdapter?.let { it.notifyItemRangeChanged(0, it.itemCount) }
        mBinding.toolbar.setNavigationIcon(R.drawable.ic_bar_back)
        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())
            )
        }
    }
}