package com.gh.gamecenter.qa.comment.conversation

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.core.view.updateLayoutParams
import com.ethanhua.skeleton.Skeleton
import com.gh.gamecenter.common.base.activity.ToolBarActivity
import com.gh.gamecenter.core.AppExecutor
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.R
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.baselist.LoadType
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.databinding.FragmentArticleDetailCommentBinding
import com.gh.gamecenter.entity.CommentEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.qa.comment.base.BaseCommentAdapter
import com.gh.gamecenter.qa.comment.base.BaseCommentFragment
import com.gh.gamecenter.qa.comment.base.BaseCommentViewModel
import com.gh.gamecenter.qa.article.detail.CommentItemData
import com.gh.gamecenter.qa.comment.CommentActivity
import com.halo.assistant.HaloApp

class CommentConversationFragment :
    BaseCommentFragment<CommentItemData, CommentConversationViewModel>() {
    private lateinit var mViewModel: CommentConversationViewModel
    private lateinit var mBinding: FragmentArticleDetailCommentBinding
    private var mAdapterCommunity: CommentConversationAdapter? = null

    private var mUseAlternativeLayout = false // 是否使用特殊布局，隐藏顶部条数显示、额外顶部间距等

    override fun getLayoutId() = 0

    override fun getInflatedLayout() =
        FragmentArticleDetailCommentBinding.inflate(
            LayoutInflater.from(requireContext()),
            null,
            false
        ).apply { mBinding = this }.root

    override fun onCreate(savedInstanceState: Bundle?) {
        mViewModel = provideListViewModel()
        super.onCreate(savedInstanceState)

        mUseAlternativeLayout = arguments?.getBoolean(EntranceConsts.KEY_USE_ALTERNATIVE_LAYOUT) ?: false

        mViewModel.getComment()
        mViewModel.positionInOriginList = arguments?.getInt(EntranceConsts.KEY_POSITION) ?: -1
    }

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

    override fun provideListAdapter(): ListAdapter<*> {
        return mAdapterCommunity
            ?: CommentConversationAdapter(
                requireContext(),
                mViewModel,
                BaseCommentAdapter.AdapterType.SUB_COMMENT,
                mEntrance
            ) {
                if (it.user.id == UserManager.getInstance().userId) {
                    toast("不能回复自己")
                } else {
                    startCommentActivity(it)
                }
            }.apply {
                mAdapterCommunity = this
            }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val commentCount = data?.getIntExtra(CommentActivity.COMMENT_COUNT, 0)
        debounceActionWithInterval(Activity.RESULT_OK) {
            if (commentCount != null && commentCount != 0) {
                mViewModel.commentDetail?.reply = commentCount
                mViewModel.commentCount = commentCount
                mViewModel.load(LoadType.REFRESH)
                mBinding.toolbarContainer.commentDialogCountTv.text =
                    "${mViewModel.commentDetail?.reply}条回复"
                SyncPageRepository.postSyncData(
                    SyncDataEntity(
                        mViewModel.commentId,
                        SyncFieldConstants.ARTICLE_COMMENT_REPLY_COUNT,
                        commentCount
                    )
                )
            }
        }
    }

    private fun initView() {
        mBinding.run {
            mSkeletonScreen = Skeleton.bind(skeletonView).shimmer(false)
                .load(R.layout.fragment_article_detail_comment_skeleton).show()

            inputContainer.bottomCommentIv.visibility = View.GONE
            inputContainer.bottomCommentTv.visibility = View.GONE
            inputContainer.bottomLikeIv.visibility = View.GONE
            inputContainer.bottomLikeTv.visibility = View.GONE
            inputContainer.bottomStarIv.visibility = View.GONE
            inputContainer.bottomStarTv.visibility = View.GONE

            // 取消掉
            if (mUseAlternativeLayout) {
                toolbarContainer.root.visibility = View.GONE
                container.updateLayoutParams { this as FrameLayout.LayoutParams
                    setMargins(0, 0, 0, 0)
                }
            }

            inputContainer.replyTv.setRoundedColorBackground(R.color.background_space_2, 19F)
            inputContainer.replyTv.setDebouncedClickListener {
                mViewModel.commentDetail?.let { startCommentActivity(it) }
            }

            if (mViewModel.topCommentId.isNotBlank()) {
                initMenu(R.menu.menu_comment_detail)
                container.layoutParams = (container.layoutParams as ViewGroup.MarginLayoutParams).apply {
                    topMargin = 0
                }
                toolbarContainer.root.visibility = View.GONE
            } else {
                toolbarContainer.commentCloseIv.setOnClickListener { requireActivity().finish() }
            }
        }
    }

    override fun onMenuItemClick(menuItem: MenuItem?) {
        super.onMenuItemClick(menuItem)
        if (menuItem?.itemId == R.id.menu_more) {
            mViewModel.run {
                val actionMenuView = (requireActivity() as? ToolBarActivity)?.actionMenuView
                if (commentDetail != null && actionMenuView != null) {
                    val path = when {
                        articleId.isNotEmpty() -> BaseCommentAdapter.PATH_ARTICLE_DETAIL
                        questionId.isNotEmpty() -> BaseCommentAdapter.PATH_QUESTION_DETAIL
                        videoId.isNotEmpty() -> BaseCommentAdapter.PATH_VIDEO_DETAIL
                        else -> ""
                    }
                    val deleteCallBack: ((comment: CommentEntity) -> Unit) = { _ ->
                        requireActivity().finish()
                    }
                    BaseCommentAdapter.CommentItemViewHolder.showCommentOptions(
                        mViewModel,
                        actionMenuView,
                        commentDetail!!,
                        path,
                        deleteCallBack
                    )
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun initObserver() {
        mViewModel.loadResultLiveData.observeNonNull(this) {
            when (it) {
                BaseCommentViewModel.LoadResult.SUCCESS -> {
                    mReuseNoConn?.visibility = View.GONE
                    mListLoading?.visibility = View.GONE
                    mReuseDataException?.visibility = View.GONE
                    val showKeyboard =
                        arguments?.getBoolean(EntranceConsts.KEY_SHOW_KEYBOARD_IF_NEEDED)
                            ?: false
                    if (showKeyboard) {
                        mBinding.inputContainer.replyTv.performClick()
                    }

                    mBinding.inputContainer.replyTv.text =
                        "回复 @${mViewModel.commentDetail?.user?.name}"
                    mBinding.toolbarContainer.commentDialogCountTv.text =
                        "${mViewModel.commentDetail?.reply}条回复"
                    AppExecutor.uiExecutor.executeWithDelay(Runnable {
                        if ((mAdapterCommunity?.entityList?.size ?: 0) > 2) {
                            mListRv.smoothScrollToPosition(1)
                        }
                    }, 100)
                }
                else -> {
                    if (it == BaseCommentViewModel.LoadResult.DELETED) {
                        mReuseNoConn?.visibility = View.GONE
                        mReuseNoData?.visibility = View.GONE
                        mReuseDataException?.visibility = View.VISIBLE
                        toast(R.string.content_delete_toast)
                    } else {
                        mReuseNoConn?.visibility = View.VISIBLE
                        mReuseNoData?.visibility = View.GONE
                        mReuseDataException?.visibility = View.GONE
                        mReuseNoConn?.setOnClickListener {
                            mViewModel.getComment()
                            mReuseNoConn?.visibility = View.GONE
                            showSkeleton(true)
                        }
                    }

                    mListLoading?.visibility = View.GONE
                    mBinding.inputContainer.bottomContainer.visibility = View.GONE
                    mBinding.bottomShadowView.visibility = View.GONE
                    showSkeleton(false)
                }
            }
        }
    }

    override fun provideListViewModel(): CommentConversationViewModel {
        return viewModelProvider(
            CommentConversationViewModel.Factory(
                HaloApp.getInstance().application,
                arguments?.getString(EntranceConsts.KEY_COMMUNITY_ARTICLE_ID) ?: "",
                arguments?.getString(CommentActivity.VIDEO_ID) ?: "",
                arguments?.getString(CommentActivity.QUESTION_ID) ?: "",
                arguments?.getString(EntranceConsts.KEY_COMMUNITY_ID) ?: "",
                arguments?.getString(CommentActivity.GAME_COLLECTION_ID) ?: "",
                arguments?.getString(EntranceConsts.KEY_COMMENT_ID) ?: "",
                arguments?.getString(EntranceConsts.KEY_TOP_COMMENT_ID) ?: ""
            )
        )
    }

    override fun onBackPressed(): Boolean {
        requireActivity().finish()
        return super.onBackPressed()
    }

    override fun onLoadDone() {
        showSkeleton(false)
        super.onLoadDone()
    }

    private fun startCommentActivity(comment: CommentEntity) {
        if (mViewModel.articleId.isNotEmpty()) {
            val intent = CommentActivity.getArticleCommentReplyIntent(
                requireContext(),
                mViewModel.articleId,
                mViewModel.commentDetail?.reply,
                true,
                comment.id ?: "",
                comment,
                true
            )
            startActivityForResult(intent, CommentActivity.REQUEST_CODE)
        } else if (mViewModel.videoId.isNotEmpty()) {
            val intent = CommentActivity.getVideoCommentReplyIntent(
                requireContext(),
                mViewModel.videoId,
                mViewModel.commentCount,
                comment.user.id == UserManager.getInstance().userId,
                true, true, comment
            )
            startActivityForResult(intent, CommentActivity.REQUEST_CODE)
        } else if (mViewModel.questionId.isNotEmpty()) {
            val intent = CommentActivity.getQuestionCommentReplyIntent(
                requireContext(),
                mViewModel.questionId,
                "",
                mViewModel.commentCount,
                true,
                true,
                comment
            )
            startActivityForResult(intent, CommentActivity.REQUEST_CODE)
        } else if (mViewModel.gameCollectionId.isNotEmpty()) {
            val intent = CommentActivity.getGameCollectionCommentReplyIntent(
                requireContext(),
                mViewModel.gameCollectionId,
                arguments?.getString(EntranceConsts.KEY_COMMENT_ID) ?: "",
                mViewModel.commentCount,
                comment
            )
            startActivityForResult(intent, CommentActivity.REQUEST_CODE)
        }
    }
}