package com.gh.gamecenter.personalhome

import android.app.Activity
import android.content.Context
import android.text.SpannableStringBuilder
import android.view.View
import com.facebook.drawee.view.SimpleDraweeView
import com.gh.common.util.DialogUtils
import com.gh.common.util.DirectUtils
import com.gh.common.util.NewsUtils
import com.gh.common.view.ImageContainerView
import com.gh.common.view.ImageContainerView.Companion.toImageContainerData
import com.gh.gamecenter.ImageViewerActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.callback.ConfirmListener
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.core.utils.SpanBuilder
import com.gh.gamecenter.databinding.CommunityAnswerItemBinding
import com.gh.gamecenter.entity.PersonalHistoryEntity
import com.gh.gamecenter.feature.entity.AnswerEntity
import com.gh.gamecenter.feature.entity.ForumVideoEntity
import com.gh.gamecenter.forum.detail.ForumDetailActivity
import com.gh.gamecenter.forum.home.AnswerArticleVideoViewEventHelper
import com.gh.gamecenter.forum.home.ArticleItemVideoView.Companion.toArticleVideoData
import com.gh.gamecenter.qa.answer.BaseAnswerOrArticleItemViewHolder
import com.gh.gamecenter.video.detail.VideoDetailContainerViewModel
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.shuyu.gsyvideoplayer.utils.OrientationUtils

class PersonalItemViewHolder(
    val context: Context,
    val binding: CommunityAnswerItemBinding,
    private val itemClickCallback: (historyEntity: PersonalHistoryEntity, position: Int) -> Unit
) :
    BaseAnswerOrArticleItemViewHolder(binding.root) {

    fun bindPersonalItem(historyEntity: PersonalHistoryEntity, entrance: String, position: Int) {
        commentCount.isClickable = true
        bindCommendAndVote(historyEntity, entrance)

        if (historyEntity.community.type == "official_bbs") {
            forumIcon?.displayGameIcon(historyEntity.community.icon, null)
        } else {
            forumIcon?.displayGameIcon(
                historyEntity.community.game?.getIcon(),
                historyEntity.community.game?.iconSubscript,
                historyEntity.community.game?.iconFloat
            )
        }

        forumNameContainer?.setOnClickListener {
            MtaHelper.onEvent(getEventId(entrance), getKey(entrance), historyEntity.community.name)
            itemView.context.startActivity(
                ForumDetailActivity.getIntent(
                    itemView.context,
                    historyEntity.community.id,
                    entrance
                )
            )
        }

        val answer = AnswerEntity()
        answer.images = historyEntity.images
        answer.imagesInfo = historyEntity.imagesInfo
        answer.videos = historyEntity.videos
        answer.type = historyEntity.type
        answer.id = historyEntity.id
        answer.communityId = historyEntity.community.id
        answer.communityName = historyEntity.community.name
        answer.status = historyEntity.status
        answer.user.id = historyEntity.user.id ?: ""

        binding.imageContainer.bindData(
            answer.toImageContainerData(),
            object : ImageContainerView.OnImageContainerEventListener {
                override fun onImageClick(
                    images: List<String>,
                    position: Int,
                    imageViewList: ArrayList<SimpleDraweeView>
                ) {
                    val intent = ImageViewerActivity.getIntent(
                        context, answer.images.toArrayList(), position, imageViewList,
                        if (answer.type == "community_article") answer else null, entrance, true
                    )
                    context.startActivity(intent)
                }

                override fun onVideoCLick(videoId: String) {
                    DirectUtils.directToVideoDetail(
                        context,
                        videoId,
                        VideoDetailContainerViewModel.Location.VIDEO_HOT.value,
                        showComment = false,
                        entrance = entrance,
                        path = ""
                    )
                }

            })


        bindVideoData(historyEntity.transformForumVideoEntity())

        binding.run {
            topLine.goneIf(position == 0)
            forumNameLl.visibleIf(historyEntity.community.id.isNotEmpty())
            userIcon.display(historyEntity.user.border, historyEntity.user.icon, historyEntity.user.auth?.icon)
            userName.text = historyEntity.user.name
            ImageUtils.display(userBadgeIcon, historyEntity.user.badge?.icon)
            userBadgeIcon.goneIf(historyEntity.user.badge == null)
            userBadgeName.text = historyEntity.user.badge?.name
            time.text =
                (if (historyEntity.me.isFollower || historyEntity.status == "pending" || historyEntity.status == "fail") " · " else "") + NewsUtils.getFormattedTime(
                    historyEntity.time!!
                )
            statusTv.goneIf(!(historyEntity.status == "pending" || historyEntity.status == "fail") && !historyEntity.me.isFollower)
            statusTv.setText(
                when {
                    historyEntity.me.isFollower -> R.string.follow_status
                    historyEntity.status == "pending" -> R.string.content_pending_status
                    else -> R.string.fail_status
                }
            )
            statusTv.setTextColor(
                when {
                    historyEntity.me.isFollower -> com.gh.gamecenter.common.R.color.theme_alpha_80
                    historyEntity.status == "pending" -> com.gh.gamecenter.common.R.color.text_tertiary
                    else -> com.gh.gamecenter.common.R.color.text_CCFF5269
                }.toColor(context)
            )
            statusTv.setDrawableStart(
                when {
                    historyEntity.me.isFollower -> R.drawable.ic_forum_follow
                    historyEntity.status == "pending" -> R.drawable.ic_forum_pending
                    else -> R.drawable.icon_forum_fail
                }
            )
            authTv.goneIf(historyEntity.user?.auth == null) {
                authTv.text = historyEntity.user?.auth?.text
                time.setPadding(8F.dip2px(), 0, 0, 0)
            }
            if (statusTv.visibility == View.VISIBLE) {
                authTv.setPadding(8F.dip2px(), 0, 0, 0)
            }
            title.goneIf(historyEntity.type.contains("answer"))
            title.text =
                if ((historyEntity.type.contains("question") || historyEntity.type.contains("article") || historyEntity.type.contains(
                        "video"
                    ))
                ) historyEntity.title else historyEntity.question.title
            questionTitle.goneIf(!historyEntity.type.contains("answer"))
            questionTitle.text = historyEntity.question.title
            content.goneIf(historyEntity.brief.isEmpty() && historyEntity.des.isEmpty() && historyEntity.description.isEmpty())
            content.text = when {
                historyEntity.type.contains("video") -> historyEntity.des
                historyEntity.type.contains("question") -> historyEntity.description
                else -> historyEntity.brief
            }
            forumNameTv.text = historyEntity.community.name

            when (historyEntity.type) {
                "question" -> {
                    val titleStr = "  ${historyEntity.title}"
                    val drawable = R.drawable.ic_ask_label.toDrawable()
                    drawable?.run {
                        setBounds(0, 0, 16F.dip2px(), 16F.dip2px())
                        title.text = SpanBuilder(titleStr).image(0, 1, this).build()
                    }
                }

                "answer" -> {
                    val briefStr = "  ${historyEntity.brief}"
                    val drawable = R.drawable.ic_answer_label.toDrawable()
                    drawable?.run {
                        setBounds(0, 0, 16F.dip2px(), 16F.dip2px())
                        content.text = SpanBuilder(briefStr).image(0, 1, this).build()
                    }
                }

                "community_article" -> {
                    if (historyEntity.getPassVideos().isNotEmpty() && historyEntity.images.isNotEmpty()) {
                        val titleStr = title.text
                        val videoSpan =
                            SpanBuilder("  ").image(1, "  ".length, R.drawable.ic_article_video_label).build()
                        title.text = SpannableStringBuilder()
                            .append(titleStr)
                            .append(videoSpan)
                    }
                }
            }

            title.setOnClickListener {
                itemView.performClick()
            }

            historyEntity.user.run {
                userBadgeName.setOnClickListener { userBadgeIcon.performClick() }
                userBadgeIcon.setOnClickListener {
                    DialogUtils.showViewBadgeDialog(context, badge, object : ConfirmListener {
                        override fun onConfirm() {
                            DirectUtils.directToBadgeWall(context, id, name, icon)
                        }
                    })
                }
            }


            // 禁止click事件穿透
            userIcon.setOnClickListener {}
        }
        itemView.setOnClickListener {
            itemClickCallback.invoke(historyEntity, position)
        }
    }

    private fun bindVideoData(entity: ForumVideoEntity) {
        binding.run {
            if (entity.url.isEmpty()) {
                horizontalVideoView.visibility = View.GONE
                verticalVideoView.visibility = View.GONE
            } else {
                val videoInfo = entity.videoInfo
                val visibleView = if (videoInfo.height > videoInfo.width) {
                    horizontalVideoView.visibility = View.GONE
                    verticalVideoView.visibility = View.VISIBLE
                    verticalVideoView
                } else {
                    horizontalVideoView.visibility = View.VISIBLE
                    verticalVideoView.visibility = View.GONE
                    horizontalVideoView
                }

                val orientationUtils = OrientationUtils(context as Activity, visibleView)
                orientationUtils.isEnable = false
                GSYVideoOptionBuilder()
                    .setIsTouchWiget(false)
                    .setUrl(entity.url)
                    .setRotateViewAuto(false)
                    .setCacheWithPlay(true)
                    .setRotateWithSystem(false)
                    .setReleaseWhenLossAudio(true)
                    .setLooping(false)
                    .setShowFullAnimation(false)
                    .setEnlargeImageRes(R.drawable.ic_video_enter_full_screen)
                    .setShrinkImageRes(R.drawable.ic_video_exit_full_screen)
                    .setVideoAllCallBack(object : GSYSampleCallBack() {
                        override fun onQuitFullscreen(url: String?, vararg objects: Any) {
                            orientationUtils.backToProtVideo()
                        }
                    })
                    .build(visibleView)
                visibleView.updateVideoData(
                    entity.toArticleVideoData(),
                    AnswerArticleVideoViewEventHelper(entity, orientationUtils)
                )
            }
        }
    }
}
