package com.gh.gamecenter.qa.comment

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.util.DisplayMetrics
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.*
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.*
import com.gh.gamecenter.CommentDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.adapter.OnCommentCallBackListener
import com.gh.gamecenter.common.base.fragment.BaseDialogWrapperFragment
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.baselist.ListFragment
import com.gh.gamecenter.common.constant.EntranceConsts.KEY_COMMENT_ID
import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.common.syncpage.SyncDataEntity
import com.gh.gamecenter.common.syncpage.SyncFieldConstants
import com.gh.gamecenter.common.syncpage.SyncPageRepository
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.VerticalItemDecoration
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.databinding.ItemCommentEditImageBinding
import com.gh.gamecenter.entity.CommentEntity
import com.gh.gamecenter.eventbus.EBCommentSuccess
import com.gh.gamecenter.eventbus.EBDeleteComment
import com.gh.gamecenter.qa.answer.detail.AnswerDetailFragment
import com.gh.gamecenter.qa.comment.CommentActivity.Companion.GAME_COLLECTION_ID
import com.gh.gamecenter.qa.comment.CommentActivity.Companion.QUESTION_ID
import com.gh.gamecenter.qa.editor.LocalMediaActivity
import com.halo.assistant.HaloApp
import com.lightgame.utils.Util_System_Keyboard
import com.lightgame.utils.Utils
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.internal.utils.PathUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import kotlin.math.abs

open class NewCommentFragment : ListFragment<CommentEntity, NewCommentViewModel>(), OnCommentCallBackListener,
    KeyboardHeightObserver,
    OnCommentOptionClickListener {

    private lateinit var commentEt: EditText
    private lateinit var commentSendBtn: TextView
    protected lateinit var mAnswerContent: LinearLayout
    protected lateinit var mScrollView: ScrollView
    private var commentCountTv: TextView? = null
    private var mCommentLine: View? = null
    private var mImageBtn: ImageView? = null
    private var mPlaceholderView: View? = null
    private var mImageScrollView: View? = null
    private var mImageContainer: LinearLayout? = null
    private var mDividerView: View? = null
    protected var commentInputContainer: View? = null
    protected var mShadowView: View? = null
    open var commentContainer: View? = null

    protected var mAnswerId: String = ""
    protected var mArticleId: String = ""
    protected var mCommunityId: String = ""
    protected var mVideoId: String = ""
    protected var mQuestionId: String = ""
    protected var mGameCollectionId: String = ""
    protected var mCommentId: String = ""
    protected var mRootCommentId: String = ""
    protected var mShowInputOnly: Boolean = false // 是否只显示输入框，不显示列表
    protected var mIsVideoAuthor: Boolean = false//是否是视频作者
    protected var mCommentType = CommentType.ANSWER
    protected var mShowSoftKeyboardOnStartUp: Boolean = false
    protected var mCommentEntity: CommentEntity? = null // 回复评论的实体 用完马上清空
    protected var mSendingDialog: Dialog? = null
    protected lateinit var mViewModel: NewCommentViewModel

    private var mKeyboardHeightProvider: KeyboardHeightProvider? = null

    var mOffset: Int = 0
    var mCommentCount: Int = 0
    var mAdapter: ListAdapter<CommentEntity>? = null
    var mCommentListener: AnswerDetailFragment.CommentListener? = null

    private fun findView() {
        commentContainer = mCachedView.findViewById(R.id.comment_container)
        commentEt = mCachedView.findViewById(R.id.answer_comment_et)
        commentSendBtn = mCachedView.findViewById(R.id.answer_comment_send_btn)
        commentCountTv = mCachedView.findViewById(R.id.comment_dialog_count_tv)
        commentInputContainer = mCachedView.findViewById(R.id.answer_comment_content_container)
        mAnswerContent = mCachedView.findViewById(R.id.answer_content)
        mScrollView = mCachedView.findViewById(R.id.scrollView)
        mShadowView = mCachedView.findViewById(R.id.shadowView)
        mCommentLine = mCachedView.findViewById(R.id.comment_line)
        mImageBtn = mCachedView.findViewById(R.id.imageBtn)
        mPlaceholderView = mCachedView.findViewById(R.id.placeholderView)
        mImageScrollView = mCachedView.findViewById(R.id.imageScrollView)
        mImageContainer = mCachedView.findViewById(R.id.imageContainer)
        mDividerView = mCachedView.findViewById(R.id.dividerView)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        arguments?.apply {
            mShowSoftKeyboardOnStartUp = getBoolean(SHOW_SOFT_KEY_BOARD_ON_STARTUP, false)
            mAnswerId = getString(ANSWER_ID, "")
            mArticleId = getString(ARTICLE_ID, "")
            mVideoId = getString(VIDEO_ID, "")
            mQuestionId = getString(QUESTION_ID, "")
            mGameCollectionId = getString(GAME_COLLECTION_ID, "")
            mRootCommentId = getString(KEY_COMMENT_ID, "")
            mCommentCount = getInt(COMMENT_COUNT, 0)
            mCommentType = getSerializable(COMMENT_TYPE) as? CommentType ?: CommentType.ANSWER
            mCommunityId = getString(COMMUNITY_ID, "")
            mShowInputOnly = getBoolean(SHOW_INPUT_ONLY, false)
            mCommentEntity = getParcelable(COMMENT_ENTITY)
            mIsVideoAuthor = getBoolean(IS_VIDEO_AUTHOR, false)
        }

        super.onCreate(savedInstanceState)

        findView()
        initListener()

        mViewModel.postCommentLiveData.observe(this, Observer { apiResponse ->
            if (apiResponse == null) return@Observer
            when {
                apiResponse.data != null -> {
                    mSendingDialog?.dismiss()
                    toast("发表成功")

                    if (mCommentEntity != null) { // 补充默认草稿
                        mCommentEntity = null // 清空当前评论实体
                        commentEt.hint = getString(R.string.message_detail_comment_hint)
                        commentEt.setText(mViewModel.getCommentDraft(mCommentEntity)?.draft ?: "")
                        commentEt.setSelection(commentEt.text.length)
                    } else {
                        commentEt.setText("")
                    }

                    mCommentCount++
                    updateCommentCount()

                    if (mCommentListener != null) {
                        if (apiResponse.data.has("_id")) {
                            val commentId = apiResponse.data.getString("_id")
                            mCommentListener?.onCommentSuccess(commentId)
                        }
                        mCommentListener?.onCountChange(mCommentCount)
                        mCommentListener?.onCommentDraftChange("")
                    }
                    commentEt.postDelayed({ setSoftInput(false) }, 100)

                    when (mCommentType) {
                        CommentType.COMMUNITY_ARTICLE -> {
                            SyncPageRepository.postSyncData(
                                SyncDataEntity(
                                    mArticleId,
                                    SyncFieldConstants.ARTICLE_COMMENT_COUNT,
                                    mCommentCount,
                                    checkFieldEntity = true
                                )
                            )
                        }
                        CommentType.ANSWER -> {
                            SyncPageRepository.postSyncData(
                                SyncDataEntity(
                                    mAnswerId,
                                    SyncFieldConstants.ANSWER_COMMENT_COUNT,
                                    mCommentCount
                                )
                            )
                        }
                        CommentType.VIDEO -> {
                            EventBus.getDefault().post(EBCommentSuccess())
                        }
                        else -> {
                            //do nothing
                        }
                    }

                    if (mShowInputOnly) {
                        requireActivity().finish()
                        return@Observer
                    } else {
                        onRefresh()
                    }
                }
                apiResponse.httpException != null -> {
                    mSendingDialog?.dismiss()

                    val exception = apiResponse.httpException
                    var errorString: String? = null
                    try {
                        errorString = exception.response().errorBody()?.string()
                    } catch (e1: Exception) {
                        e1.printStackTrace()
                    }

                    val entrance = when (mCommentType) {
                        CommentType.COMMUNITY_ARTICLE,
                        CommentType.COMMUNITY_ARTICLE_CONVERSATION,
                        CommentType.ANSWER,
                        CommentType.ANSWER_CONVERSATION,
                        CommentType.VIDEO,
                        CommentType.VIDEO_CONVERSATION -> "文章及帖子的评论和回复"

                        CommentType.GAME_COLLECTION,
                        CommentType.GAME_COLLECTION_CONVERSATION -> "游戏单评论及回复"

                        else -> ""
                    }
                    ErrorHelper.handleError(
                        requireContext(), errorString, false,
                        { commentSendBtn.performClick() }, entrance
                    )
                }
                else -> {
                    mSendingDialog?.dismiss()
                }
            }
        })
        mViewModel.deleteVideoCommentLiveData.observeNonNull(this) {
            if (this is NewCommentConversationFragment || this is StairsCommentFragment) {
                onLoadRefresh()
                EventBus.getDefault().post(EBDeleteComment(it))
            } else {
                val indexOf = mAdapter?.entityList?.indexOf(it) ?: 0
                mAdapter?.entityList?.remove(it)
                mAdapter?.notifyItemRemoved(indexOf)
                mCommentCount--
                mCommentListener?.onCountChange(mCommentCount)
                updateCommentCount()
                if (mAdapter?.entityList?.isEmpty() == true) {
                    onLoadEmpty()
                }
            }
            toast("删除成功")
        }

        mViewModel.pictureLiveData.observeNonNull(this) {
            addImageViews(it)
        }
    }

    @SuppressLint("DefaultLocale")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        if (mShowInputOnly) {
            if (mCommentEntity != null) {
                commentEt.hint = "回复 @${mCommentEntity?.user?.name}"
            }
            commentContainer?.visibility = View.GONE
            commentEt.requestFocus()
        }

        commentEt.isFocusable = true
        commentEt.isFocusableInTouchMode = true
        commentEt.setTextChangedListener { _, _, _, _ ->
            checkSendBtnEnable()

            if (mCommentListener != null) {
                mCommentListener?.onCommentDraftChange(commentEt.text.toString())
            }
            mViewModel.saveCommentDraft(mCommentEntity, commentEt.text.toString())
        }
        commentEt.filters = arrayOf(TextHelper.getFilter(9999, "评论不能多于9999字"))
        mViewModel.getCommentDraft(mCommentEntity)?.let {
            commentEt.setText(it.draft)
            if (!it.pictureList.isNullOrEmpty()) {
                mViewModel.pictureList.clear()
                mViewModel.pictureList.addAll(it.pictureList!!)
                addImageViews(mViewModel.pictureList)
            }
        }

        commentEt.setSelection(commentEt.text.length)
        if (mShowSoftKeyboardOnStartUp) {
            commentEt.postDelayed({
                val keyboard =
                    HaloApp.getInstance().application.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                keyboard.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
            }, 200)
        } else {
            commentEt.clearFocus()
        }

        updateCommentCount()

        if (commentContainer != null) {
            val displayMetrics = DisplayMetrics()
            (context as Activity).windowManager.defaultDisplay.getMetrics(displayMetrics)
            val layoutParams = commentContainer?.layoutParams
            layoutParams?.height = displayMetrics.heightPixels * 488 / 640
            commentContainer?.layoutParams = layoutParams
        }

        mKeyboardHeightProvider = KeyboardHeightProvider(activity)
        view.post { mKeyboardHeightProvider?.start() }
        val emptyHint = mCachedView?.findViewById<TextView>(R.id.reuseNoneDataTv)
        emptyHint?.text = "这里还没有人评论噢~"
        emptyHint?.setTextColor(R.color.background_white.toColor(requireContext()))
        val emptyHintDesc = mCachedView?.findViewById<TextView>(R.id.reuseNoneDataDescTv)
        emptyHintDesc?.visibility = View.VISIBLE
        emptyHintDesc?.text = "说说你的看法吧"
    }

    private fun checkSendBtnEnable() {
        val enable = commentEt.text.toString().trim { it <= ' ' }.isNotEmpty() || mViewModel.pictureList.isNotEmpty()
        commentSendBtn.isEnabled = enable
    }

    fun setCommentListener(listener: AnswerDetailFragment.CommentListener) {
        mCommentListener = listener
    }

    override fun onResume() {
        super.onResume()
        mKeyboardHeightProvider?.setKeyboardHeightObserver(this)
        EventBus.getDefault().post(EBReuse(COMMENT_RESUME))

        if (::commentEt.isInitialized && commentEt.text.isNotEmpty()) {
            // 若不延迟，可能回来的时候不能获取焦点导致弹不起来
            mBaseHandler.postDelayed({
                Util_System_Keyboard.showSoftKeyboard(context, commentEt)
            }, 200)
        }
    }

    override fun onPause() {
        super.onPause()
        mKeyboardHeightProvider?.setKeyboardHeightObserver(null)
        if (activity?.isFinishing != true) {
            mBaseHandler.postDelayed({ EventBus.getDefault().post(EBReuse(COMMENT_PAUSE)) }, 1000)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mKeyboardHeightProvider?.close()
    }

    private fun updateCommentCount() {
        if (commentCountTv != null) {
            commentCountTv?.text = String.format("%d条评论", mCommentCount)
        }
    }

    override fun getItemDecoration(): RecyclerView.ItemDecoration {
        return VerticalItemDecoration(context, 0f, true)
    }

    override fun isAutomaticLoad() = !mShowInputOnly

    override fun provideListViewModel(): NewCommentViewModel {
        mViewModel = viewModelProvider(
            NewCommentViewModel.Factory(
                application = HaloApp.getInstance().application,
                answerId = mAnswerId,
                articleId = mArticleId,
                communityId = mCommunityId,
                commentId = mCommentId,
                videoId = mVideoId,
                questionId = mQuestionId,
                gameCollectionId = mGameCollectionId,
                rootCommentId = mRootCommentId,
                commentType = mCommentType,
                isVideoAuthor = mIsVideoAuthor
            )
        )
        return mViewModel
    }

    override fun provideListAdapter(): ListAdapter<*> {
        if (mAdapter == null) {
            val entrance = when (mViewModel.commentType) {
                CommentType.ANSWER,
                CommentType.ANSWER_CONVERSATION -> "(答案详情-评论列表)"

                CommentType.COMMUNITY_ARTICLE,
                CommentType.COMMUNITY_ARTICLE_CONVERSATION -> "(文章详情-评论列表)"

                CommentType.COMMUNITY_QUESTION,
                CommentType.COMMUNITY_QUESTION_CONVERSATION -> "(问题详情-评论列表)"

                CommentType.VIDEO,
                CommentType.VIDEO_CONVERSATION -> "(视频详情-评论列表)"

                CommentType.GAME_COLLECTION,
                CommentType.GAME_COLLECTION_CONVERSATION -> "(游戏单详情-评论列表)"
            }
            mAdapter = NewCommentAdapter(requireContext(), mViewModel, true, this, this, entrance)
        }
        return mAdapter!!
    }

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

    override fun onCommentCallback(entity: CommentEntity) {
        mCommentEntity = entity
        setSoftInput(true)
        val commentDraft = mViewModel.getCommentDraft(entity)
        if (commentDraft != null) {
            commentEt.setText(commentDraft.draft)
            commentEt.setSelection(commentEt.text.length)
        } else {
            commentEt.setText("")
        }
    }

    private fun initListener() {
        commentSendBtn.setOnClickListener {
            if (!ClickUtils.isFastDoubleClick(R.id.answer_comment_send_btn, 5000)) {
                Util_System_Keyboard.hideSoftKeyboard(requireActivity())
                ifLogin(getLoginEntrance()) {
                    showRegulationTestDialogIfNeeded {
                        postComment()
                    }
                }
            } else {
                toast("操作太快，慢一点嘛")
            }
        }
        mCachedView.findViewById<View>(R.id.comment_close_iv)?.setOnClickListener {
            val fragment = parentFragment
            if (fragment is BaseDialogWrapperFragment) {
                fragment.dismiss()
            }
            if (activity is CommentActivity) {
                requireActivity().finish()
            }
        }
        mShadowView?.setOnClickListener {
            Util_System_Keyboard.hideSoftKeyboard(requireContext(), commentEt)
            if (mShowInputOnly && activity is CommentActivity) {
                requireActivity().finish()
            }
        }
        mImageBtn?.setOnClickListener {
            PermissionHelper.checkStoragePermissionBeforeAction(
                requireActivity(), object : EmptyCallback {
                    override fun onCallback() {
                        if (mViewModel.pictureList.size >= 9) {
                            toast("至多上传9张")
                            return
                        }
                        val maxChooseCount = 9 - mViewModel.pictureList.size
                        val intent = LocalMediaActivity.getIntent(
                            requireContext(),
                            LocalMediaActivity.ChooseType.IMAGE,
                            maxChooseCount,
                            "评论列表"
                        )
                        Util_System_Keyboard.hideSoftKeyboard(requireActivity())
                        startActivityForResult(intent, REQUEST_CODE_IMAGE)
                    }
                })
        }

    }

    private fun postComment() {
        val content = commentEt.text.toString()

        if (content.isEmpty() && mViewModel.pictureList.isNullOrEmpty()) {
            toast("评论内容不能为空！")
            return
        }

        mSendingDialog = DialogUtils.showWaitDialog(context, getString(R.string.post_dialog_hint))

        if (mCommentEntity != null && mCommentEntity?.id == null) {
            toast("评论异常 id null")
            mSendingDialog?.cancel()
            return
        }

        if (mShowInputOnly) {
            // Fuck pm
            MtaHelper.onEvent("帖子详情", "评论详情-全部回复", "发送")
        }

        mViewModel.postPictureAndComment(content, mCommentEntity)
    }

    //软键盘控制
    protected fun setSoftInput(isShow: Boolean) {
        if (isShow) {
            ifLogin(getLoginEntrance()) {
                val keyboard = requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                keyboard.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
                commentEt.isFocusable = true
                commentEt.isFocusableInTouchMode = true
                commentEt.requestFocus()

                if (mCommentEntity != null && mCommentEntity?.user != null) {
                    commentEt.hint = getString(R.string.comment_repty_hint, mCommentEntity?.user?.name)
                } else {
                    commentEt.hint = getString(R.string.message_detail_comment_hint)
                }
            }
        } else {
            Util_System_Keyboard.hideSoftKeyboard(context, commentEt)

            if (mCommentEntity != null) {
                mCommentEntity = null // 清空当前评论实体
                commentEt.hint = getString(R.string.message_detail_comment_hint)
                commentEt.setText("")
            }
        }
    }

    private fun getLoginEntrance(): String {
        return when (mViewModel.commentType) {
            CommentType.ANSWER,
            CommentType.ANSWER_CONVERSATION -> {
                if (mCommentEntity == null) {
                    "回答详情-评论-写评论"
                } else {
                    "回答详情-评论-回复"
                }
            }

            CommentType.COMMUNITY_ARTICLE,
            CommentType.COMMUNITY_ARTICLE_CONVERSATION -> {
                if (mCommentEntity == null) {
                    "社区文章详情-评论-写评论"
                } else {
                    "社区文章详情-评论-回复"
                }
            }

            CommentType.VIDEO,
            CommentType.VIDEO_CONVERSATION -> {
                if (mCommentEntity == null) {
                    if (this is StairsCommentFragment) "视频流详情-评论-写评论" else "视频详情-评论-写评论"
                } else {
                    if (this is StairsCommentFragment) "视频流详情-评论-回复" else "视频详情-评论-回复"
                }
            }

            CommentType.COMMUNITY_QUESTION,
            CommentType.COMMUNITY_QUESTION_CONVERSATION -> {
                if (mCommentEntity == null) {
                    "问题详情-评论-写评论"
                } else {
                    "问题详情-评论-回复"
                }
            }

            CommentType.GAME_COLLECTION,
            CommentType.GAME_COLLECTION_CONVERSATION -> {
                if (mCommentEntity == null) {
                    "游戏单详情-评论-写评论"
                } else {
                    "游戏单详情-评论-回复"
                }
            }
        }
    }

    override fun onKeyboardHeightChanged(height: Int, orientation: Int) {
        if (commentInputContainer != null && commentInputContainer?.visibility != View.GONE) {
            popInputLayout(height > 0, height)
        }
    }

    open fun popInputLayout(isPopup: Boolean, height: Int) {
        mCommentLine?.goneIf(mShowInputOnly || isPopup)
        mShadowView?.goneIf(mShowInputOnly || !isPopup)
        if (requireActivity() is CommentDetailActivity) {
            val shadowView = (requireActivity() as CommentDetailActivity).shadowView
            shadowView.visibility = if (isPopup && !mShowInputOnly) View.VISIBLE else View.GONE
            DisplayUtils.setLightStatusBar(requireActivity(), !isPopup)
            shadowView.setOnClickListener { Util_System_Keyboard.hideSoftKeyboard(activity) }
        }
        if (!isPopup) mOffset = abs(height)
        val mScrollViewParams = mScrollView.layoutParams as LinearLayout.LayoutParams
        val mLayoutParams = commentInputContainer?.layoutParams as FrameLayout.LayoutParams
        if (!mShowInputOnly) {
            mAnswerContent.orientation = if (isPopup) LinearLayout.VERTICAL else LinearLayout.HORIZONTAL
            if (isPopup) {
                mAnswerContent.background =
                    ContextCompat.getDrawable(requireActivity(), R.drawable.bg_shape_white_radius_10_top_only)
            } else {
                mAnswerContent.setBackgroundColor(ContextCompat.getColor(requireActivity(), R.color.white))
            }
            mScrollViewParams.width = if (isPopup) LinearLayout.LayoutParams.MATCH_PARENT else 0
            mScrollViewParams.height = if (isPopup) 64f.dip2px() else 28f.dip2px()
            mLayoutParams.height = if (isPopup) 130f.dip2px() else LinearLayout.LayoutParams.WRAP_CONTENT
            mLayoutParams.bottomMargin = if (isPopup) height + mOffset - 12F.dip2px() else 0
        } else {
            mAnswerContent.orientation = LinearLayout.VERTICAL
            mAnswerContent.background =
                ContextCompat.getDrawable(requireActivity(), R.drawable.bg_shape_white_radius_10_top_only)
            mPlaceholderView?.visibility = View.VISIBLE
            mImageBtn?.goneIf(mCommentEntity != null || mGameCollectionId.isNotEmpty())
            mScrollViewParams.width = LinearLayout.LayoutParams.MATCH_PARENT
            mScrollViewParams.height = 76f.dip2px()
            mScrollViewParams.topMargin = 4f.dip2px()
            mLayoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT
            mLayoutParams.bottomMargin = height + mOffset
            mAnswerContent.setPadding(0, 12f.dip2px(), 0, 0)
        }
        mScrollView.layoutParams = mScrollViewParams
        commentInputContainer?.layoutParams = mLayoutParams
    }

    override fun onLoadEmpty() {
        super.onLoadEmpty()
        // 如果评论说为不为零且列表数据为空,则判定相关内容被隐藏
        if (mCommentCount != 0) {
            val emptyHint = mCachedView?.findViewById<TextView>(R.id.reuseNoneDataTv)
            emptyHint?.setText(R.string.content_delete_hint)
        }
    }

    override fun onCommentOptionClick(entity: CommentEntity, option: String) {
        if (option == "删除评论") {
            DialogHelper.showDialog(requireContext(), "提示", "确定要删除评论吗？", "确定", "取消", {
                mViewModel.deleteVideoComment(entity)
            }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true))
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(entity: EBDeleteComment) {
        //查看对话页面删除评论需同步评论列表
        if (this !is NewCommentConversationFragment) {
            val currentEntity = mAdapter?.entityList?.find { it.id == entity.commentEntity.id }
            val indexOf = mAdapter?.entityList?.indexOf(currentEntity) ?: 0
            mAdapter?.entityList?.remove(currentEntity)
            mAdapter?.notifyItemRemoved(indexOf)
            mCommentCount--
            mCommentListener?.onCountChange(mCommentCount)
            updateCommentCount()
            if (mAdapter?.entityList?.isEmpty() == true) {
                onLoadEmpty()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        if (data != null && requestCode == REQUEST_CODE_IMAGE) {
            val uris = Matisse.obtainResult(data)
            val pictureList = ArrayList<String>()
            for (uri in uris) {
                val picturePath = PathUtils.getPath(requireContext(), uri)
                if (picturePath != null) {
                    if (File(picturePath).length() > ImageUtils.getUploadFileMaxSize()) {
                        val count = ImageUtils.getUploadFileMaxSize() / 1024 / 1024
                        Utils.toast(requireContext(), requireContext().getString(R.string.pic_max_hint, count))
                        continue
                    }
                    Utils.log("picturePath = $picturePath")
                    pictureList.add(picturePath)
                } else {
                    Utils.log("picturePath is null")
                }
            }
            if (pictureList.size == 0) return
            mViewModel.pictureList.addAll(pictureList)
            addImageViews(mViewModel.pictureList)
        }
    }

    private fun addImageViews(pictureList: ArrayList<String>) {
        mImageContainer?.removeAllViews()
        mImageScrollView?.goneIf(pictureList.isEmpty())
        mDividerView?.goneIf(pictureList.isEmpty())
        pictureList.forEachIndexed { index, picture ->
            val binding = ItemCommentEditImageBinding.inflate(LayoutInflater.from(requireContext()), null, false)
            ImageUtils.display(binding.pictureView, "file://${picture}")
            binding.deleteBtn.setOnClickListener {
                if (index == 0 || index == pictureList.size - 1) {
                    mViewModel.pictureList.remove(picture)
                    addImageViews(mViewModel.pictureList)
                    return@setOnClickListener
                }
                mViewModel.pictureList.remove(picture)
                mImageContainer?.removeView(binding.root)
                if (mViewModel.pictureList.isEmpty()) {
                    mImageScrollView?.visibility = View.GONE
                    mDividerView?.visibility = View.GONE
                }
                checkSendBtnEnable()
                mViewModel.saveCommentDraft(mCommentEntity, commentEt.text.toString())
            }
            LinearLayout.LayoutParams(56f.dip2px(), 56f.dip2px()).apply {
                when (index) {
                    0 -> {
                        leftMargin = 12f.dip2px()
                        rightMargin = 4f.dip2px()
                    }
                    pictureList.size - 1 -> {
                        leftMargin = 4f.dip2px()
                        rightMargin = 12f.dip2px()
                    }
                    else -> {
                        leftMargin = 4f.dip2px()
                        rightMargin = 4f.dip2px()
                    }
                }

                binding.root.layoutParams = this
            }
            mImageContainer?.addView(binding.root)
            checkSendBtnEnable()
        }
        mViewModel.saveCommentDraft(mCommentEntity, commentEt.text.toString())
    }

    companion object {

        const val COMMENT_PAUSE = "comment_pause"
        const val COMMENT_RESUME = "comment_resume"

        const val SHOW_SOFT_KEY_BOARD_ON_STARTUP = "showSoftKeyboardOnStartUp"
        const val ANSWER_ID = "answerId"
        const val ARTICLE_ID = "articleId"
        const val VIDEO_ID = "videoId"
        const val COMMENT_COUNT = "commentCount"
        const val COMMENT_TYPE = "commentType"
        const val COMMUNITY_ID = "communityId"
        const val SHOW_INPUT_ONLY = "showInputOnly"
        const val COMMENT_ENTITY = "commentEntity"
        const val IS_VIDEO_AUTHOR = "isVideoAuthor"
        const val IS_STAIRS_COMMENT = "is_stairs_comment"
        const val REQUEST_CODE_IMAGE = 100

        fun getAnswerCommentInstance(
            answerId: String,
            showSoftKeyboardOnStartUp: Boolean,
            commentCount: Int,
            showInputOnly: Boolean,
            listener: AnswerDetailFragment.CommentListener
        )
                : NewCommentFragment {
            return NewCommentFragment().apply {
                mCommentListener = listener
                with(
                    bundleOf(
                        SHOW_SOFT_KEY_BOARD_ON_STARTUP to showSoftKeyboardOnStartUp,
                        ANSWER_ID to answerId,
                        COMMENT_COUNT to commentCount,
                        COMMENT_TYPE to CommentType.ANSWER,
                        SHOW_INPUT_ONLY to showInputOnly
                    )
                )
            }
        }

        fun getCommunityArticleCommentInstance(
            articleId: String,
            communityId: String,
            showSoftKeyboardOnStartUp: Boolean,
            commentCount: Int,
            showInputOnly: Boolean,
            useReplyApi: Boolean,
            commentEntity: CommentEntity?,
            listener: AnswerDetailFragment.CommentListener
        )
                : NewCommentFragment {
            val commentType = if (useReplyApi) {
                CommentType.COMMUNITY_ARTICLE_CONVERSATION
            } else {
                CommentType.COMMUNITY_ARTICLE
            }
            return NewCommentFragment().apply {
                mCommentListener = listener
                with(
                    bundleOf(
                        SHOW_SOFT_KEY_BOARD_ON_STARTUP to showSoftKeyboardOnStartUp,
                        ARTICLE_ID to articleId,
                        COMMENT_COUNT to commentCount,
                        COMMENT_TYPE to commentType,
                        COMMUNITY_ID to communityId,
                        SHOW_INPUT_ONLY to showInputOnly,
                        COMMENT_ENTITY to commentEntity
                    )
                )
            }
        }

        fun getCommunityQuestionCommentInstance(
            questionId: String,
            communityId: String,
            showSoftKeyboardOnStartUp: Boolean,
            commentCount: Int,
            showInputOnly: Boolean,
            useReplyApi: Boolean,
            commentEntity: CommentEntity?,
            listener: AnswerDetailFragment.CommentListener
        )
                : NewCommentFragment {
            val commentType = if (useReplyApi) {
                CommentType.COMMUNITY_QUESTION_CONVERSATION
            } else {
                CommentType.COMMUNITY_QUESTION
            }
            return NewCommentFragment().apply {
                mCommentListener = listener
                with(
                    bundleOf(
                        SHOW_SOFT_KEY_BOARD_ON_STARTUP to showSoftKeyboardOnStartUp,
                        QUESTION_ID to questionId,
                        COMMENT_COUNT to commentCount,
                        COMMENT_TYPE to commentType,
                        COMMUNITY_ID to communityId,
                        SHOW_INPUT_ONLY to showInputOnly,
                        COMMENT_ENTITY to commentEntity
                    )
                )
            }
        }

        fun getVideoCommentInstance(
            videoId: String,
            showSoftKeyboardOnStartUp: Boolean,
            commentCount: Int,
            isVideoAuthor: Boolean,
            commentEntity: CommentEntity? = null,
            showInputOnly: Boolean,
            isStairsComment: Boolean,
            useReplyApi: Boolean,
            listener: AnswerDetailFragment.CommentListener
        )
                : Fragment {
            return if (isStairsComment) {
                StairsCommentFragment().apply {
                    mCommentListener = listener
                    with(
                        bundleOf(
                            SHOW_SOFT_KEY_BOARD_ON_STARTUP to showSoftKeyboardOnStartUp,
                            VIDEO_ID to videoId,
                            COMMENT_COUNT to commentCount,
                            COMMENT_TYPE to CommentType.VIDEO,
                            COMMENT_ENTITY to commentEntity,
                            IS_VIDEO_AUTHOR to isVideoAuthor
                        )
                    )
                }
            } else {
                val commentType = if (useReplyApi) {
                    CommentType.VIDEO_CONVERSATION
                } else {
                    CommentType.VIDEO
                }
                NewCommentFragment().apply {
                    mCommentListener = listener
                    with(
                        bundleOf(
                            SHOW_SOFT_KEY_BOARD_ON_STARTUP to showSoftKeyboardOnStartUp,
                            VIDEO_ID to videoId,
                            COMMENT_COUNT to commentCount,
                            COMMENT_TYPE to CommentType.VIDEO,
                            COMMENT_ENTITY to commentEntity,
                            SHOW_INPUT_ONLY to showInputOnly,
                            IS_STAIRS_COMMENT to isStairsComment,
                            IS_VIDEO_AUTHOR to isVideoAuthor,
                            COMMENT_TYPE to commentType
                        )
                    )
                }
            }


        }

        fun getGameCollectionCommentInstance(
            gameCollectionId: String,
            commentId: String,
            showSoftKeyboardOnStartUp: Boolean,
            commentCount: Int,
            showInputOnly: Boolean,
            useReplyApi: Boolean,
            commentEntity: CommentEntity?,
            listener: AnswerDetailFragment.CommentListener
        )
                : NewCommentFragment {
            val commentType = if (useReplyApi) {
                CommentType.GAME_COLLECTION_CONVERSATION
            } else {
                CommentType.GAME_COLLECTION
            }
            return NewCommentFragment().apply {
                mCommentListener = listener
                with(
                    bundleOf(
                        SHOW_SOFT_KEY_BOARD_ON_STARTUP to showSoftKeyboardOnStartUp,
                        GAME_COLLECTION_ID to gameCollectionId,
                        KEY_COMMENT_ID to commentId,
                        COMMENT_COUNT to commentCount,
                        COMMENT_TYPE to commentType,
                        SHOW_INPUT_ONLY to showInputOnly,
                        COMMENT_ENTITY to commentEntity
                    )
                )
            }
        }
    }
}
