package com.gh.gamecenter.qa.article.edit

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Message
import android.text.TextUtils
import android.view.MenuItem
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.widget.doOnTextChanged
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.gh.base.BaseRichEditorActivity
import com.gh.common.util.ErrorHelper
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.fragment.WaitingDialogFragment
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.entity.CommunityEntity
import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.AppExecutor
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.databinding.ActivityCommunityArticleEditBinding
import com.gh.gamecenter.entity.ActivityLabelEntity
import com.gh.gamecenter.entity.ForumDetailEntity
import com.gh.gamecenter.feature.entity.ArticleDraftEntity
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.qa.BbsType
import com.gh.gamecenter.qa.article.draft.ArticleDraftActivity
import com.gh.gamecenter.qa.dialog.ChooseActivityDialogFragment
import com.gh.gamecenter.qa.dialog.ChooseForumActivity
import com.gh.gamecenter.qa.dialog.ChooseSectionDialogFragment
import com.gh.gamecenter.qa.editor.GameActivity
import com.gh.gamecenter.qa.entity.ArticleDetailEntity
import com.gh.gamecenter.qa.questions.edit.TagsSelectFragment
import com.gh.gamecenter.qa.video.publish.VideoPublishFragment
import com.gh.gamecenter.video.poster.video.VideoPosterFragment
import com.lightgame.utils.Util_System_Keyboard
import com.lightgame.utils.Utils
import org.greenrobot.eventbus.EventBus

/**
 * 发布帖子/修改帖子
 */
class ArticleEditActivity : BaseRichEditorActivity<ArticleEditViewModel>(), KeyboardHeightObserver {
    private lateinit var mMenuDraft: MenuItem
    private lateinit var mMenuPost: MenuItem
    private var mProcessingDialog: WaitingDialogFragment? = null
    private var mUploadImageCancelDialog: DialogHelper.DialogAlertDefaultBindingWrapper? = null
    private var mPostDraftsCount: Int = 0
    private var mArticleTagsSelectFragment: ArticleTagsSelectFragment? = null
    private lateinit var mBinding: ActivityCommunityArticleEditBinding

    override fun mtaEventName(): String {
        return "社区文章详情" // issues 定的就是社区文章详情
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_community_article_edit
    }

    override fun handleMessage(msg: Message) {
        super.handleMessage(msg)
        if (msg.what == 1) {
            if (!TextUtils.isEmpty(mBinding.articleEditTitle.text.trim())
                && (!TextUtils.isEmpty(mRichEditor.text)
                        || mRichEditor.html.contains("<img src"))
                && !mRichEditor.hasPlaceholderImage()
            ) {
                mViewModel.title = mBinding.articleEditTitle.text.toString()
                mViewModel.content = getReplaceRealContent()
                mViewModel.postArticleDrafts(SaveDraftType.AUTO)
            }
            mBaseHandler.sendEmptyMessageDelayed(1, SAVE_DRAFTS_INTERVAL_TIME.toLong())
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null || resultCode != Activity.RESULT_OK) return
        if (requestCode == ARTICLE_DRAFT_REQUEST_CODE) {
            val draftEntity = data.getParcelableExtra<ArticleDraftEntity>(ArticleDraftEntity::class.java.simpleName)
            if (draftEntity != null) {
                mViewModel.draftEntity = draftEntity
                setArticleDraft()
            }
        } else if (requestCode == ChooseForumActivity.CHOOSE_FORUM_REQUEST) {
            val community = data.getParcelableExtra<CommunityEntity>(EntranceConsts.KEY_COMMUNITY_DATA)
            mViewModel.type = community?.type ?: ""
            mViewModel.mSelectCommunityData = community
            if (mViewModel.type == BbsType.GAME_BBS.value) {
                mViewModel.gameEntity = null
            }
            setGameName()
            resetSection()
        } else if (requestCode == VideoPublishFragment.REQUEST_GAME_CODE) {
            val game = data.getParcelableExtra<GameEntity>(GameEntity::class.java.simpleName)
            if (game != null) {
                mViewModel.gameEntity = game
                setGameName()
            }
        }
    }

    override fun onActivityDialogResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == ChooseActivityDialogFragment.REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            getChooseSelectCallback().invoke(data?.getParcelableExtra(EntranceConsts.KEY_DATA))
        }
        if (requestCode == ChooseSectionDialogFragment.REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            data?.getParcelableExtra<ForumDetailEntity.Section>(EntranceConsts.KEY_DATA)?.let {
                mBinding.articleSectionName.text = it.name
                mViewModel.selectSection = it
                setSectionUI(false)
            }
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        VideoPosterFragment.clearVideoCoverCache(this)
        updateStatusBarColor(com.gh.gamecenter.common.R.color.ui_surface, com.gh.gamecenter.common.R.color.ui_surface)
        mBinding = ActivityCommunityArticleEditBinding.bind(mContentView)
        setToolbarMenu(R.menu.menu_answer_post)
        mMenuDraft = getMenuItem(R.id.menu_draft)
        mMenuPost = getMenuItem(R.id.menu_answer_post)
        mToolbar.navigationIcon = null
        mMenuDraft.isVisible = true
        checkPostButtonEnable()
        initListener()
        mRichEditor.setOnTextChangeListener { t ->
            if (t.contains("<blockquote>") || t.contains("<img src") || !TextUtils.isEmpty(mRichEditor.text) || mViewModel.localVideoList.isNotEmpty()) {
                mBinding.articlePlaceholder.visibility = View.GONE
            } else {
                mBinding.articlePlaceholder.visibility = View.VISIBLE
            }
            checkPostButtonEnable()
        }

        mBinding.articleEditTitle.setOnTouchListener { _, _ ->
            closeExtendedKeyboard()
            false
        }
        mBinding.articleEditTitle.setOnFocusChangeListener { _, hasFocus ->
            controlEditorInsertContainerEnabled(!hasFocus)
        }

        //setEditTextInputSpace()
        mBinding.articleEditTitle.filters = arrayOf(TextHelper.getFilter(50, "标题最多50个字"))

        mBinding.articleEditTitle.doOnTextChanged { text, start, _, _ ->
            if (text?.contains("\n") == true) {
                mBinding.articleEditTitle.setText(text.toString().replace("\n", ""))
                mBinding.articleEditTitle.setSelection(start)
                return@doOnTextChanged
            }
            if (PatternUtils.isHasSpace(text.toString())) {
                mBinding.articleEditTitle.setText(PatternUtils.replaceSpace(text.toString()))
                mBinding.articleEditTitle.setSelection(start)
                return@doOnTextChanged
            }
            checkPostButtonEnable()
        }

        observeData()

        val bbsType = if (mViewModel.mSelectCommunityData?.type == "official_bbs") "综合论坛" else "游戏论坛"
        SensorsBridge.trackEvent(
            "ViewPostArticle",
            "source_entrance",
            mEntrance,
            "article_type",
            "帖子",
            "bbs_type",
            bbsType,
            "bbs_id",
            mViewModel.mSelectCommunityData?.id ?: ""
        )
    }

    override fun provideViewModel(): ArticleEditViewModel {
        mViewModel = ViewModelProviders.of(this).get(ArticleEditViewModel::class.java)
        mViewModel.detailEntity = intent.getParcelableExtra(ArticleDetailEntity::class.java.simpleName)
        mViewModel.draftEntity = intent.getParcelableExtra(ArticleDraftEntity::class.java.simpleName)
        mViewModel.openArticleInNewPage = intent.getBooleanExtra(EntranceConsts.KEY_ARTICLE_OPEN_IN_NEW_PAGE, false)
        return mViewModel
    }

    private fun observeData() {
        mViewModel.detailEntityLiveData.observe(this) {
            if (it != null) {
                mViewModel.detailEntity = it
                setPatchContent()
            } else {
                Utils.toast(this, "获取帖子详情失败")
            }
        }
        // 保存草稿
        mViewModel.postArticleDrafts.observe(this, Observer { pair ->
            if (pair != null) {
                when (pair.first) {
                    SaveDraftType.EXIT -> {
                        if (pair.second) {
                            if (mViewModel.detailEntity != null) {
                                val intent = Intent()
                                intent.putExtra(ArticleDraftEntity::class.java.simpleName, mViewModel.draftEntity)
                                setResult(Activity.RESULT_OK, intent)
                                if (mViewModel.checkIsAllUploadedAndToast()) {
                                    Utils.toast(this, "内容已保存至草稿箱")
                                }
                            } else {
                                if (mViewModel.checkIsAllUploadedAndToast()) {
                                    Utils.toast(this, "帖子已保存到草稿箱")
                                }
                            }
                            EventBus.getDefault().post(EBReuse(ARTICLE_DRAFT_CHANGE_TAG))
                            finish()
                        }
                    }

                    SaveDraftType.AUTO -> {
                        if (pair.second) {
                            if (mPostDraftsCount >= SAVE_DRAFTS_TOAST_COUNT) {
                                mPostDraftsCount = 0
                                Utils.toast(this, "帖子已保存到草稿箱")
                            } else {
                                mPostDraftsCount++
                            }
                        }
                    }

                    SaveDraftType.SKIP -> {
                        if (pair.second) {
                            Utils.toast(this, "帖子已保存到草稿箱")
                            startActivityForResult(ArticleDraftActivity.getIntent(this), ARTICLE_DRAFT_REQUEST_CODE)
                        } else {
                            Utils.toast(this, "帖子草稿保存失败")
                        }
                    }
                }
            }
        })

        // 获取新闻内容（编辑草稿时）
        mViewModel.articleDraftsContent.observe(this, Observer {
            setEditHtml(it)
            mViewModel.draftEntity?.content = mRichEditor.html
        })

        mViewModel.processDialog.observe(this, Observer {
            if (it?.isShow!!) {
                if (mProcessingDialog?.dialog?.isShowing == true) {
                    mProcessingDialog?.uploadWaitingHint(it.msg)
                } else {
                    mProcessingDialog = WaitingDialogFragment.newInstance(it.msg, false)
                    mProcessingDialog?.show(supportFragmentManager, null) {
                        if (mViewModel.uploadImageSubscription != null && !mViewModel?.uploadImageSubscription!!.isDisposed) {
                            mUploadImageCancelDialog = DialogHelper.showDialog(
                                this, "提示", "图片正在上传中，确定取消吗？",
                                "确定", "取消", {
                                    mViewModel.uploadImageSubscription!!.dispose()
                                    mUploadImageCancelDialog?.dismiss()
                                    mProcessingDialog?.dismiss()
                                }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                            )
                        }
                    }
                }
            } else {
                mUploadImageCancelDialog?.dismiss()
                mProcessingDialog?.dismiss()
            }
        })

        mViewModel.error.observeNonNull(this) {
            ErrorHelper.handleError(this, it, false, "发帖子（普通）", "社区实名", "帖子") {
                if (::mMenuPost.isInitialized) {
                    onMenuItemClick(mMenuPost)
                }
            }
        }

        mBaseHandler.sendEmptyMessageDelayed(1, SAVE_DRAFTS_INTERVAL_TIME.toLong())
        when {
            mViewModel.detailEntity != null -> { // 修改文章 内容填充
                setNavigationTitle("修改帖子")
                showPatchDraftDialogIfExisted()
            }

            !mViewModel.draftEntity?.articleId.isNullOrEmpty() && mViewModel.detailEntity == null -> {
                setNavigationTitle("修改帖子")
                mViewModel.getArticleDetail(mViewModel.draftEntity?.articleId ?: "")
            }

            mViewModel.draftEntity != null -> {
                setNavigationTitle("发布帖子")
                setArticleDraft()
            }

            else -> {// 启动自动保存草稿
                setNavigationTitle("发布帖子")
                mViewModel.mSelectCommunityData = intent.getParcelableExtra(CommunityEntity::class.java.simpleName)
                mViewModel.type = intent?.getStringExtra(BbsType::class.java.simpleName) ?: ""
                if (mViewModel.mSelectCommunityData != null) {
                    setGameName()
                    resetSection()
                    if (mViewModel.type == BbsType.GAME_BBS.value) {
                        mBinding.articleGameName.isEnabled = false
                    }
                }
                mBinding.articleEditTitle.requestFocus()
                showUploadVideoGuide()
            }
        }
        mViewModel.notSelectForum.observe(this, Observer {
            if (it) showSelectGameDialog()
        })
        mViewModel.sectionListLiveData.observeNonNull(this) {
            mBinding.arrowIv.goneIf(it.isEmpty())
            mBinding.articleSectionContainer.goneIf(it.isEmpty())
        }
    }

    override fun getSelectedLabel(): Int = mViewModel.selectedTags.size

    private fun initListener() {
        mBinding.backBtn.setOnClickListener {
            val bbsType =
                if (mViewModel.type.isNotEmpty()) if (mViewModel.type == "game_bbs") "游戏论坛" else "综合论坛" else ""
            NewLogUtils.logArticleEditClick(
                "click_article_cancel", mViewModel.mSelectCommunityData?.id
                    ?: "",
                bbsType, mViewModel.selectActivityLabelEntity?.name
                    ?: "", mOriginalCb.isChecked, mViewModel.quoteCountEntity
            )
            SensorsBridge.trackEvent("ArticleCancelclick")
            onBackPressed()
        }
        mBinding.articleGameName.setOnClickListener {
//            MtaHelper.onEvent("发表文章", "指定游戏", CommunityManager.getInstance().community.name)
            showSelectGameDialog()
        }
        mBinding.activityTv.setOnClickListener {
            if (mViewModel.mSelectCommunityData == null || mViewModel.mSelectCommunityData?.id?.isEmpty() == true) {
                toast("请先选择论坛")
                showSelectGameDialog()
                return@setOnClickListener
            }
            val delayTime = if (mIsKeyBoardShow) {
                Util_System_Keyboard.hideSoftKeyboard(this)
                200L
            } else 0L
            AppExecutor.uiExecutor.executeWithDelay({
                ChooseActivityDialogFragment.show(
                    this,
                    ChooseActivityDialogFragment.ActivityLabelLocation.BBS_ARTICLE,
                    mViewModel.mSelectCommunityData?.id ?: "",
                    mViewModel.selectActivityLabelEntity?.id,
                    "editorActivity"
                )
            }, delayTime)
        }
        mBinding.articleSectionName.setOnClickListener {
            val delayTime = if (mIsKeyBoardShow) {
                Util_System_Keyboard.hideSoftKeyboard(this)
                200L
            } else 0L
            AppExecutor.uiExecutor.executeWithDelay({
                ChooseSectionDialogFragment.show(
                    this,
                    mViewModel.mSelectCommunityData?.id ?: "",
                    mViewModel.selectSection?.id ?: "",
                    mViewModel.isModerator,
                    "editorActivity"
                )
            }, delayTime)
        }
        mBinding.clearIv.setOnClickListener {
            setSectionUI(true)
            mViewModel.selectSection = null
        }
    }

    private fun getChooseSelectCallback(): (entity: ActivityLabelEntity?) -> Unit {
        return {
            mViewModel.selectActivityLabelEntity = it
            mBinding.activityTv.text = it?.name ?: "添加话题标签"
            mBinding.activityTv.setTextColor(
                if (it != null) com.gh.gamecenter.common.R.color.text_FA8500.toColor(this) else com.gh.gamecenter.common.R.color.text_primary.toColor(
                    this
                )
            )
        }
    }

    private fun setArticleDraft() {
        val community = mViewModel.draftEntity?.community
        if (!community?.id.isNullOrEmpty() && !community?.name.isNullOrEmpty()) {
            mViewModel.mSelectCommunityData = mViewModel.draftEntity?.community
            mViewModel.mSelectCommunityData?.icon = mViewModel.draftEntity?.community?.game?.getIcon()
            mViewModel.mSelectCommunityData?.iconSubscript = mViewModel.draftEntity?.community?.game?.iconSubscript
        }
        if (!mViewModel.draftEntity?.tagActivityId.isNullOrEmpty() && !mViewModel.draftEntity?.tagActivityName.isNullOrEmpty()) {
            mViewModel.selectActivityLabelEntity = ActivityLabelEntity(
                mViewModel.draftEntity?.tagActivityId
                    ?: "", mViewModel.draftEntity?.tagActivityName ?: ""
            )
            mBinding.activityTv.text = mViewModel.draftEntity?.tagActivityName ?: ""
            mBinding.activityTv.setTextColor(com.gh.gamecenter.common.R.color.text_FA8500.toColor(this))
        }
        mViewModel.type = mViewModel.draftEntity?.type ?: ""
        mBinding.articleEditTitle.setText(mViewModel.draftEntity?.title)
        mBinding.articleGameName.isEnabled = true
        setGameName()
        resetSection()
        mViewModel.getArticleDraftsContent(mViewModel.draftEntity?.id!!)
    }

    private fun showPatchDraftDialogIfExisted() {
        if (mViewModel.detailEntity?.me?.articleDraft != null) {
            DialogHelper.showDialog(
                this,
                "提示",
                "是否继续上次修改？",
                "是",
                "否",
                confirmClickCallback = {
                    mViewModel.draftEntity = mViewModel.detailEntity?.me?.articleDraft
                    setPatchContent()
                },
                cancelClickCallback = {
                    setPatchContent()
                },
                extraConfig = DialogHelper.Config(
                    centerContent = true,
                    centerTitle = true
                )
            )?.run {
                setCancelable(false)
            }
        } else {
            setPatchContent()
        }
    }

    private fun setPatchContent() {
        //编辑贴子可能存在草稿
        mViewModel.type = mViewModel.detailEntity?.type ?: ""
        mViewModel.mSelectCommunityData = mViewModel.detailEntity?.community
        mViewModel.mSelectCommunityData?.icon = mViewModel.detailEntity?.community?.game?.getIcon()
        mViewModel.mSelectCommunityData?.iconSubscript = mViewModel.detailEntity?.community?.game?.iconSubscript
        mViewModel.gameEntity = mViewModel.detailEntity?.gameEntity
        if (!mViewModel.detailEntity?.tagActivityId.isNullOrEmpty() && !mViewModel.detailEntity?.tagActivityName.isNullOrEmpty()) {
            mViewModel.selectActivityLabelEntity = ActivityLabelEntity(
                mViewModel.detailEntity?.tagActivityId
                    ?: "", mViewModel.detailEntity?.tagActivityName ?: ""
            )
            mBinding.activityTv.text = mViewModel.detailEntity?.tagActivityName ?: ""
            mBinding.activityTv.setTextColor(com.gh.gamecenter.common.R.color.text_FA8500.toColor(this))
        }
        setGameName()
        resetSection()

        mMenuDraft.isVisible = true
        mBinding.articleGameName.isEnabled = false
        mBinding.activityTv.isEnabled = false
        mBinding.articleSectionName.isEnabled = false
        mBinding.clearIv.isEnabled = false

        // 编辑文章时可能存在草稿
        if (mViewModel.draftEntity != null) {
            mBinding.articleEditTitle.setText(mViewModel.draftEntity?.title)
            mViewModel.getArticleDraftsContent(mViewModel.draftEntity?.id!!)
        } else {
            mBinding.articleEditTitle.setText(mViewModel.detailEntity?.rawTitle ?: mViewModel.detailEntity?.title)
            setEditHtml(mViewModel.detailEntity?.rawContent ?: mViewModel.detailEntity?.content)
        }
    }

    private fun setEditHtml(html: String?) {
        mRichEditor.setHtml(html, false)
        try {
            mRichEditor.scrollTo(0, 10000000)
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    private fun getReplaceRealContent(): String {
        var content = mRichEditor.html
        for (s in mViewModel.mapImages.keys) {
            content = content?.replace(FILE_HOST + s, mViewModel.mapImages[s].toString())
        }
        return content
    }

    override fun handleBackPressed(): Boolean {
        if (super.handleBackPressed()) {
            return true
        }

        if (TextUtils.isEmpty(UserManager.getInstance().token)) {
            return false
        }

        //帖子发布，需判断是否输入了内容，输入了则弹窗提示
        if (mViewModel.detailEntity == null && mViewModel.draftEntity == null) {
            if (mBinding.articleEditTitle.text.toString().isNotEmpty() || mRichEditor.html.isNotEmpty()) {
                SensorsBridge.trackEvent("ArticleCancelDialogShow")
                DialogHelper.showDialog(this, "提示", "是否保存内容再退出？", "保存并退出", "不保存", {
                    SensorsBridge.trackEvent("ArticleCancelDialogClick", "button_name", "保存并退出")
                    mViewModel.title = mBinding.articleEditTitle.text.toString()
                    mViewModel.content = getReplaceRealContent()
                    mViewModel.postArticleDrafts(SaveDraftType.EXIT)
                }, {
                    SensorsBridge.trackEvent("ArticleCancelDialogClick", "button_name", "不保存")
                    finish()
                }, extraConfig = DialogHelper.Config(showCloseIcon = true, centerContent = true, centerTitle = true))
                return true
            }
        }

        //帖子编辑，需要判断是否修改过
        if (mViewModel.detailEntity != null && mViewModel.draftEntity == null) {
            return if (mViewModel.detailEntity?.title != mBinding.articleEditTitle.text.toString()
                // 内容相对已发布的有变更
                || (mViewModel.detailEntity?.content != mRichEditor.html && mViewModel.detailEntity?.rawContent != mRichEditor.html)
            ) {
                showBackDialog()
                true
            } else false
        }

        //检查草稿数据
        return !checkDraft(SaveDraftType.EXIT)
    }

    private fun checkDraft(saveType: SaveDraftType): Boolean {
        val draftEntity = mViewModel.draftEntity ?: return true
        if (draftEntity.title.isEmpty() && draftEntity.content.isEmpty()) return true
        if (saveType == SaveDraftType.SKIP) {
            //判断是否修改了草稿，修改了需自动保存无需提示
            if (draftEntity.title != mBinding.articleEditTitle.text.toString()
                || mViewModel.articleDraftsContent.value != mRichEditor.html
            ) {
                mViewModel.title = mBinding.articleEditTitle.text.toString()
                mViewModel.content = getReplaceRealContent()
                mViewModel.postArticleDrafts(SaveDraftType.AUTO)
                return true
            }
        } else if (saveType == SaveDraftType.EXIT) {
            //退出页面需判断是否修改了草稿，修改了需弹窗提示
            if (draftEntity.title != mBinding.articleEditTitle.text.toString()
                || mViewModel.articleDraftsContent.value != mRichEditor.html
            ) {
                showBackDialog()
                return false
            }
        }
        return true
    }

    private fun checkPostButtonEnable() {
        mViewModel.title = mBinding.articleEditTitle.text.toString()
        mViewModel.content = getReplaceRealContent()
        mMenuPost.actionView?.postDelayed({
            val isEnabled = mViewModel.checkData()
            mMenuPost.actionView?.alpha = if (isEnabled) 1f else 0.6f
        }, 100)
    }

    private fun showBackDialog() {
        if (mRichEditor.hasPlaceholderImage()) return
        DialogHelper.showDialog(
            this,
            "提示",
            "是否保存内容再退出？",
            "保存并退出",
            "不保存",
            {
                mViewModel.title = mBinding.articleEditTitle.text.toString()
                mViewModel.content = getReplaceRealContent()
                mViewModel.postArticleDrafts(SaveDraftType.EXIT)
            },
            { finish() },
            extraConfig = DialogHelper.Config(showCloseIcon = true, centerTitle = true, centerContent = true)
        )
    }

    private fun showSelectGameDialog() {
        if (mViewModel.type == BbsType.OFFICIAL_BBS.value) {
            startActivityForResult(
                GameActivity.getIntent(this, GameActivity.SELECT_GAME_TITLE),
                VideoPublishFragment.REQUEST_GAME_CODE
            )
        } else {
            val delayTime = if (mIsKeyBoardShow) {
                Util_System_Keyboard.hideSoftKeyboard(this)
                200L
            } else 0L
            AppExecutor.uiExecutor.executeWithDelay(Runnable {
                ChooseForumActivity.startChooseForumActivity(this, "社区")
            }, delayTime)
            NewLogUtils.logChooseForumPanelEnter("发帖子")
        }
    }

    private fun setGameName() {
        if (mViewModel.mSelectCommunityData != null) {
            if (mViewModel.type == BbsType.GAME_BBS.value) {
                mBinding.articleGameName.text = mViewModel.mSelectCommunityData?.name
                mBinding.forumIconView.displayGameIcon(
                    mViewModel.mSelectCommunityData?.icon,
                    mViewModel.mSelectCommunityData?.iconSubscript
                )
                setForumUI()
            } else if (mViewModel.type == BbsType.OFFICIAL_BBS.value) {
                if (mViewModel.gameEntity == null) {
                    mBinding.articleGameName.text = "选择游戏"
                    mBinding.forumIconView.visibility = View.GONE
                } else {
                    mBinding.articleGameName.text = mViewModel.gameEntity?.name
                    mBinding.forumIconView.displayGameIcon(
                        mViewModel.gameEntity?.icon,
                        mViewModel.gameEntity?.iconSubscript
                    )
                    setForumUI()
                }
            }
        } else {
            if (mViewModel.type == BbsType.GAME_BBS.value) {
                mBinding.articleGameName.text = "选择论坛"
            } else if (mViewModel.type == BbsType.OFFICIAL_BBS.value) {
                mBinding.articleGameName.text = "选择游戏"
            }
        }

        val beginTransaction = supportFragmentManager.beginTransaction()
        mArticleTagsSelectFragment = ArticleTagsSelectFragment.getInstance()
        beginTransaction.replace(R.id.tagsContainer, mArticleTagsSelectFragment!!, TagsSelectFragment::javaClass.name)
        beginTransaction.commitAllowingStateLoss()
        mViewModel.selectedTags.clear()
        mViewModel.selectedTagsChange.postValue(true)
        checkPostButtonEnable()
    }

    private fun setForumUI() {
        mBinding.forumIconView.visibility = View.VISIBLE
        mBinding.forumContainer.background =
            ContextCompat.getDrawable(this, com.gh.gamecenter.common.R.drawable.bg_shape_f5_radius_999)
        mBinding.articleGameName.setTextColor(
            ContextCompat.getColor(
                this,
                com.gh.gamecenter.common.R.color.text_secondary
            )
        )
    }

    private fun setSectionUI(isEmpty: Boolean) {
        mBinding.run {
            articleSectionContainer.background =
                if (isEmpty) R.drawable.button_round_primary_light.toDrawable(this@ArticleEditActivity) else com.gh.gamecenter.common.R.drawable.bg_shape_f5_radius_999.toDrawable(
                    this@ArticleEditActivity
                )
            articleSectionName.setTextColor(
                if (isEmpty) com.gh.gamecenter.common.R.color.text_theme.toColor(this@ArticleEditActivity) else com.gh.gamecenter.common.R.color.text_secondary.toColor(
                    this@ArticleEditActivity
                )
            )
            clearIv.goneIf(isEmpty)
            if (isEmpty) articleSectionName.text = "选择子版块"
        }
    }

    private fun resetSection() {
        mBinding.clearIv.performClick()
        mViewModel.mSelectCommunityData?.id?.let {
            mViewModel.getForumSections(it)
            mViewModel.getModeratorsInfo(it)
        }
    }

    override fun onMenuItemClick(item: MenuItem?): Boolean {
        if (item?.itemId == R.id.menu_answer_post) {
            debounceActionWithInterval(R.id.menu_answer_post, 2000L) {
                ifLogin("社区文章编辑-[发布]") {
                    val bbsType =
                        if (mViewModel.mSelectCommunityData?.type == "official_bbs") "综合论坛" else "游戏论坛"
                    SensorsBridge.trackEvent(
                        "ArticlePostClick",
                        "bbs_id",
                        mViewModel.mSelectCommunityData?.id ?: "",
                        "bbs_type",
                        bbsType,
                        "activity_tag",
                        mViewModel.selectActivityLabelEntity?.name ?: "",
                        "article_type",
                        "帖子"
                    )

                    mRichEditor.hideLinkStyle()
                    mRichEditor.postDelayed({
                        mViewModel.title = mBinding.articleEditTitle.text.toString()
                        mViewModel.content = getReplaceRealContent()
                        mRichEditor.showLinkStyle()
                        if (mRichEditor.hasPlaceholderImage()) {
                            ToastUtils.showToast("图片上传中")
                            return@postDelayed
                        }
                        if (mViewModel.localVideoList.isNotEmpty() || mViewModel.uploadVideoErrorList.isNotEmpty()) {
                            ToastUtils.showToast("视频上传中")
                            return@postDelayed
                        }
                        if (mViewModel.selectActivityLabelEntity?.original == true && !mOriginalCb.isChecked) {
                            toast("本次话题内容要求原创")
                            return@postDelayed
                        }
                        if (mViewModel.checkDataAndLoadTitleTag(mIsKeyBoardShow)) {
                            mArticleTagsSelectFragment?.publishArticle(mOriginalCb.isChecked)
                        }
                        val bbsType =
                            if (mViewModel.type.isNotEmpty()) if (mViewModel.type == "game_bbs") "游戏论坛" else "综合论坛" else ""
                        NewLogUtils.logArticleEditClick(
                            "click_article_post_button", mViewModel.mSelectCommunityData?.id ?: "",
                            bbsType, mViewModel.selectActivityLabelEntity?.name ?: "",
                            mOriginalCb.isChecked, mViewModel.quoteCountEntity
                        )
                    }, 100)
                }
            }
        } else if (item?.itemId == R.id.menu_draft) {
//            MtaHelper.onEvent("发表文章", "文章草稿", CommunityManager.getInstance().community.name)
            if (checkDraft(SaveDraftType.SKIP)) {
                NewLogUtils.logArticleDraftClick()
                val intent = ArticleDraftActivity.getIntent(
                    this,
                    mViewModel.detailEntity?.id,
                    mViewModel.detailEntity == null
                )
                startActivityForResult(intent, ARTICLE_DRAFT_REQUEST_CODE)
            }
        }
        return super.onMenuItemClick(item)
    }

    override fun getVideoGuideKey(): String = Constants.SP_ARTICLE_VIDEO_GUIDE

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        updateStatusBarColor(com.gh.gamecenter.common.R.color.ui_surface, com.gh.gamecenter.common.R.color.ui_surface)
        setSectionUI(mViewModel.selectSection == null)
        mBinding.activityTv.setTextColor(
            if (mViewModel.selectActivityLabelEntity != null) com.gh.gamecenter.common.R.color.text_FA8500.toColor(this) else com.gh.gamecenter.common.R.color.text_primary.toColor(
                this
            )
        )
        mBinding.forumContainer.background =
            if (mViewModel.mSelectCommunityData == null) R.drawable.button_round_primary_light.toDrawable(this) else com.gh.gamecenter.common.R.drawable.bg_shape_f5_radius_999.toDrawable(
                this
            )
        mBinding.articleGameName.setTextColor(
            if (mViewModel.mSelectCommunityData == null) com.gh.gamecenter.common.R.color.text_theme.toColor(
                this
            ) else com.gh.gamecenter.common.R.color.text_secondary.toColor(this)
        )
    }

    override fun updateStaticViewBackground(view: View?) {
        updateStaticView(view, listOf(R.id.selectForumContainer, R.id.articleSectionContainer, R.id.activityTv))
    }

    companion object {
        const val SAVE_DRAFTS_INTERVAL_TIME = 15000
        const val ARTICLE_DRAFT_REQUEST_CODE = 105
        const val SAVE_DRAFTS_TOAST_COUNT = 3
        const val ARTICLE_DRAFT_CHANGE_TAG = "ANSWER_DRAFT_CHANGE_TAG"
        const val ARTICLE_POSTED_TAG = "ARTICLE_POSTED_TAG"

        @JvmStatic
        fun getIntent(context: Context): Intent {
            return Intent(context, ArticleEditActivity::class.java)
        }

        @JvmStatic
        fun getIntent(context: Context, community: CommunityEntity?, type: String = "", entrance: String): Intent {
            val intent = Intent(context, ArticleEditActivity::class.java)
            intent.putExtra(BbsType::class.java.simpleName, type)
            intent.putExtra(CommunityEntity::class.java.simpleName, community)
            intent.putExtra(EntranceConsts.KEY_ENTRANCE, entrance)
            return intent
        }

        @JvmStatic
        fun getPatchIntent(
            context: Context,
            detailEntity: ArticleDetailEntity,
            draftEntity: ArticleDraftEntity? = null,
            showInNewPage: Boolean = false
        ): Intent {
            val intent = Intent(context, ArticleEditActivity::class.java)
            intent.putExtra(ArticleDetailEntity::class.java.simpleName, detailEntity)
            intent.putExtra(ArticleDraftEntity::class.java.simpleName, draftEntity)
            intent.putExtra(EntranceConsts.KEY_ARTICLE_OPEN_IN_NEW_PAGE, showInNewPage)
            return intent
        }

        @JvmStatic
        fun getDraftIntent(context: Context, draftEntity: ArticleDraftEntity, showInNewPage: Boolean = true): Intent {
            val intent = Intent(context, ArticleEditActivity::class.java)
            intent.putExtra(ArticleDraftEntity::class.java.simpleName, draftEntity)
            intent.putExtra(EntranceConsts.KEY_ARTICLE_OPEN_IN_NEW_PAGE, showInNewPage)
            return intent
        }
    }

    enum class SaveDraftType {
        EXIT, // 退出时保存
        AUTO, // 自动保存
        SKIP  // 跳转至草稿箱时保存
    }
}