package com.gh.gamecenter.forum.home


import android.app.Activity
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.text.SpannableStringBuilder
import android.view.View
import com.gh.common.util.*
import com.gh.common.util.DialogUtils
import com.gh.common.util.LogUtils
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.callback.ConfirmListener
import com.gh.gamecenter.common.entity.CommunityEntity
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.core.utils.SpanBuilder
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.databinding.CommunityAnswerItemBinding
import com.gh.gamecenter.entity.ForumVideoEntity
import com.gh.gamecenter.eventbus.EBUserFollow
import com.gh.gamecenter.forum.detail.ForumDetailActivity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.qa.answer.BaseAnswerOrArticleItemViewHolder
import com.gh.gamecenter.qa.article.detail.ArticleDetailActivity
import com.gh.gamecenter.qa.entity.AnswerEntity
import com.gh.gamecenter.qa.entity.ArticleEntity
import com.gh.gamecenter.qa.entity.QuestionsDetailEntity
import com.gh.gamecenter.qa.questions.invite.QuestionsInviteActivity
import com.gh.gamecenter.qa.questions.newdetail.NewQuestionDetailActivity
import com.gh.gamecenter.qa.video.detail.ForumVideoDetailActivity
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.shuyu.gsyvideoplayer.utils.OrientationUtils
import org.greenrobot.eventbus.EventBus

class ForumArticleAskItemViewHolder(val binding: CommunityAnswerItemBinding) :
    BaseAnswerOrArticleItemViewHolder(binding.root) {

    fun bindForumAnswerItem(entity: AnswerEntity, entrance: String, path: String, position: Int? = null) {
        bindItem(entity, entrance, path)
        bindCommendAndVote(entity, BaseActivity.mergeEntranceAndPath(entrance, path), path, position)
    }

    fun bindForumArticleItem(entity: ArticleEntity, entrance: String, path: String, position: Int) {
        bindItem(entity.transformAnswerEntity(), entrance, path)
        bindCommendAndVote(entity, BaseActivity.mergeEntranceAndPath(entrance, path), position)
    }

    private fun bindItem(entity: AnswerEntity, entrance: String, path: String) {
        binding.run {
            BaseActivity.updateStaticView(root, emptyList())
            questionTitle.goneIf(entity.type != "answer")
            questionTitle.text = entity.questions.title
            userName.text = entity.user.name
            userBadgeName.text = entity.user.badge?.name
            ImageUtils.display(userBadgeIcon, entity.user.badge?.icon)
            ImageUtils.display(popularAnswerUserIcon, entity.popularAnswer?.user?.icon)
            userBadgeIcon.goneIf(entity.user.badge == null)
            concernBtn.goneIf(entity.me.isFollower || entity.user.id == UserManager.getInstance().userId)
            time.text =
                (if (entity.me.isFollower || entity.status == "pending" || entity.status == "fail") " · " else "") + NewsUtils.getFormattedTime(
                    entity.time!!
                )
            statusTv.goneIf(!(entity.status == "pending" || entity.status == "fail") && !entity.me.isFollower)
            statusTv.setText(
                when {
                    entity.me.isFollower -> R.string.follow_status
                    entity.status == "pending" -> R.string.content_pending_status
                    else -> R.string.fail_status
                }
            )
            statusTv.setTextColor(
                when {
                    entity.me.isFollower -> R.color.theme_alpha_80
                    entity.status == "pending" -> R.color.text_subtitleDesc
                    else -> R.color.text_CCFF5269
                }.toColor(statusTv.context)
            )
            statusTv.setDrawableStart(
                when {
                    entity.me.isFollower -> R.drawable.ic_forum_follow
                    entity.status == "pending" -> R.drawable.ic_forum_pending
                    else -> R.drawable.icon_forum_fail
                }
            )
            title.goneIf(entity.type == "answer")
            title.text = if (entity.type.contains("video")) entity.articleTitle else entity.questions.title
            content.text = if (entity.type.contains("video")) entity.des else entity.brief
            popularAnswerContainer.background = GradientDrawable().apply {
                setColor(Color.parseColor("#F5F6F7"))
                cornerRadius = 4F.dip2px().toFloat()
            }
            popularAnswerUserName.text = entity.popularAnswer?.user?.name
            popularAnswerContent.text = entity.popularAnswer?.brief
            forumNameTv.text = entity.bbs.name
        }

        binding.userIcon.display(entity.user.border, entity.user.icon, entity.user.auth?.icon)
        if (entity.type == "answer") {
            binding.content.goneIf(entity.content.isEmpty())
            binding.content.text = entity.content
            val content = "  ${entity.content}"
            val drawable = R.drawable.ic_answer_label.toDrawable()
            drawable?.run {
                setBounds(0, 0, 16F.dip2px(), 16F.dip2px())
                binding.content.text = SpanBuilder(content).image(0, 1, this).build()
            }
        } else if (entity.type == "question") {
            binding.content.goneIf(entity.questions.description.isNullOrEmpty())
            binding.content.text = entity.questions.description
            val title = "  ${entity.questions.title}"
            val drawable = R.drawable.ic_ask_label.toDrawable()
            drawable?.run {
                setBounds(0, 0, 16F.dip2px(), 16F.dip2px())
                binding.title.text = SpanBuilder(title).image(0, 1, this).build()
            }
        } else {
            binding.content.visibility = View.VISIBLE
            if (entity.type == "video") {
                binding.content.goneIf(entity.des.isEmpty())
            } else {
                binding.content.visibility = View.VISIBLE
            }
            //若文章内有图片和视频,标题后增加‘有视频’标签 issues-1052
            if (entity.getPassVideos().isNotEmpty()) {
                val videoSpan = SpanBuilder("  ").image(1, "  ".length, R.drawable.ic_article_video_label).build()
                binding.title.text = SpannableStringBuilder()
                    .append(entity.questions.title)
                    .append(videoSpan)
            } else {
                binding.title.text = entity.questions.title
            }
        }

        binding.imageContainer.bindData(entity, entrance, path)
        bindVideoData(entity.transformForumVideoEntity())

        val user = entity.user
        val contentType = when (entity.type) {
            "community_article" -> "帖子"
            "video" -> "视频帖"
            "question" -> "提问帖"
            else -> "提问帖评论"
        }
        val userId = user.id ?: ""
        val bbsId = entity.bbs.id
        val bbsType = if (entity.bbs.type == "official_bbs") "综合论坛" else "游戏论坛"
        binding.userBadgeName.setOnClickListener { binding.userBadgeIcon.performClick() }
        binding.userBadgeIcon.setOnClickListener {
            if (entrance == "社区") {
                NewLogUtils.logRecommendFeedBadgeClick(user.badge?.name ?: "")
            }
            if (entrance == "论坛详情") {
                NewLogUtils.logForumDetailFeedBadgeClick(user.badge?.name ?: "", bbsId, bbsType)
            }
            DialogUtils.showViewBadgeDialog(binding.root.context, user.badge, object : ConfirmListener {
                override fun onConfirm() {
                    MtaHelper.onEvent("进入徽章墙_用户记录", path, user.name + "（" + user.id + "）")
                    MtaHelper.onEvent("徽章中心", "进入徽章中心", path)
                    DirectUtils.directToBadgeWall(binding.root.context, user.id, user.name, user.icon)
                }
            })
        }

        binding.userIcon.setOnClickListener {
            if (entrance == "社区") {
                NewLogUtils.logRecommendFeedUserClick("click_for_you_profile_photo", userId, contentType)
            }
            if (entrance == "论坛详情") {
                NewLogUtils.logForumDetailFeedUserClick(
                    "click_forum_detail_profile_photo",
                    userId,
                    contentType,
                    "${path}tab",
                    bbsId,
                    bbsType
                )
            }
            MtaHelper.onEvent(
                getEventId(BaseActivity.mergeEntranceAndPath(entrance, path)),
                getKey(BaseActivity.mergeEntranceAndPath(entrance, path)),
                "用户头像"
            )
            DirectUtils.directToHomeActivity(binding.root.context, entity.user.id, 1, entrance, path)
        }
        binding.userName.setOnClickListener {
            if (entrance == "社区") {
                NewLogUtils.logRecommendFeedUserClick("click_for_you_nickname", userId, contentType)
            }
            if (entrance == "论坛详情") {
                NewLogUtils.logForumDetailFeedUserClick(
                    "click_forum_detail_nickname",
                    userId,
                    contentType,
                    "${path}tab",
                    bbsId,
                    bbsType
                )
            }
            MtaHelper.onEvent(
                getEventId(BaseActivity.mergeEntranceAndPath(entrance, path)),
                getKey(BaseActivity.mergeEntranceAndPath(entrance, path)),
                "用户名字"
            )
            DirectUtils.directToHomeActivity(binding.root.context, entity.user.id, 1, entrance, path)
        }
        binding.concernBtn.setOnClickListener {
            debounceActionWithInterval(R.id.concernBtn, 1000) {
                CheckLoginUtils.checkLogin(itemView.context, entrance) {
                    if (entrance == "社区") {
                        NewLogUtils.logRecommendFeedUserClick("click_for_you_follow", userId, contentType)
                    }
                    if (entrance == "论坛首页+(搜索)") {
                        NewLogUtils.logForumSearchFollowClick("关注用户", bbsId, bbsType, userId)
                    }
                    if (entrance == "论坛详情") {
                        NewLogUtils.logForumDetailFeedUserClick(
                            "click_forum_detail_follow",
                            userId,
                            contentType,
                            "${path}tab",
                            bbsId,
                            bbsType
                        )
                    }
                    followUser(entity) {
                        entity.me.isFollower = true
                        binding.concernBtn.visibility = View.GONE
                        binding.statusTv.visibility = View.VISIBLE
                        binding.statusTv.setDrawableStart(R.drawable.ic_forum_follow)
                        binding.statusTv.setTextColor(R.color.theme_alpha_80.toColor(binding.statusTv.context))
                        binding.statusTv.text = R.string.follow_status.toResString()
                        binding.time.text = " · ${binding.time.text}"
                        ToastUtils.toast("关注成功")
                        EventBus.getDefault().post(EBUserFollow(userId, true))
                    }
                }
            }
        }
    }

    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(itemView.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_game_detail_enter_full_screen)
                    .setShrinkImageRes(R.drawable.ic_game_detail_exit_full_screen)
                    .setVideoAllCallBack(object : GSYSampleCallBack() {
                        override fun onQuitFullscreen(url: String?, vararg objects: Any) {
                            orientationUtils.backToProtVideo()
                            visibleView.uploadVideoStreamingPlaying("退出全屏")
                        }
                    })
                    .build(visibleView)
                visibleView.run {
                    updateVideoData(entity)
                    updateThumb(entity.poster)
                    updateDurationTv(entity.duration)

                    setVideoStatus(entity.status)

                    fullscreenButton.setOnClickListener {
                        val horizontalVideoView =
                            startWindowFullscreen(itemView.context, true, true) as? ArticleItemVideoView
                        if (horizontalVideoView == null) {
                            toastInInternalRelease("全屏失败，请向技术人员提供具体的操作步骤")
                            return@setOnClickListener
                        }
                        orientationUtils.resolveByClick()
                        horizontalVideoView.uuid = uuid
                        horizontalVideoView.updateVideoData(entity)
                        horizontalVideoView.updateThumb(entity.poster)
                        horizontalVideoView.violenceUpdateMuteStatus()
                        horizontalVideoView.setFullViewStatus()
                        uploadVideoStreamingPlaying("开始播放")
                        uploadVideoStreamingPlaying("点击全屏")
                    }
                }
            }
        }
    }

    override fun bindCommendAndVote(entity: AnswerEntity, entrance: String, path: String?, position: Int?) {
        inviteAnswer.visibility = View.GONE
        voteCountContainer.visibility = View.VISIBLE

        if (entity.type != "question") {
            binNormalView(entity)
        } else {
            if (entity.questions.answerCount > 0) {
                commentCount.text = entity.questions.answerCount.toString()
            } else {
                commentCount.text = "回答"
            }
            inviteAnswer.visibility = View.VISIBLE
            voteCountContainer.visibility = View.GONE
        }

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

        forumNameTv.setOnClickListener {
            MtaHelper.onEvent(getEventId(entrance), getKey(entrance), entity.bbs.name)
            itemView.context.startActivity(ForumDetailActivity.getIntent(itemView.context, entity.bbs.id, entrance))
            LogUtils.uploadAccessToBbs(entity.bbs.id, "文章外所属论坛")
        }

        forumNameContainer?.setOnClickListener {
            forumNameTv.performClick()
        }

        inviteAnswer.setOnClickListener {
            CheckLoginUtils.checkLogin(itemView.context, "${entrance}-点赞") {
                val questionsDetailEntity = QuestionsDetailEntity(
                    id = entity.id,
                    title = entity.questions.title,
                    images = entity.images,
                    description = entity.questions.description
                )
                it.context.startActivity(
                    QuestionsInviteActivity.getIntent(
                        it.context,
                        questionsDetailEntity,
                        entrance
                    )
                )
            }
        }

        commentCount.setOnClickListener {
            if (filterIllegalCommentStatus(entity.commentable, entity.active)) return@setOnClickListener

            if (entrance.contains("论坛详情") && position != null) {
                entity.run {
                    val userId = entity.user.id ?: ""
                    val contentId = entity.id ?: ""
                    val contentType = when (entity.type) {
                        "community_article" -> "帖子"
                        "video" -> "视频帖"
                        "question" -> "提问帖"
                        else -> "提问帖评论"
                    }
                    val sequence = position + 1
                    val bbsId = entity.bbs.id
                    val bbsType = if (entity.bbs.type == "official_bbs") "综合论坛" else "游戏论坛"
                    val tabInfo = "${path}tab"
                    val commentType = when (entity.type) {
                        "community_article" -> "帖子评论"
                        "video" -> "视频帖评论"
                        else -> "提问帖评论"
                    }
                    NewLogUtils.logForumDetailFeedContentClick(
                        "click_forum_detail_comment",
                        userId,
                        contentId,
                        contentType,
                        sequence,
                        bbsId,
                        bbsType,
                        tabInfo,
                        commentType
                    )
                }
            }
            when (entity.type) {
                "community_article" -> {
                    val communityId = entity.bbs.id
                    val intent = ArticleDetailActivity.getCommentIntent(
                        itemView.context,
                        CommunityEntity(communityId, entity.communityName ?: ""),
                        entity.id ?: "",
                        entrance, ""
                    )
                    itemView.context.startActivity(intent)
                    MtaHelper.onEvent(getEventId(entrance), getKey(entrance), "评论图标")
                }
                "video" -> {
                    val communityId = entity.bbs.id
                    itemView.context.startActivity(
                        ForumVideoDetailActivity.getIntent(
                            itemView.context, entity.id
                                ?: "", communityId, true
                        )
                    )
                }
                "question" -> {
                    if (entity.questions.answerCount == 0) {
                        MtaHelper.onEvent(getEventId(entrance), getKey(entrance), "我来回答")
                    }
                    itemView.context.startActivity(
                        NewQuestionDetailActivity.getCommentIntent(
                            it.context,
                            entity.questions.id,
                            entrance,
                            ""
                        )
                    )
                }
                "answer" -> {
                    itemView.context.startActivity(
                        NewQuestionDetailActivity.getCommentIntent(
                            it.context,
                            entity.questions.id,
                            entity.id ?: "",
                            entrance,
                            ""
                        )
                    )
                }
            }
        }

        voteCountContainer.setOnClickListener {
            if (filterIllegalVoteStatus(entity.active)) return@setOnClickListener

            debounceActionWithInterval(R.id.container_like, 1000) {
                CheckLoginUtils.checkLogin(itemView.context, entrance) {
                    if (entrance.contains("论坛详情") && position != null) {
                        entity.run {
                            val userId = entity.user.id ?: ""
                            val contentId = entity.id ?: ""
                            val contentType = when (entity.type) {
                                "community_article" -> "帖子"
                                "video" -> "视频帖"
                                "question" -> "提问帖"
                                else -> "提问帖评论"
                            }
                            val sequence = position + 1
                            val bbsId = entity.bbs.id
                            val bbsType = if (entity.bbs.type == "official_bbs") "综合论坛" else "游戏论坛"
                            val tabInfo = "${path}tab"
                            NewLogUtils.logForumDetailFeedContentClick(
                                "click_forum_detail_like",
                                userId,
                                contentId,
                                contentType,
                                sequence,
                                bbsId,
                                bbsType,
                                tabInfo
                            )
                        }
                    }

                    if (entity.type != "question") {
                        MtaHelper.onEvent(getEventId(entrance), getKey(entrance), "点赞图标")
                        if (!voteIcon.isChecked) voteAnswer(entity)
                        else cancelAnswerVote(entity)
                    } else {
                        MtaHelper.onEvent(getEventId(entrance), getKey(entrance), "邀请回答")
                        val questionsDetailEntity = QuestionsDetailEntity(
                            id = entity.id,
                            title = entity.questions.title,
                            images = entity.images,
                            description = entity.questions.description
                        )
                        it.context.startActivity(
                            QuestionsInviteActivity.getIntent(
                                it.context,
                                questionsDetailEntity,
                                entrance
                            )
                        )
                    }
                }
            }
        }
    }

}