package com.gh.gamecenter.qa.questions.edit

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Message
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.MenuItem
import android.view.View
import android.widget.EditText
import androidx.core.content.ContextCompat
import androidx.core.widget.addTextChangedListener
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.entity.NotificationUgc
import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.common.mvvm.Status
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.AppExecutor
import com.gh.gamecenter.core.utils.KeyboardHeightObserver
import com.gh.gamecenter.core.utils.PatternUtils
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.databinding.ActivityQuestionsEditBinding
import com.gh.gamecenter.entity.*
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.entity.Permissions
import com.gh.gamecenter.feature.entity.QuestionDraftEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.qa.BbsType
import com.gh.gamecenter.qa.answer.edit.AnswerEditActivity
import com.gh.gamecenter.qa.article.draft.ArticleDraftActivity
import com.gh.gamecenter.qa.article.edit.ArticleEditActivity
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.QuestionsDetailEntity
import com.gh.gamecenter.qa.questions.draft.QuestionDraftActivity
import com.gh.gamecenter.qa.questions.edit.tip.QuestionTitleTipAdapter
import com.gh.gamecenter.qa.video.publish.VideoPublishFragment
import com.lightgame.utils.Util_System_Keyboard
import com.lightgame.utils.Utils
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject

/**
 * Created by khy on 28/04/18.
 */
class QuestionEditActivity : BaseRichEditorActivity<QuestionEditViewModel>(),
    KeyboardHeightObserver {

    private lateinit var mBinding: ActivityQuestionsEditBinding

    private var mProcessingDialog: WaitingDialogFragment? = null
    private var mUploadImageCancelDialog: Dialog? = null
    private lateinit var mMenuDraft: MenuItem
    private lateinit var mMenuPost: MenuItem
    private var mTagsSelectFragment: TagsSelectFragment? = null
    private var mPostDraftsCount: Int = 0
    private val mSaveTitleKey = "title"
    private val mSaveContentKey = "content"

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

    override fun mtaEventName(): String {
        return "提问帖"
    }

    @SuppressLint("Recycle")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null || resultCode != Activity.RESULT_OK) return
        if (requestCode == QUESTION_DRAFT_REQUEST_CODE) {
            val draftEntity =
                data.getParcelableExtra<QuestionDraftEntity>(QuestionDraftEntity::class.java.simpleName)
            if (draftEntity != null) {
                mViewModel.questionDraftEntity = draftEntity
                setQuestionDraft(draftEntity)
                mViewModel.getQuestionDraftContent(draftEntity.id)
            }
        } else if (requestCode == ChooseForumActivity.CHOOSE_FORUM_REQUEST) {
            val community =
                data.getParcelableExtra<CommunityEntity>(EntranceConsts.KEY_COMMUNITY_DATA)
            mViewModel.communityEntity = community
            mViewModel.type = community?.type ?: ""
            if (mViewModel.questionEntity != null) {
                mViewModel.questionEntity?.community?.id = community?.id ?: ""
                mViewModel.questionEntity?.community?.name = community?.name ?: ""
            }
            if (mViewModel.type == BbsType.GAME_BBS.value) {
                mViewModel.gameEntity = null
            }
            setForumName()
            resetSection()
            mBinding.questionseditTitle.setText(mViewModel.title)
        } else if (requestCode == VideoPublishFragment.REQUEST_GAME_CODE) {
            val game = data.getParcelableExtra<GameEntity>(GameEntity::class.java.simpleName)
            if (game != null) {
                mViewModel.gameEntity = game
                setForumName()
            }
        }
    }

    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.sectionName.text = it.name
                mViewModel.selectSection = it
                setSectionUI(false)
            }
        }
    }

    override fun handleMessage(msg: Message) {
        super.handleMessage(msg)
        if (msg.what == 1) {
            if (!mViewModel.title.isNullOrEmpty()
                && !mViewModel.content.isNullOrEmpty()
            ) {
                mViewModel.title = mBinding.questionseditTitle.text.toString()
                mViewModel.content = getReplaceRealContent()
                mViewModel.saveQuestionDraft(SaveDraftType.AUTO)
            }
            mBaseHandler.sendEmptyMessageDelayed(1, SAVE_DRAFTS_INTERVAL_TIME.toLong())
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        updateStatusBarColor(R.color.background_white, R.color.background_white)
        setToolbarMenu(R.menu.menu_question_post)
        mToolbar.navigationIcon = null
        mMenuDraft = getMenuItem(R.id.menu_draft)
        mMenuPost = getMenuItem(R.id.menu_question_post)
        if (savedInstanceState != null) {
            val cacheTitle = savedInstanceState.getString(mSaveTitleKey)
            val cacheContent = savedInstanceState.getString(mSaveContentKey)
            if (!cacheTitle.isNullOrEmpty()) mViewModel.title = cacheTitle
            if (!cacheContent.isNullOrEmpty()) mViewModel.content = cacheContent
        }
        mBinding = ActivityQuestionsEditBinding.bind(mContentView)
        checkPostButtonEnable()
        mBinding.questionseditTitle.setOnEditorActionListener { _, _, e -> e?.keyCode == KeyEvent.KEYCODE_ENTER; }
        mBinding.questionseditTitle.setText(mViewModel.title)
        mBinding.editorInsertContainer.editorFont.visibility = View.GONE
        mBinding.editorInsertContainer.editorLink.visibility = View.GONE
        mOriginalCb.visibility = View.GONE

        // Navigation
        when {
            mViewModel.isModeratorPatch -> setNavigationTitle("修改问题")
            mViewModel.questionEntity != null -> setNavigationTitle("修改问题")
            else -> setNavigationTitle("发提问")
        }

        mViewModel.initCommunityDataAndDraft()

        // TitleTip
        if (mViewModel.questionEntity == null) {
            val titleTipAdapter = QuestionTitleTipAdapter(
                this,
                mBinding.questionseditTitle,
                mViewModel.communityEntity?.id
            )
            mBinding.questionseditTitle.setAdapter(titleTipAdapter)
        }

        // TitleEdit
        mBinding.questionseditTitle.addTextChangedListener(LimitTextWatcher(mBinding.questionseditTitle))
        mBinding.questionseditTitle.filters = arrayOf(TextHelper.getFilter(50, "标题最多50个字"))
        mBinding.questionseditTitle.addTextChangedListener {
            checkPostButtonEnable()
        }

        mBinding.richEditor.setOnTextChangeListener { t ->
            if (t.contains("<img src") || !TextUtils.isEmpty(mRichEditor.text) || mViewModel.localVideoList.isNotEmpty()) {
                mBinding.editPlaceholder.visibility = View.GONE
            } else {
                mBinding.editPlaceholder.visibility = View.VISIBLE
            }
            checkPostButtonEnable()
        }

        mBinding.questionseditTitle.setOnTouchListener { _, _ ->
            closeExtendedKeyboard()
            false
        }

        mBinding.questionseditTitle.setOnFocusChangeListener { _, hasFocus ->
            controlEditorInsertContainerEnabled(!hasFocus)
        }
        mBinding.questionseditTitle.requestFocus()

        mBinding.backBtn.setOnClickListener {
            val bbsType =
                if (mViewModel.type.isNotEmpty()) if (mViewModel.type == "game_bbs") "游戏论坛" else "综合论坛" else ""
            NewLogUtils.logQuestionEditClick(
                "click_question_cancel", mViewModel.communityEntity?.id
                    ?: "",
                bbsType, mViewModel.selectActivityLabelEntity?.name
                    ?: "", mViewModel.quoteCountEntity
            )
            onBackPressed()
        }
        mBinding.chooseForumTv.setOnClickListener {
            showSelectGameDialog()
        }
        mBinding.activityTv.setOnClickListener {
            if (mViewModel.communityEntity == null || mViewModel.communityEntity?.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_QUESTION,
                    mViewModel.communityEntity?.id ?: "",
                    mViewModel.selectActivityLabelEntity?.id,
                    "editorActivity"
                )
            }, delayTime)
        }
        mBinding.sectionName.setOnClickListener {
            val delayTime = if (mIsKeyBoardShow) {
                Util_System_Keyboard.hideSoftKeyboard(this)
                200L
            } else 0L
            AppExecutor.uiExecutor.executeWithDelay({
                ChooseSectionDialogFragment.show(
                    this,
                    mViewModel.communityEntity?.id ?: "",
                    mViewModel.selectSection?.id ?: "",
                    mViewModel.isModerator,
                    "editorActivity"
                )
            }, delayTime)
        }
        mBinding.clearIv.setOnClickListener {
            setSectionUI(true)
            mViewModel.selectSection = null
        }

        // 增加提问时, 如果searchKey不为空 光标跳到最后
        mBaseHandler.postDelayed({
            mBinding.questionseditTitle.setSelection(mBinding.questionseditTitle.text.toString().length)
        }, 50)

        if (intent != null) {
            val communityEntity =
                intent.getParcelableExtra<CommunityEntity>(CommunityEntity::class.java.simpleName)
            val detailEntity =
                intent.getParcelableExtra<QuestionsDetailEntity>(QuestionsDetailEntity::class.java.simpleName)
            val draftEntity =
                intent.getParcelableExtra<QuestionDraftEntity>(QuestionDraftEntity::class.java.simpleName)
            when {
                detailEntity != null -> { // 问题编辑
                    setPatchContent(detailEntity)
                }
                draftEntity != null -> { //草稿编辑
                    mViewModel.questionDraftEntity = draftEntity
                    setQuestionDraft(draftEntity)
                    mViewModel.getQuestionDraftContent(draftEntity.id)
                    mBaseHandler.sendEmptyMessageDelayed(1, SAVE_DRAFTS_INTERVAL_TIME.toLong())
                }
                else -> { // 新增问题
                    var searchKey = intent.getStringExtra(EntranceConsts.KEY_QUESTIONS_SEARCH_KEY)
                    if (!searchKey.isNullOrEmpty() && searchKey.length > QuestionEditViewModel.QUESTION_TITLE_MAX_LENGTH)
                        searchKey =
                            searchKey.substring(0, QuestionEditViewModel.QUESTION_TITLE_MAX_LENGTH)
                    if (mViewModel.title.isNullOrEmpty()) mViewModel.title = searchKey
                    mViewModel.isFromSearch =
                        intent.getBooleanExtra(QuestionEditViewModel.QUESTION_FORM_SEARCH, false)
                    mViewModel.type = intent?.getStringExtra(BbsType::class.java.simpleName) ?: ""
                    mBaseHandler.sendEmptyMessageDelayed(1, SAVE_DRAFTS_INTERVAL_TIME.toLong())
                    if (communityEntity != null) {
                        mViewModel.communityEntity = communityEntity
                        setForumName()
                        resetSection()
                        if (mViewModel.type == BbsType.GAME_BBS.value) {
                            mBinding.chooseForumTv.isEnabled = false
                        }
                    }
                    showUploadVideoGuide()
                }
            }
        }
        observeData()

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

    private fun getChooseSelectCallback(): (entity: ActivityLabelEntity?) -> Unit {
        return {
            mViewModel.selectActivityLabelEntity = it
            mBinding.activityTv.text = it?.name
            mBinding.activityTv.setTextColor(
                if (it != null) R.color.text_FA8500.toColor(this) else R.color.text_title.toColor(
                    this
                )
            )
        }
    }

    override fun provideViewModel(): QuestionEditViewModel {
        mViewModel = ViewModelProviders.of(this).get(QuestionEditViewModel::class.java)
        return mViewModel
    }

    private fun setPatchContent(detailEntity: QuestionsDetailEntity) {
        mMenuDraft.isVisible = false
        mViewModel.type = detailEntity.type
        mViewModel.questionDraftEntity = detailEntity.me.questionDraft
        mViewModel.questionEntity = detailEntity
        mViewModel.communityEntity = detailEntity.community
        mViewModel.communityEntity?.icon = detailEntity.community.game?.getIcon()
        mViewModel.communityEntity?.iconSubscript = detailEntity.community.game?.iconSubscript
        mViewModel.gameEntity = detailEntity.gameEntity
        if (detailEntity.tagActivityId.isNotEmpty() && detailEntity.tagActivityName.isNotEmpty()) {
            mViewModel.selectActivityLabelEntity =
                ActivityLabelEntity(detailEntity.tagActivityId, detailEntity.tagActivityName)
            mBinding.activityTv.text = detailEntity.tagActivityName
            mBinding.activityTv.setTextColor(R.color.text_FA8500.toColor(this))
        }
        setForumName()
        resetSection()
        mBinding.activityTv.isEnabled = false
        mBinding.chooseForumTv.isEnabled = false
        mBinding.sectionName.isEnabled = false
        mBinding.clearIv.isEnabled = false

        mViewModel.isModeratorPatch =
            intent.getBooleanExtra(EntranceConsts.KEY_QUESTION_MODERATOR_PATCH, false)

        // 编辑问题时可能存在草稿
        if (mViewModel.questionDraftEntity != null) {
            mViewModel.title = mViewModel.questionDraftEntity?.title
            mViewModel.getQuestionDraftContent(mViewModel.questionDraftEntity?.id ?: "")
        } else {
            mViewModel.title = detailEntity.title
            mViewModel.content = detailEntity.description
            mBinding.questionseditTitle.setText(detailEntity.title)
            setEditHtml(detailEntity.description)
        }
    }

    private fun setQuestionDraft(draftEntity: QuestionDraftEntity) {
        mViewModel.communityEntity = draftEntity.bbs
        mViewModel.communityEntity?.icon = draftEntity.bbs?.game?.getIcon()
        mViewModel.communityEntity?.iconSubscript = draftEntity.bbs?.game?.iconSubscript
        mViewModel.type = draftEntity.type
        if (draftEntity.tagActivityId.isNotEmpty() && draftEntity.tagActivityName.isNotEmpty()) {
            mViewModel.selectActivityLabelEntity =
                ActivityLabelEntity(draftEntity.tagActivityId, draftEntity.tagActivityName)
            mBinding.activityTv.text = draftEntity.tagActivityName
            mBinding.activityTv.setTextColor(R.color.text_FA8500.toColor(this))
        }
        setEditHtml(draftEntity.description)
        mViewModel.gameEntity = draftEntity.gameEntity
        mViewModel.title = draftEntity.title
        mViewModel.content = draftEntity.description
        mBinding.questionseditTitle.setText(mViewModel.title)
        setForumName()
        resetSection()
    }

    private fun observeData() {
        mViewModel.moderatorPostLiveData.observe(this, Observer {
            if (it?.status == Status.SUCCESS) {
                if (mViewModel.questionEntity!!.me.moderatorPermissions.updateQuestion == Permissions.REPORTER) {
                    toast("提交成功")
                } else {
                    toast("操作成功")
                    val data = Intent()
                    data.putExtra(
                        QuestionsDetailEntity::class.java.simpleName,
                        mViewModel.questionEntity
                    )
                    setResult(Activity.RESULT_OK, data)
                }
                finish()
                AppExecutor.uiExecutor.executeWithDelay(Runnable {
                    NotificationHelper.showNotificationHintDialog(NotificationUgc.QUESTION)
                }, 1000)
            } else if (it?.status == Status.ERROR) {
                val e = it.exception
                if (e != null && e.code() == 403) {
                    val string = e.response().errorBody()?.string()
                    val errorJson = JSONObject(string)
                    val errorCode = errorJson.getInt("code")
                    if (errorCode == 403059) {
                        DialogHelper.showDialog(
                            this, "提交失败", "权限错误，请刷新后重试",
                            "确定", "", {
                                setResult(Activity.RESULT_CANCELED)
                                finish()
                            },
                            extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                        )
                        return@Observer
                    } else if (errorCode == 403209) {
                        ErrorHelper.handleError(this, string, false, {
                            if (::mMenuPost.isInitialized) {
                                onMenuItemClick(mMenuPost)
                            }
                        }, "发帖子（问答）")
                    }
                }
                toast(R.string.post_failure_hint)
            }
        })
        mViewModel.postQuestionDrafts.observe(this, Observer { pair ->
            if (pair != null) {
                when (pair.first) {
                    SaveDraftType.EXIT -> {
                        if (pair.second) {
                            if (mViewModel.questionDraftEntity != null) {
                                val intent = Intent()
                                intent.putExtra(
                                    QuestionDraftEntity::class.java.simpleName,
                                    mViewModel.questionDraftEntity
                                )
                                setResult(Activity.RESULT_OK, intent)
                                if (mViewModel.checkIsAllUploadedAndToast()) {
                                    Utils.toast(this, "已保存！")
                                }
                            } else {
                                if (mViewModel.checkIsAllUploadedAndToast()) {
                                    Utils.toast(this, "问题已保存到草稿箱")
                                }
                            }
                            EventBus.getDefault()
                                .post(EBReuse(ArticleEditActivity.ARTICLE_DRAFT_CHANGE_TAG))
                            finish()
                        }
                    }
                    SaveDraftType.AUTO -> {
                        if (pair.second) {
                            if (mPostDraftsCount >= AnswerEditActivity.SAVE_DRAFTS_TOAST_COUNT) {
                                mPostDraftsCount = 0
                                Utils.toast(this, "问题已保存到草稿箱")
                            } else {
                                mPostDraftsCount++
                            }
                        }
                    }
                    SaveDraftType.SKIP -> {
                        if (pair.second) {
                            Utils.toast(this, "问题已保存到草稿箱")
                            startActivityForResult(
                                ArticleDraftActivity.getIntent(this),
                                ArticleEditActivity.ARTICLE_DRAFT_REQUEST_CODE
                            )
                        } else {
                            Utils.toast(this, "问题草稿保存失败")
                        }
                    }
                }
            }
        })
        mViewModel.questionDraftsContent.observe(this, Observer {
            mViewModel.questionDraftEntity?.bbs = it.bbs
            mViewModel.questionDraftEntity?.gameEntity = it.gameEntity
            mViewModel.questionDraftEntity?.description = it.description
            setQuestionDraft(it)
        })

        // Process dialog
        mViewModel.processDialog.observe(this, Observer { it ->
            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.notSelectForum.observe(this, Observer {
            if (it) showSelectGameDialog()
        })

        mViewModel.sectionListLiveData.observeNonNull(this) {
            mBinding.arrowIv.goneIf(it.isEmpty())
            mBinding.sectionContainer.goneIf(it.isEmpty())
        }
    }

    override fun onMenuItemClick(menuItem: MenuItem?): Boolean {
        if (menuItem?.itemId == R.id.menu_question_post) {
            debounceActionWithInterval(R.id.menu_question_post, 2000L) {
                val bbsType = if (mViewModel.communityEntity?.type == "official_bbs") "综合论坛" else "游戏论坛"
                SensorsBridge.trackEvent(
                    "ArticlePostClick",
                    "bbs_id",
                    mViewModel.communityEntity?.id ?: "",
                    "bbs_type",
                    bbsType,
                    "activity_tag",
                    mViewModel.selectActivityLabelEntity?.name ?: "",
                    "article_type",
                    "提问贴"
                )

                mRichEditor.post {
                    if (mRichEditor.hasPlaceholderImage()) {
                        ToastUtils.showToast("图片上传中")
                        return@post
                    }
                    if (mViewModel.localVideoList.isNotEmpty() || mViewModel.uploadVideoErrorList.isNotEmpty()) {
                        ToastUtils.showToast("视频上传中")
                        return@post
                    }
                    if (mViewModel.isModeratorPatch) {
                        if (checkSameFromQuestionData()) {
                            toast("内容没有变化")
                        } else {
                            //版主不是作者时，仅能修改用户的标题内容，正文不能修改
                            if (mViewModel.questionEntity?.user?.id != UserManager.getInstance().userId && mViewModel.questionEntity?.description != mViewModel.content) {
                                toast("不能修改正文")
                                return@post
                            }
                            mViewModel.selectedTags.addAll(mViewModel.questionEntity?.tags!!)
                            DialogHelper.showDialog(
                                this, "修改问题",
                                if (mViewModel.questionEntity!!.me.moderatorPermissions.updateQuestion == Permissions.REPORTER)
                                    "你的操作将提交给小编审核，确定提交吗？" else "你的操作将立即生效，确定提交吗？",
                                "确定", "取消", {
                                    mViewModel.uploadPicAndPatchQuestion(false)
                                }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                            )
                        }
                    } else {
                        if (mViewModel.checkTitleAndLoadTitleTag(mIsKeyBoardShow)) {
                            mTagsSelectFragment?.postQuestion()
                        }
                    }
                    val bbsType =
                        if (mViewModel.type.isNotEmpty()) if (mViewModel.type == "game_bbs") "游戏论坛" else "综合论坛" else ""
                    NewLogUtils.logQuestionEditClick(
                        "click_question_post_button", mViewModel.communityEntity?.id ?: "",
                        bbsType, mViewModel.selectActivityLabelEntity?.name ?: "", mViewModel.quoteCountEntity
                    )
                }
            }
        } else if (menuItem?.itemId == R.id.menu_draft) {
            if (checkDraft(SaveDraftType.SKIP)) {
                NewLogUtils.logQuestionDraftClick()
                startActivityForResult(QuestionDraftActivity.getIntent(this), QUESTION_DRAFT_REQUEST_CODE)
            }
        }

        return super.onMenuItemClick(menuItem)
    }

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

    override fun onDestroy() {
        mProcessingDialog?.dismissAllowingStateLoss()
        mProcessingDialog = null
        super.onDestroy()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putString(mSaveTitleKey, mViewModel.title)
        outState.putString(mSaveContentKey, mViewModel.content)
    }

    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("发提问")
        }
    }

    // Limits of EditText
    private inner class LimitTextWatcher(private val mEditText: EditText) : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            if (mEditText === mBinding.questionseditTitle) {

                val etContent = s.toString()
                if (etContent.contains("\n")) {
                    mBinding.questionseditTitle.setText(etContent.replace("\n", ""))
                    mBinding.questionseditTitle.setSelection(start)
                    return
                }
                // 多个空格保留一个
                if (PatternUtils.isHasSpace(etContent)) {
                    mBinding.questionseditTitle.setText(PatternUtils.replaceSpace(etContent))
                    mBinding.questionseditTitle.setSelection(start)
                    return
                }
                /*if (etContent.contains(" ")) {
                    mBinding.questionseditTitle.setText(etContent.replace(" ".toRegex(), ""))
                    mBinding.questionseditTitle.setSelection(start)
                    return
                }*/
            }
        }

        override fun afterTextChanged(s: Editable) {}
    }


    // 退出提示
    override fun handleBackPressed(): Boolean {
        if (super.handleBackPressed()) {
            return true
        }

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

        if (mViewModel.isModeratorPatch) {
            if (checkSameFromQuestionData()) {
                return false
            }
            DialogHelper.showDialog(
                this, "提示", "确定退出修改？已编辑的内容将丢失", "继续编辑", " 退出", cancelClickCallback = { finish() },
                extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
            )
            return true
        }

        //问题发布
        if (mViewModel.questionEntity == null && mViewModel.questionDraftEntity == null) {
            if (!mBinding.questionseditTitle.text.isNullOrEmpty() || !mBinding.richEditor.html.isNullOrEmpty()) {
                SensorsBridge.trackEvent("ArticleCancelDialogShow")
                DialogHelper.showDialog(
                    this,
                    "提示",
                    "是否保存内容再退出？",
                    cancelText = "不保存",
                    confirmText = "保存并退出",
                    cancelClickCallback = {
                        SensorsBridge.trackEvent("ArticleCancelDialogClick", "button_name", "不保存")
                        finish()
                    },
                    confirmClickCallback = {
                        SensorsBridge.trackEvent("ArticleCancelDialogClick", "button_name", "保存并退出")
                        mViewModel.title = mBinding.questionseditTitle.text.toString()
                        mViewModel.content = getReplaceRealContent()
                        mViewModel.saveQuestionDraft(SaveDraftType.EXIT)
                    },
                    extraConfig = DialogHelper.Config(
                        showCloseIcon = true,
                        centerTitle = true,
                        centerContent = true
                    )
                )
                return true
            }
        }

        //问题编辑，需要判断是否修改过
        if (mViewModel.questionEntity != null && mViewModel.questionDraftEntity == null) {
            return if (mViewModel.questionEntity?.title != mBinding.questionseditTitle.text.toString()
                || mViewModel.questionEntity?.description != mBinding.richEditor.html
            ) {
                showBackDialog()
                true
            } else false
        }

        return !checkDraft(SaveDraftType.EXIT)
    }

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

    private fun showBackDialog() {
        DialogHelper.showDialog(
            this,
            "提示",
            "是否保存修改内容用于下次编辑？",
            cancelText = "不保存",
            confirmText = "保存并退出",
            cancelClickCallback = {
                finish()
            },
            confirmClickCallback = {
                mViewModel.title = mBinding.questionseditTitle.text.toString()
                mViewModel.content = getReplaceRealContent()
                mViewModel.saveQuestionDraft(SaveDraftType.EXIT)
            },
            extraConfig = DialogHelper.Config(
                showCloseIcon = true,
                centerTitle = true,
                centerContent = true
            )
        )
    }

    private fun checkSameFromQuestionData(): Boolean {
        mViewModel.questionEntity?.let {
            if (mViewModel.title != it.title) {
                return false
            }
            if (mViewModel.content != it.description) {
                return false
            }
            return true
        }
        return false
    }

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

        val beginTransaction = supportFragmentManager.beginTransaction()
        mTagsSelectFragment = TagsSelectFragment.getInstance()
        beginTransaction.replace(
            R.id.tagsContainer,
            mTagsSelectFragment!!,
            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, R.drawable.bg_shape_f5_radius_999)
        mBinding.chooseForumTv.setTextColor(ContextCompat.getColor(this, R.color.text_subtitle))
    }

    private fun setSectionUI(isEmpty: Boolean) {
        mBinding.run {
            sectionContainer.background =
                if (isEmpty) R.drawable.button_round_primary_light.toDrawable(this@QuestionEditActivity) else R.drawable.bg_shape_f5_radius_999.toDrawable(
                    this@QuestionEditActivity
                )
            sectionName.setTextColor(
                if (isEmpty) R.color.theme_font.toColor(this@QuestionEditActivity) else R.color.text_subtitle.toColor(
                    this@QuestionEditActivity
                )
            )
            clearIv.goneIf(isEmpty)
            if (isEmpty) sectionName.text = "选择子版块"
        }
    }

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

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

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

    override fun getVideoGuideKey(): String = Constants.SP_QUESTION_VIDEO_GUIDE

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

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        updateStatusBarColor(R.color.background_white, R.color.background_white)
        setSectionUI(mViewModel.selectSection == null)
        mBinding.activityTv.setTextColor(
            if (mViewModel.selectActivityLabelEntity != null) R.color.text_FA8500.toColor(this) else R.color.text_title.toColor(
                this
            )
        )
        mBinding.forumContainer.background =
            if (mViewModel.communityEntity == null) R.drawable.button_round_primary_light.toDrawable(this) else R.drawable.bg_shape_f5_radius_999.toDrawable(
                this
            )
        mBinding.chooseForumTv.setTextColor(
            if (mViewModel.communityEntity == null) R.color.theme_font.toColor(this) else R.color.text_subtitle.toColor(
                this
            )
        )
    }

    companion object {
        const val QUESTION_POSTED_TAG = "QUESTION_POSTED_TAG"
        const val QUESTION_DRAFT_REQUEST_CODE = 105
        const val QUESTION_DRAFT_CHANGE_TAG = "ANSWER_DRAFT_CHANGE_TAG"
        const val SAVE_DRAFTS_INTERVAL_TIME = 15000

        // searchKey 补充到标题(新增问题)
        fun getIntent(context: Context, searchKey: String?): Intent {
            val intent = Intent(context, QuestionEditActivity::class.java)
            intent.putExtra(EntranceConsts.KEY_QUESTIONS_SEARCH_KEY, searchKey)
            intent.putExtra(QuestionEditViewModel.QUESTION_FORM_SEARCH, true)
            return intent
        }

        // 新增问题
        fun getIntent(context: Context, type: BbsType = BbsType.GAME_BBS, entrance: String): Intent {
            val intent = Intent(context, QuestionEditActivity::class.java)
            intent.putExtra(BbsType::class.java.simpleName, type.value)
            intent.putExtra(EntranceConsts.KEY_ENTRANCE, entrance)
            return intent
        }

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

        // 编辑问题
        fun getIntent(context: Context, entity: QuestionsDetailEntity): Intent {
            val intent = Intent(context, QuestionEditActivity::class.java)
            intent.putExtra(QuestionsDetailEntity::class.java.simpleName, entity)
            return intent
        }

        // 编辑问题
        @JvmStatic
        fun getManagerIntent(context: Context, entity: QuestionsDetailEntity): Intent {
            val intent = Intent(context, QuestionEditActivity::class.java)
            intent.putExtra(QuestionsDetailEntity::class.java.simpleName, entity)
            intent.putExtra(EntranceConsts.KEY_QUESTION_MODERATOR_PATCH, true)
            return intent
        }

        //编辑草稿
        @JvmStatic
        fun getDraftIntent(context: Context, questionDraftEntity: QuestionDraftEntity): Intent {
            val intent = Intent(context, QuestionEditActivity::class.java)
            intent.putExtra(QuestionDraftEntity::class.java.simpleName, questionDraftEntity)
            return intent
        }

    }

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