package com.gh.gamecenter.qa.answer.edit

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.TextUtils
import android.view.Gravity
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.facebook.drawee.view.SimpleDraweeView
import com.gh.base.BaseRichEditorActivity
import com.gh.gamecenter.common.base.fragment.WaitingDialogFragment
import com.gh.gamecenter.core.AppExecutor
import com.gh.common.util.*
import com.gh.gamecenter.common.view.DrawableView
import com.gh.gamecenter.ImageViewerActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.callback.ConfirmListener
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.utils.DialogUtils
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.databinding.FragmentAnswerEditBinding
import com.gh.gamecenter.common.entity.NotificationUgc
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.common.mvvm.Status
import com.gh.gamecenter.qa.answer.detail.AnswerDetailActivity
import com.gh.gamecenter.qa.answer.draft.AnswerDraftActivity
import com.gh.gamecenter.qa.entity.Questions
import com.gh.gamecenter.video.VideoVerifyItemViewHolder
import com.gh.gamecenter.video.detail.VideoDetailContainerViewModel
import com.halo.assistant.HaloApp
import org.json.JSONObject

/**
 * Created by khy on 10/04/18.
 */
@Deprecated("V5.0废弃")
class AnswerEditActivity : BaseRichEditorActivity<AnswerEditViewModel>(), KeyboardHeightObserver {

    private lateinit var mMenuDraft: MenuItem
    private lateinit var mMenuPost: MenuItem
    private lateinit var mBinding: FragmentAnswerEditBinding
    private var mProcessingDialog: WaitingDialogFragment? = null
    private var mUploadImageCancelDialog: Dialog? = null
    private var mCommunityName: String? = null
    private var mOpenAnswerInNewPage: Boolean = false
    private var mImageViewList: ArrayList<SimpleDraweeView>? = null

    override fun mtaEventName(): String {
        return "回答详情" // issues 定的就是回答详情
    }

    override fun handleMessage(msg: Message) {
        super.handleMessage(msg)
        if (msg.what == AUTO_SAVE_DRAFT) {
            saveDraft(false)
            mBaseHandler.sendEmptyMessageDelayed(AUTO_SAVE_DRAFT, SAVE_DRAFTS_INTERVAL_TIME.toLong())
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == ANSWER_DRAFT_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            mViewModel.getUserAnswerDrafts()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setToolbarMenu(R.menu.menu_answer_post)
        mMenuDraft = mToolbar.menu.findItem(R.id.menu_draft)
        mMenuPost = mToolbar.menu.findItem(R.id.menu_answer_post)
        mCommunityName = intent?.getStringExtra(EntranceConsts.KEY_COMMUNITY_NAME)
        mOpenAnswerInNewPage = intent?.getBooleanExtra(EntranceConsts.KEY_ANSWER_OPEN_IN_NEW_PAGE, false)!!
        mBinding = FragmentAnswerEditBinding.bind(mContentView)
        onClickView()
        addObserver()
        initQuestionContent()

        if (TextUtils.isEmpty(mViewModel.answerId)) {
            mBaseHandler.sendEmptyMessageDelayed(AUTO_SAVE_DRAFT, SAVE_DRAFTS_INTERVAL_TIME.toLong()) // 启动自动保存草稿
        }

        mRichEditor.setOnTextChangeListener { t ->
            mBinding.appBar.setExpanded(false, true)
            mBinding.answerPlaceholder.visibility =
                if (t.contains("<img src") || !TextUtils.isEmpty(mRichEditor.text)) {
                    View.GONE
                } else View.VISIBLE
            checkPostButtonEnable()
        }

        mRichEditor.setOnInitialLoadListener { isReady ->
            if (isReady) {
                requestFocusAndMoveCursorToEnd()
            }
        }

        if (!TextUtils.isEmpty(mViewModel.answerId)) {
            setNavigationTitle(getString(R.string.answer_patch_title))
            mViewModel.cacheAnswerContent = mViewModel.answerContent

            mMenuDraft.isVisible = true
            if (intent.getBooleanExtra(EntranceConsts.KEY_SHOW_EDIT_DRAFT, false)) {
                mViewModel.getUserAnswerDrafts()
            } else {
                mRichEditor.setHtml(mViewModel.answerContent, false)
            }
        } else {
            setNavigationTitle(getString(R.string.answer_edit_title))
            mViewModel.getUserAnswerDrafts()
            mMenuDraft.isVisible = false
        }

        checkPostButtonEnable()

        mImageViewList = arrayListOf(
            findViewById(R.id.question_images_1),
            findViewById(R.id.question_images_2),
            findViewById(R.id.question_images_3)
        )
    }

    override fun provideViewModel(): AnswerEditViewModel {
        val factory = AnswerEditViewModel.Factory(
            HaloApp.getInstance().application,
            intent?.getStringExtra(EntranceConsts.KEY_ANSWER_ID),
            intent?.getStringExtra(EntranceConsts.KEY_ANSWER_CONTENT),
            intent?.getStringExtra(EntranceConsts.KEY_DRAFT_ID),
            intent?.getParcelableExtra(Questions::class.java.simpleName) ?: Questions()
        )
        mViewModel = ViewModelProviders.of(this, factory).get(AnswerEditViewModel::class.java)
        return mViewModel
    }

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

    override fun onKeyboardHeightChanged(height: Int, orientation: Int) {
        super.onKeyboardHeightChanged(height, orientation)
        if (height > 0) mBinding.appBar.setExpanded(false, true)
    }

    override fun onMenuItemClick(item: MenuItem?): Boolean {
        if (item?.itemId == R.id.menu_answer_post && !ClickUtils.isFastDoubleClick(R.id.menu_answer_post, 5000)) {
            readyPost()
        } else if (item?.itemId == R.id.menu_draft) {
            startActivityForResult(AnswerDraftActivity.getIntent(this, mViewModel.answerId), ANSWER_DRAFT_REQUEST_CODE)
        }
        return super.onMenuItemClick(item)
    }

    private fun addObserver() {
        mViewModel.postLiveData.observeNonNull(this) {
            if (it.status == Status.SUCCESS) {
                MtaHelper.onEvent("发表答案", "提交成功", mCommunityName)
                if (mViewModel.checkIsAllUploadedAndToast()) {
                    toast("发布成功")
                }
                var answerId: String? = null
                tryWithDefaultCatch {
                    answerId = JSONObject(it.data).getString("_id")
                }

                if (answerId == null) {
                    answerId = mViewModel.answerId
                }

                val data = Intent()
                data.putExtra(EntranceConsts.KEY_ANSWER_CONTENT, getReplaceRealContent())
                data.putExtra(EntranceConsts.KEY_ANSWER_ID, answerId ?: mViewModel.answerId)
                setResult(Activity.RESULT_OK, data)
                if (mOpenAnswerInNewPage) {
                    val intent = AnswerDetailActivity
                        .getIntent(this, answerId, mEntrance, "编辑答案")
                    startActivity(intent)
                }
                finish()
                AppExecutor.uiExecutor.executeWithDelay(Runnable {
                    NotificationHelper.showNotificationHintDialog(NotificationUgc.ANSWER)
                }, 1000)

            } else if (it.status == Status.ERROR) {
                val errorString = it.exception?.response()?.errorBody()?.string()
                ErrorHelper.handleErrorWithCustomizedHandler(this, errorString, customizedHandler = { code ->
                    when (code) {
                        403037 -> consume {
                            if (TextUtils.isEmpty(mViewModel.draftId)) {
                                DialogHelper.showDialog(this, "发布失败", "问题已被删除，无法发布回答", "好吧", "", { finish() })
                            } else {
                                DialogHelper.showDialog(this,
                                    "发布失败",
                                    "问题已被删除，需要删除草稿吗？",
                                    "删除草稿",
                                    "暂不",
                                    {
                                        mViewModel.deleteAnswerDraft()
                                        finish()
                                    })
                            }
                        }
                        else -> false
                    }
                })
            }
        }

        mViewModel.processDialog.observeNonNull(this) {
            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 = DialogUtils.showAlertDialog(
                                this, "提示", "图片正在上传中，确定取消吗？",
                                "确定", "取消", object : ConfirmListener {
                                    override fun onConfirm() {
                                        mViewModel.uploadImageSubscription?.dispose()
                                        mUploadImageCancelDialog?.dismiss()
                                        mProcessingDialog?.dismiss()
                                    }
                                }, null
                            )
                        }
                    }
                }
            } else {
                mUploadImageCancelDialog?.dismiss()
                mProcessingDialog?.dismiss()
            }
        }

        mViewModel.deleteDraftLiveDate.observe(this, Observer {
            if (it == true) {
                setResult(Activity.RESULT_OK)
                finish()
            }
        })

        mViewModel.draftsLiveData.observe(this, Observer {
            mRichEditor.setHtml(it, false)
            requestFocusAndMoveCursorToEnd()
            checkPostButtonEnable()
        })

        mViewModel.saveDraftsLiveData.observeNonNull(this) {
            if (it) {
                val data = Intent()
                data.putExtra(EntranceConsts.KEY_ANSWER_CONTENT, getReplaceRealContent())
                setResult(SAVE_DRAFTS, data)
                finish()
            } else {
                showDraftFailureDialog()
            }
        }
    }

    private fun requestFocusAndMoveCursorToEnd() {
        try {
            mRichEditor.scrollTo(0, 10000000)
            mRichEditor.postDelayed({
                val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.showSoftInput(mRichEditor, InputMethodManager.SHOW_IMPLICIT)
                mRichEditor.focusEditor()
            }, 400)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun initQuestionContent() {
        val question = mViewModel.question
        question.title = HtmlUtils.filterHtmlLabel(question.title)
        val video = if (!question.videos.isNullOrEmpty()) question.videos[0] else null
        val videoSize = if (video != null) 1 else 0

        mBinding.answerPlaceholder.text =
            if (!question.description.isNullOrEmpty() || question.images.size > 0 || question.videos.isNotEmpty()) {
                "请撰写回答（下拉查看问题详情）..."
            } else "请撰写回答..."

        mBinding.appBar.setExpanded(false)
        mBinding.questionTitle.text = question.title
        mBinding.questionDes.initWidth(resources.displayMetrics.widthPixels - 40F.dip2px())
        mBinding.questionDes.maxLines = 3
        mBinding.questionDes.setOriginalText(question.description)
        mBinding.questionDes.goneIf(question.description.isNullOrEmpty())
        mBinding.videoPlay.visibleIf(video != null)
        mBinding.videoStatus.visibleIf(video != null && video.status != "pass")
        mBinding.videoDuration.visibleIf(video?.status == "pass")
        if (video?.status == "pass") {
            mBinding.videoDuration.background = DrawableView.getOvalDrawable(R.color.black_alpha_50, 999f)
            mBinding.videoDuration.text = video.duration
        } else {
            val status = if (!question.me.isContentOwner && !question.me.isModerator && video?.status == "fail") {
                "pending"
            } else video?.status ?: ""
            VideoVerifyItemViewHolder.setVideoStatus(mBinding.videoStatus, status)
        }

        if (video != null) {
            if (video.status == "pass") {
                mBinding.questionImages1.display(video.poster)
            } else {
                mBinding.questionImages1.setImageResource(R.drawable.community_video_default_poster)
            }
        }

        question.images.let { images ->
            for (i in images.indices) {
                val index = i + videoSize // view index
                val position = index - videoSize // data index
                if (images.size > position) {
                    when (index) {
                        0 -> ImageUtils.display(mBinding.questionImages1, images[position])
                        1 -> ImageUtils.display(mBinding.questionImages2, images[position])
                        2 -> {
                            ImageUtils.display(mBinding.questionImages3, images[position])
                            if (images.size + videoSize > 3) {
                                mBinding.questionImages3Mask.visibility = View.VISIBLE
                                mBinding.questionImages3Desc.visibility = View.VISIBLE
                                mBinding.questionImages3Desc.text = "+${images.size + videoSize - 3}"
                            }
                        }
                    }
                }
            }

            mBinding.questionImagesContainer.visibility = if (images.size + videoSize > 0) {
                View.VISIBLE
            } else View.GONE
        }
    }

    private fun readyPost() {
        ifLogin("回答编辑-提交") {
            mRichEditor.hideLinkStyle()
            mRichEditor.postDelayed({
                val answerContent = getReplaceRealContent()
                mRichEditor.showLinkStyle()
                if (mRichEditor.hasPlaceholderImage()) {
                    ToastUtils.showToast("图片上传ing")
                    return@postDelayed
                }
                if (checkData(answerContent)) {
                    mViewModel.postAnswer(answerContent)
                }
            }, 100)
        }
    }

    private fun checkData(answerContent: String, isShowToast: Boolean = true): Boolean {
        val answerLength = HtmlUtils.stripHtml(answerContent).length
        if (answerLength < MIN_ANSWER_TEXT_LENGTH) {
            if (isShowToast) ToastUtils.showToast(
                getString(R.string.answer_beneath_length_limit),
                if (mIsKeyBoardShow) Gravity.CENTER else -1
            )
            return false
        } else if (answerLength > MAX_ANSWER_TEXT_LENGTH) {
            if (isShowToast) ToastUtils.showToast("回答最多输入10000个字", if (mIsKeyBoardShow) Gravity.CENTER else -1)
            return false
        }
        return true
    }

    private fun getReplaceRealContent(): String {
        var answerContent = mRichEditor.html
        for (s in mViewModel.mapImages.keys) {
            val netUrl = mViewModel.mapImages[s]
            if (netUrl != null) {
                answerContent = answerContent.replace(FILE_HOST + s, netUrl)
            }
        }
        return answerContent
    }

    private fun checkPostButtonEnable() {
        val answerContent = getReplaceRealContent()
        val isEnabled = checkData(answerContent, false)
        mMenuPost.actionView?.alpha = if (isEnabled) 1f else 0.6f
    }

    override fun handleBackPressed(): Boolean {
        return if (TextUtils.isEmpty(UserManager.getInstance().token)) {
            false
        } else if (!TextUtils.isEmpty(mViewModel.answerId)
            && TextUtils.isEmpty(mRichEditor.text)
            && !mRichEditor.html.contains("<img src")
        )
            false
        else if (!TextUtils.isEmpty(mViewModel.answerId)) {
            consume { showPatchBackDialog() }
        } else if (TextUtils.isEmpty(mViewModel.answerId)
            && !TextUtils.isEmpty(mViewModel.cacheAnswerContent)
            && !mRichEditor.html.contains("<img src")
            && TextUtils.isEmpty(mRichEditor.text)
        ) {
            consume {
                DialogHelper.showDialog(this, "提示", "当前内容为空，退出即会删除该草稿，确定退出吗？", "确定", "取消", {
                    mViewModel.deleteAnswerDraft()
                })
            }
        } else if (!TextUtils.isEmpty(mViewModel.cacheAnswerContent)
            && mViewModel.cacheAnswerContent == mRichEditor.html
        ) {
            false
        } else {
            consume { saveDraft(true) }
        }
    }

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

    private fun showDraftFailureDialog() {
        DialogHelper.showDialog(this, "提示", "确定退出？已撰写的内容将会丢失？", "继续撰写", "退出", cancelClickCallback = { finish() })
    }

    private fun showPatchBackDialog() {
        DialogHelper.showDialog(this, "提示", "是否保存修改内容用于下次编辑？", "保存并退出", "不保存", { saveDraft(true) }, { finish() })
    }

    /**
     *  [forcedExit] -> 强行退出当前页面，不考虑接口请求成功与否
     */
    private fun saveDraft(forcedExit: Boolean) {
        val editContent = getReplaceRealContent()
        if (mRichEditor.hasPlaceholderImage()) return
        if (TextUtils.isEmpty(UserManager.getInstance().token)) {
            return
        } else if (forcedExit && TextUtils.isEmpty(editContent)) {
            finish()
            return
        } else if (!forcedExit && TextUtils.isEmpty(editContent)) {
            return
        }

        mViewModel.saveAnswerDrafts(editContent, forcedExit)
    }

    private fun onClickView() {
        val videoSize = if (!mViewModel.question.videos.isNullOrEmpty()) 1 else 0
        mBinding.questionImages1.setOnClickListener {
            val question = mViewModel.question
            if (!question.videos.isNullOrEmpty()) {
                val videoEntity = question.videos[0]
                if (videoEntity.status == "pass") {
                    DirectUtils.directToVideoDetail(
                        this,
                        videoEntity.id,
                        VideoDetailContainerViewModel.Location.SINGLE_VIDEO.value,
                        path = "回答详情"
                    )
                } else if (videoEntity.status == "pending" ||
                    (!question.me.isContentOwner
                            && !question.me.isModerator
                            && videoEntity.status == "fail")
                ) {
                    toast("视频正在审核中")
                } else if (videoEntity.status == "fail") {
                    toast("视频审核未通过")
                }
            } else {
                showQuestionImageDetail(0)
            }
        }
        mBinding.questionImages2.setOnClickListener {
            showQuestionImageDetail(1 - videoSize)
        }
        mBinding.questionImages3.setOnClickListener {
            showQuestionImageDetail(2 - videoSize)
        }
    }

    private fun showQuestionImageDetail(position: Int) {
        val images = ArrayList(mViewModel.question.images)
        if (position <= images.size) {
            val intent = ImageViewerActivity.getIntent(this, images, position, mImageViewList, "$mEntrance+(回答编辑)")
            startActivity(intent)
        }
    }

    override fun getVideoGuideKey(): String = ""

    companion object {
        const val SAVE_DRAFTS = 110
        const val AUTO_SAVE_DRAFT = 1
        const val SAVE_DRAFTS_INTERVAL_TIME = 15000
        const val SAVE_DRAFTS_TOAST_COUNT = 3
        const val MIN_ANSWER_TEXT_LENGTH = 6
        const val MAX_ANSWER_TEXT_LENGTH = 10000
        const val ANSWER_DRAFT_REQUEST_CODE = 112

        const val ANSWER_DRAFT_CHANGE_TAG = "ANSWER_DRAFT_CHANGE_TAG"

        /**
         * 撰写回答
         */
        fun getIntent(
            context: Context,
            question: Questions?,
            showInNewPage: Boolean?,
            communityName: String?,
            showHintBackground: Boolean = false
        ): Intent {
            val intent = Intent(context, AnswerEditActivity::class.java)
            intent.putExtra(EntranceConsts.KEY_ANSWER_OPEN_IN_NEW_PAGE, showInNewPage)
            intent.putExtra(EntranceConsts.KEY_COMMUNITY_NAME, communityName)
            intent.putExtra(EntranceConsts.KEY_HINT, showHintBackground)
            intent.putExtra(Questions::class.java.simpleName, question)
            return intent
        }

        /**
         * 撰写回答(存在回答草稿)
         */
        fun getIntent(
            context: Context,
            question: Questions?,
            draftId: String?,
            showInNewPage: Boolean?,
            communityName: String?
        ): Intent {
            val intent = Intent(context, AnswerEditActivity::class.java)
            intent.putExtra(EntranceConsts.KEY_ANSWER_OPEN_IN_NEW_PAGE, showInNewPage)
            intent.putExtra(EntranceConsts.KEY_DRAFT_ID, draftId)
            intent.putExtra(EntranceConsts.KEY_COMMUNITY_NAME, communityName)
            intent.putExtra(Questions::class.java.simpleName, question)
            return intent
        }

        /**
         * 撰写回答
         */
        fun getIntent(context: Context, question: Questions?, communityName: String?): Intent {
            val intent = Intent(context, AnswerEditActivity::class.java)
            intent.putExtra(EntranceConsts.KEY_COMMUNITY_NAME, communityName)
            intent.putExtra(Questions::class.java.simpleName, question)
            return intent
        }

        /**
         * 修改回答
         */
        fun getIntent(
            context: Context,
            answerId: String?,
            question: Questions?,
            content: String?,
            communityName: String?,
            showEditDraft: Boolean = false,
            showInNewPage: Boolean = false
        ): Intent {
            val intent = Intent(context, AnswerEditActivity::class.java)
            intent.putExtra(EntranceConsts.KEY_ANSWER_ID, answerId)
            intent.putExtra(EntranceConsts.KEY_ANSWER_CONTENT, content)
            intent.putExtra(EntranceConsts.KEY_COMMUNITY_NAME, communityName)
            intent.putExtra(EntranceConsts.KEY_SHOW_EDIT_DRAFT, showEditDraft)
            intent.putExtra(Questions::class.java.simpleName, question)
            intent.putExtra(EntranceConsts.KEY_ANSWER_OPEN_IN_NEW_PAGE, showInNewPage)
            return intent
        }
    }
}
