package com.gh.gamecenter.qa.video.detail.desc

import android.animation.ValueAnimator
import android.text.Layout
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.animation.doOnEnd
import androidx.core.animation.doOnStart
import androidx.core.view.marginTop
import com.gh.common.util.CommentUtils
import com.gh.common.util.DialogUtils
import com.gh.common.util.DirectUtils
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.callback.ConfirmListener
import com.gh.gamecenter.common.entity.NormalShareEntity
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.SpanBuilder
import com.gh.gamecenter.databinding.ItemVideoDescTopBinding
import com.gh.gamecenter.entity.ForumVideoEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.qa.dialog.MoreFunctionPanelDialog
import com.gh.gamecenter.qa.video.detail.ForumVideoDetailViewModel
import kotlin.math.max

class VideoDescTopViewHolder(
    val binding: ItemVideoDescTopBinding,
    var mIsExpand: Boolean,
    var mShrinkHeight: Int,
    var mExpandHeight: Int,
    val mVideoDetailViewModel: ForumVideoDetailViewModel,
    val mViewModel: VideoDescViewModel
) : BaseRecyclerViewHolder<Any>(binding.root) {
    private var mIsAnimationFinish = true
    fun bindData(entity: ForumVideoEntity) {
        binding.userNameTv.text = entity.user.name
        ImageUtils.display(binding.badgeIv, entity.user.badge?.icon)
        binding.badgeIv.goneIf(entity.user.badge == null)
        binding.fansAndTimeTv.text = if (entity.ipSource != null && entity.ipSource.region.isNotEmpty()) {
            "${entity.user.count.fans}粉丝 · ${CommentUtils.getCommentTime(entity.time.upload)} · ${entity.ipSource.region}"
        } else {
            "${entity.user.count.fans}粉丝 · ${CommentUtils.getCommentTime(entity.time.upload)}"
        }
        binding.concernBtn.run {
            goneIf(entity.user.id == UserManager.getInstance().userId)
            text = if (entity.me.isFollower) "已关注" else "关注"
            background =
                if (entity.me.isFollower) R.drawable.button_round_gray_light.toDrawable() else R.drawable.button_round_primary_light.toDrawable()
            setTextColor(if (entity.me.isFollower) R.color.text_subtitleDesc.toColor() else R.color.theme_font.toColor())
        }
        binding.titleTv.text = entity.title
        binding.desTv.text = entity.des
        binding.desTv.goneIf(entity.des.isEmpty())
        binding.activityNameTv.goneIf(entity.tagActivityName.isEmpty())
        binding.activityNameTv.text = entity.tagActivityName
        binding.userAvatar.display(entity.user.border, entity.user.icon, entity.user.auth?.icon)
        binding.likeIv.setImageDrawable(if (entity.me.isVoted) R.drawable.ic_forum_video_detail_liked.toDrawable() else R.drawable.ic_forum_video_detail_like.toDrawable())
        binding.likeCountTv.text = entity.count.vote.toString()
        binding.likeCountTv.setTextColor(if (entity.me.isVoted) R.color.theme_font.toColor() else R.color.text_subtitleDesc.toColor())
        binding.collectIv.setImageDrawable(if (entity.me.isVideoFavorite) R.drawable.ic_forum_video_detail_collected.toDrawable() else R.drawable.ic_forum_video_detail_collect.toDrawable())
        binding.collectCountTv.text = entity.count.favorite.toString()
        binding.collectCountTv.setTextColor(if (entity.me.isVideoFavorite) R.color.theme_font.toColor() else R.color.text_subtitleDesc.toColor())
        binding.shareIv.setImageDrawable(R.drawable.ic_forum_video_detail_share.toDrawable())
        binding.shareTv.text = entity.share.toString()

        if (entity.original == "yes") {
            binding.originalTv.visibility = View.VISIBLE
            binding.activityNameTv.layoutParams =
                (binding.activityNameTv.layoutParams as ConstraintLayout.LayoutParams).apply {
                    leftMargin = 8f.dip2px()
                }
        }
        if (entity.getSimplifyChoicenessStatus() == "pass") {
            binding.titleTv.text =
                SpanBuilder("   ${entity.title}").image(0, 1, R.drawable.ic_essence).build()
        }
        initAnimation(entity)

        val bbsType = if (entity.bbs?.type == "game_bbs") "游戏论坛" else "综合论坛"
        binding.userAvatar.setOnClickListener {
            DirectUtils.directToHomeActivity(binding.root.context, entity.user.id, "视频详情", "")
            NewLogUtils.logVideoDetailClick(
                "click_detail_tab_profile_photo", entity.user.id,
                "视频贴", entity.bbs?.id ?: "", bbsType
            )
        }
        binding.userNameTv.setOnClickListener {
            DirectUtils.directToHomeActivity(binding.root.context, entity.user.id, "视频详情", "")
            NewLogUtils.logVideoDetailClick(
                "click_detail_tab_nickname", entity.user.id,
                "视频贴", entity.bbs?.id ?: "", bbsType
            )
        }
        binding.likeContainer.setOnClickListener {
            debounceActionWithInterval(it.id, 2000) {
                mViewModel.postVote()
                NewLogUtils.logVideoDetailClick(
                    "click_detail_tab_like", entity.user.id,
                    "视频贴", entity.bbs?.id ?: "", bbsType, entity.id
                )
            }
        }
        binding.collectContainer.setOnClickListener {
            debounceActionWithInterval(it.id) {
                mViewModel.postFavorite()
                NewLogUtils.logVideoDetailClick(
                    "click_detail_tab_collect", entity.user.id,
                    "视频贴", entity.bbs?.id ?: "", bbsType, entity.id
                )
            }
        }
        binding.concernBtn.setOnClickListener {
            if (entity.user.id != UserManager.getInstance().userId) {
                debounceActionWithInterval(it.id) {
                    if (!entity.me.isFollower) {
                        mViewModel.followCommand()
                    } else {
                        DialogHelper.showDialog(
                            binding.concernBtn.context,
                            "提示",
                            "确定要取消关注 ${entity.user.name} 吗？",
                            "确定取消",
                            "暂不取消",
                            {
                                mViewModel.followCommand()
                            })
                    }
                    NewLogUtils.logVideoDetailClick(
                        "click_detail_tab_follow", entity.user.id,
                        "视频贴", entity.bbs?.id ?: "", bbsType
                    )
                }
            }
        }
        binding.shareContainer.setOnClickListener {
            share(entity)
            NewLogUtils.logVideoDetailClick(
                "click_detail_tab_share", entity.user.id,
                "视频贴", entity.bbs?.id ?: "", bbsType, entity.id
            )
        }
        binding.badgeIv.setOnClickListener {
            DialogUtils.showViewBadgeDialog(binding.root.context, entity.user.badge, object : ConfirmListener {
                override fun onConfirm() {
                    DirectUtils.directToBadgeWall(
                        binding.root.context,
                        entity.user.id,
                        entity.user.name,
                        entity.user.badge?.icon
                    )
                }
            })
        }
    }

    private fun initAnimation(entity: ForumVideoEntity) {
        binding.root.post {
            mShrinkHeight = if (mShrinkHeight == 0) {
                getTextViewHeight(binding.titleTv, 1)
            } else mShrinkHeight

            mExpandHeight = if (mExpandHeight == 0) {
                var height = getTextViewHeight(binding.titleTv) +
                        getTextViewHeight(binding.desTv) +
                        (if (binding.desTv.visibility == View.VISIBLE) binding.desTv.marginTop else 0) +
                        (if (binding.activityNameTv.visibility == View.VISIBLE || binding.originalTv.visibility == View.VISIBLE) binding.activityNameTv.marginTop else 0)
                if (binding.activityNameTv.visibility == View.VISIBLE || binding.originalTv.visibility == View.VISIBLE) {
                    height += max(
                        getTextViewHeight(binding.activityNameTv),
                        binding.originalTv.measuredHeight
                    )
                }
                height
            } else mExpandHeight

            if (mIsExpand) {
                binding.titleTv.maxLines = Int.MAX_VALUE
                updateTitleContainerHeight(mExpandHeight)
            } else {
                binding.titleTv.maxLines = 1
                updateTitleContainerHeight(mShrinkHeight)
            }

            //若标题未超过一行或无描述内容、活动标签、原创标签，箭头不显示
            val ellipsisCount =
                binding.titleTv.layout?.getEllipsisCount(binding.titleTv.lineCount - 1) ?: 0
            binding.expandMoreIv.goneIf(entity.des.isEmpty() && entity.tagActivityName.isEmpty() && entity.original != "yes" && ellipsisCount == 0)
        }
        binding.expandMoreIv.setOnClickListener {
            NewLogUtils.logVideoDetailClick(if (!mIsExpand) "click_detail_tab_down" else "click_detail_tab_up")
            val animator = if (mIsExpand) {
                ValueAnimator.ofInt(mExpandHeight, mShrinkHeight)
            } else {
                ValueAnimator.ofInt(mShrinkHeight, mExpandHeight)
            }
            animator.duration = 300
            animator.addUpdateListener {
                val value = it.animatedValue as Int
                updateTitleContainerHeight(value)
            }
            animator.doOnStart {
                if (!mIsExpand) {
                    binding.titleTv.maxLines = Int.MAX_VALUE
                }
                mIsAnimationFinish = false
            }
            animator.doOnEnd {
                if (mIsExpand) {
                    binding.titleTv.maxLines = 1
                }
                mIsExpand = !mIsExpand
                binding.expandMoreIv.rotation = if (mIsExpand) 180f else 0f
                mIsAnimationFinish = true
            }
            if (mIsAnimationFinish) {
                animator.start()
            }
        }
    }

    private fun share(entity: ForumVideoEntity) {
        val shareEntity = NormalShareEntity(
            id = entity.id,
            shareUrl = binding.root.context.getString(R.string.share_community_video_url, entity.shortId),
            shareIcon = entity.poster,
            shareTitle = entity.title,
            shareSummary = entity.des,
            shareEntrance = ShareUtils.ShareEntrance.video
        )
        MoreFunctionPanelDialog.showMoreDialog(
            binding.root.context as AppCompatActivity,
            arrayListOf(),
            shareEntity.shareTitle,
            shareEntity,
            "",
            ""
        )
    }

    private fun updateTitleContainerHeight(newHeight: Int) {
        (binding.contentContainer.layoutParams as ConstraintLayout.LayoutParams).apply {
            height = newHeight
            binding.contentContainer.layoutParams = this
        }
    }

    private fun getTextViewHeight(view: TextView, lineCount: Int = 0): Int {
        if (view.visibility == View.GONE) return 0
        val layout: Layout = view.layout ?: return 0
        val desired: Int = layout.getLineTop(if (lineCount > 0) lineCount else view.lineCount)
        val padding = view.compoundPaddingTop + view.compoundPaddingBottom
        return desired + padding
    }
}