package com.gh.gamecenter.qa.answer

import android.annotation.SuppressLint
import android.view.View
import android.widget.TextView
import com.airbnb.lottie.LottieAnimationView
import com.gh.common.util.*
import com.gh.gamecenter.feature.view.GameIconView
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.entity.CommunityEntity
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.common.utils.debounceActionWithInterval
import com.gh.gamecenter.common.utils.doOnAnimationEnd
import com.gh.gamecenter.common.utils.setDrawableStart
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.entity.VoteEntity
import com.gh.gamecenter.forum.detail.ForumDetailActivity
import com.gh.gamecenter.qa.article.detail.ArticleDetailActivity
import com.gh.gamecenter.qa.comment.CommentActivity
import com.gh.gamecenter.feature.entity.AnswerEntity
import com.gh.gamecenter.feature.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.gh.gamecenter.retrofit.RetrofitManager
import com.lightgame.utils.Utils
import com.lightgame.view.CheckableImageView
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody
import retrofit2.HttpException

/**
 * 主要实现文章/回答的点赞和评论操作
 */
open class BaseAnswerOrArticleItemViewHolder(itemView: View) : BaseRecyclerViewHolder<Any>(itemView) {

    val commentAndVoteContainer: View = itemView.findViewById(R.id.include_vote_and_comment)
    val inviteAnswer: View = itemView.findViewById(R.id.inviteAnswer)
    val voteIcon: CheckableImageView = itemView.findViewById(R.id.vote_icon)
    val voteCount: TextView = itemView.findViewById(R.id.vote_count)
    val commentCount: TextView = itemView.findViewById(R.id.comment_count)
    val voteAnimation: LottieAnimationView = itemView.findViewById(R.id.vote_animation)
    val voteCountContainer: View = itemView.findViewById(R.id.vote_count_container)
    val forumNameTv: View = itemView.findViewById(R.id.forumNameTv)
    val forumNameLl: View? = itemView.findViewById(R.id.forumNameLl)
    val forumNameContainer: View? = itemView.findViewById(R.id.forumNameContainer)
    val forumIcon: GameIconView? = itemView.findViewById(R.id.forumIcon)


    open fun bindCommendAndVote(entity: AnswerEntity, entrance: String, path: String? = null, position: Int? = null) {
        binNormalView(entity)

        commentCount.setOnClickListener {
            if (filterIllegalCommentStatus(entity.commentable, entity.active)) return@setOnClickListener
            when (entity.type) {
                "community_article" -> {
                    val communityId = if (!entity.communityId.isNullOrEmpty()) entity.communityId
                        ?: "" else entity.bbs.id
                    val intent = ArticleDetailActivity.getCommentIntent(
                        itemView.context,
                        CommunityEntity(communityId, entity.communityName ?: ""),
                        entity.id ?: "", entrance, ""
                    )
                    itemView.context.startActivity(intent)
                }
                "video" -> {
                    val communityId = if (!entity.communityId.isNullOrEmpty()) entity.communityId
                        ?: "" else entity.bbs.id
                    itemView.context.startActivity(
                        ForumVideoDetailActivity.getIntent(
                            itemView.context, entity.id
                                ?: "", communityId, true
                        )
                    )
                }
                "answer" -> {
                    val intent = CommentActivity.getAnswerCommentIntent(
                        itemView.context,
                        entity.id ?: "",
                        entity.count.comment,
                        false
                    )
                    itemView.context.startActivity(intent)
                }
                else -> {
                    val intent = NewQuestionDetailActivity.getCommentIntent(
                        itemView.context, entity.id
                            ?: "", entrance, ""
                    )
                    itemView.context.startActivity(intent)
                }
            }

        }

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

            debounceActionWithInterval(R.id.container_like, 1000) {
                CheckLoginUtils.checkLogin(itemView.context, "${entrance}-点赞") {
                    if (!voteIcon.isChecked) voteAnswer(entity)
                    else cancelAnswerVote(entity)
                }
            }
        }
    }

    fun getEventId(entrance: String): String {
        return when (entrance) {
            "论坛首页+(关注)", "论坛首页+(推荐)" -> "论坛首页"
            "论坛详情+(全部)", "论坛详情+(精华)", "论坛详情+(问答)" -> "论坛详情"
            else -> entrance
        }
    }

    fun getKey(entrance: String): String {
        return when (entrance) {
            "论坛首页+(关注)" -> "关注Tab"
            "论坛首页+(推荐)" -> "推荐Tab"
            "论坛详情+(全部)" -> "全部Tab"
            "论坛详情+(精华)" -> "精华Tab"
            "论坛详情+(问答)" -> "问答Tab"
            else -> entrance
        }
    }

    open fun bindCommendAndVote(entity: ArticleEntity, entrance: String, position: Int? = null) {
        binNormalView(entity.transformAnswerEntity())

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

        val contentType = when (entity.type) {
            "community_article" -> "帖子"
            "video" -> "视频帖"
            "question" -> "提问帖"
            else -> "提问帖评论"
        }
        val bbsType = if (entity.bbs.type == "official_bbs") "综合论坛" else "游戏论坛"

        forumNameTv.setOnClickListener {
            if (entrance == "社区+(推荐)") {
                NewLogUtils.logRecommendFeedForumClick(contentType, entity.id, entity.bbs.id, bbsType)
            }

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

        forumNameContainer?.setOnClickListener {
            forumNameTv.performClick()
        }

        inviteAnswer.setOnClickListener {
            CheckLoginUtils.checkLogin(itemView.context, entrance) {
                val questionsDetailEntity = QuestionsDetailEntity(
                    id = entity.id,
                    title = entity.title,
                    images = entity.images,
                    description = entity.brief
                )
                it.context.startActivity(
                    QuestionsInviteActivity.getIntent(
                        it.context,
                        questionsDetailEntity,
                        entrance
                    )
                )
            }
        }

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

            if (entrance == "社区+(推荐)" && position != null) {
                entity.run {
                    val commentType = when (entity.type) {
                        "community_article" -> "帖子评论"
                        "video" -> "视频帖评论"
                        else -> "提问帖评论"
                    }
                    NewLogUtils.logRecommendFeedContentClick(
                        "click_for_you_comment",
                        contentType,
                        id,
                        (position + 1),
                        bbs.id,
                        bbsType,
                        user.id ?: "",
                        commentType
                    )
                }
            }

            when (entity.type) {
                "question" -> {
                    val intent = NewQuestionDetailActivity.getCommentIntent(it.context, entity.id, entrance, "")
                    itemView.context.startActivity(intent)
                }
                "answer" -> {
                    val intent = NewQuestionDetailActivity.getCommentIntent(
                        it.context,
                        entity.questions.id,
                        entity.id,
                        entrance,
                        ""
                    )
                    itemView.context.startActivity(intent)
                }
                "video" -> {
                    itemView.context.startActivity(
                        ForumVideoDetailActivity.getIntent(
                            itemView.context,
                            entity.id,
                            entity.community.id,
                            true
                        )
                    )
                }
                else -> {
                    val communityId = entity.community.id
                    val intent = ArticleDetailActivity.getCommentIntent(
                        itemView.context,
                        CommunityEntity(communityId, entity.community.name),
                        entity.id,
                        entrance, ""
                    )
                    itemView.context.startActivity(intent)
                    MtaHelper.onEvent(getEventId(entrance), getKey(entrance), "评论图标")
                }
            }
        }

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

            debounceActionWithInterval(R.id.container_like, 1000) {
                CheckLoginUtils.checkLogin(itemView.context, "${entrance}-点赞") {
                    if (entrance == "社区+(推荐)" && position != null) {
                        entity.run {
                            NewLogUtils.logRecommendFeedContentClick(
                                "click_for_you_like",
                                contentType,
                                id,
                                position + 1,
                                bbs.id,
                                bbsType,
                                user.id ?: ""
                            )
                        }
                    }

                    if (entity.type != "question") {
                        if (!voteIcon.isChecked) voteAnswer(entity.transformAnswerEntity())
                        else cancelAnswerVote(entity.transformAnswerEntity())
                        MtaHelper.onEvent(getEventId(entrance), getKey(entrance), "点赞图标")
                    }
                }
            }
        }
    }

    fun binNormalView(entity: AnswerEntity) {
        setVoteAndCommentStyle(entity)
        inviteAnswer.visibility = View.GONE
        voteCountContainer.visibility = View.VISIBLE
        when (entity.type) {
            "question" -> {
                inviteAnswer.visibility = View.VISIBLE
                voteCountContainer.visibility = View.GONE
                commentCount.text = if (entity.count.answer > 0) entity.count.answer.toString() else "回答"
            }
            "answer" -> {
                commentCount.text = if (entity.count.reply > 0) entity.count.reply.toString() else "评论"
                voteCount.text = if (entity.count.vote > 0) entity.count.vote.toString() else "赞同"
            }
            else -> {
                commentCount.text = if (entity.count.comment > 0) entity.count.comment.toString() else "评论"
                voteCount.text = if (entity.count.vote > 0) entity.count.vote.toString() else "赞同"
            }
        }
    }

    private fun setVoteAndCommentStyle(entity: AnswerEntity) {
        if (entity.type != "question") {
            if (!entity.active) {
                voteIcon.setImageResource(R.drawable.community_vote_unavailable)
                voteCount.setTextColor(R.color.text_body.toColor(voteCount.context))
            } else if (entity.me.isCommunityArticleVote || entity.me.isAnswerVoted || entity.me.isVoted) {
                voteIcon.setImageResource(R.drawable.community_vote_selector)
                voteIcon.isChecked = true
                voteCount.setTextColor(R.color.theme_font.toColor(voteCount.context))
            } else {
                voteIcon.setImageResource(R.drawable.community_vote_selector)
                voteIcon.isChecked = false
                voteCount.setTextColor(R.color.text_subtitleDesc.toColor(voteCount.context))
            }
        }

        if (entity.commentable && entity.active) {
            commentCount.setDrawableStart(R.drawable.community_comment_count)
            commentCount.setTextColor(R.color.text_subtitleDesc.toColor(commentCount.context))
        } else {
            commentCount.setDrawableStart(R.drawable.community_comment_count_unavailable)
            commentCount.setTextColor(R.color.text_body.toColor(commentCount.context))
        }
    }

    @SuppressLint("CheckResult")
    fun voteAnswer(entity: AnswerEntity) {
        if (entity.status == "pending") {
            ToastUtils.showToast("内容审核中")
            return
        }
        if (entity.type == "video") {
            RetrofitManager.getInstance()
                .api.voteVideo(entity.id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : BiResponse<ResponseBody>() {
                    override fun onSuccess(data: ResponseBody) {
                        entity.count.vote = entity.count.vote + 1
                        entity.me.isVoted = true
                        voteCount.text = if (entity.count.vote > 0) entity.count.vote.toString() else "赞同"
                        setVoteAndCommentStyle(entity)
                    }

                    override fun onFailure(exception: Exception) {
                        super.onFailure(exception)
                        if (exception is HttpException) {
                            ErrorHelper.handleError(
                                itemView.context,
                                exception.response()?.errorBody()?.string()
                            )
                        }
                        setVoteAndCommentStyle(entity)
                    }
                })
        } else {
            val voteObservable = if (entity.type == "community_article") {
                RetrofitManager.getInstance().api.postCommunityArticleVote(entity.id)
            } else {
                RetrofitManager.getInstance().api
                    .postVoteQuestionComment(entity.questions.id, entity.id)
                    .map { GsonUtils.fromJson(it.string(), VoteEntity::class.java) }
            }
            voteObservable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Response<VoteEntity>() {
                    override fun onResponse(response: VoteEntity?) {
                        if (entity.type == "community_article") {
                            entity.me.isCommunityArticleVote = true
                        } else {
                            entity.me.isAnswerVoted = true
                        }
                        ToastUtils.showToast("已赞同")
                        entity.count.vote = entity.count.vote + 1
                        voteCount.text = if (entity.count.vote > 0) entity.count.vote.toString() else "赞同"
                        setVoteAndCommentStyle(entity)
                    }

                    override fun onFailure(e: HttpException?) {
                        ErrorHelper.handleErrorWithCustomizedHandler(
                            itemView.context,
                            e?.response()?.errorBody()?.string(),
                            false
                        ) {
                            when (it) {
                                403008 -> {
                                    Utils.toast(itemView.context, R.string.ask_vote_hint)
                                    true
                                }
                                403036 -> {
                                    Utils.toast(itemView.context, R.string.ask_vote_limit_hint)
                                    true
                                }
                                404001 -> {
                                    Utils.toast(itemView.context, "内容可能已被删除")
                                    entity.active = false
                                    setVoteAndCommentStyle(entity)
                                    true
                                }
                                else -> {
                                    setVoteAndCommentStyle(entity)
                                    false
                                }
                            }
                        }
                    }
                })
        }
        playVoteAnimation()
    }

    @SuppressLint("CheckResult")
    fun cancelAnswerVote(entity: AnswerEntity) {
        if (entity.type == "video") {
            RetrofitManager.getInstance()
                .api.undoVoteVideo(entity.id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : BiResponse<ResponseBody>() {
                    override fun onSuccess(data: ResponseBody) {
                        entity.count.vote = entity.count.vote - 1
                        entity.me.isVoted = false
                        voteCount.text = if (entity.count.vote > 0) entity.count.vote.toString() else "赞同"
                        setVoteAndCommentStyle(entity)
                        Utils.toast(itemView.context, "取消点赞")
                    }

                    override fun onFailure(exception: Exception) {
                        super.onFailure(exception)
                        if (exception is HttpException) {
                            ErrorHelper.handleError(
                                itemView.context,
                                exception.response()?.errorBody()?.string()
                            )
                        }
                        setVoteAndCommentStyle(entity)
                    }
                })
        } else {
            val unVoteObservable = if (entity.type == "community_article") {
                RetrofitManager.getInstance().api.postCommunityArticleUnVote(entity.id)
            } else {
                RetrofitManager.getInstance().api
                    .postAnswerUnvote(entity.id)
            }
            unVoteObservable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Response<VoteEntity>() {
                    override fun onResponse(response: VoteEntity?) {
                        entity.count.vote = entity.count.vote - 1
                        if (entity.type == "community_article") {
                            entity.me.isCommunityArticleVote = false
                        } else {
                            entity.me.isAnswerVoted = false
                        }
                        voteCount.text = if (entity.count.vote > 0) entity.count.vote.toString() else "赞同"
                        setVoteAndCommentStyle(entity)
                        Utils.toast(itemView.context, "取消赞同")
                    }

                    override fun onFailure(e: HttpException?) {
                        ErrorHelper.handleErrorWithCustomizedHandler(
                            itemView.context,
                            e?.response()?.errorBody()?.string(),
                            false
                        ) {
                            when (it) {
                                403008 -> {
                                    Utils.toast(itemView.context, R.string.ask_vote_hint)
                                    true
                                }
                                403036 -> {
                                    Utils.toast(itemView.context, R.string.ask_vote_limit_hint)
                                    true
                                }
                                404001 -> {
                                    Utils.toast(itemView.context, "内容可能已被删除")
                                    entity.active = false
                                    setVoteAndCommentStyle(entity)
                                    true
                                }
                                else -> {
                                    setVoteAndCommentStyle(entity)
                                    false
                                }
                            }
                        }
                    }
                })
        }
    }

    fun voteArticle(entity: ArticleEntity) {
        entity.count.vote = entity.count.vote + 1
        voteCount.text = if (entity.count.vote > 0) entity.count.vote.toString() else "赞同"
        playVoteAnimation()

        RetrofitManager.getInstance().api
            .postCommunityArticleVote(entity.id)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<VoteEntity>() {
                override fun onResponse(response: VoteEntity?) {
                    entity.me.isCommunityArticleVote = true
                    ToastUtils.showToast("已赞同")
                }

                override fun onFailure(e: HttpException?) {
                    ErrorHelper.handleErrorWithCustomizedHandler(
                        itemView.context,
                        e?.response()?.errorBody()?.string(),
                        false
                    ) {
                        if (403008 == it) {
                            Utils.toast(itemView.context, R.string.ask_vote_hint)
                            true
                        } else if (403036 == it) {
                            Utils.toast(itemView.context, R.string.ask_vote_limit_hint)
                            true
                        } else if (404001 == it) {
                            Utils.toast(itemView.context, "内容可能已被删除")
                            entity.active = false
                            setVoteAndCommentStyle(entity.transformAnswerEntity())
                            true
                        } else {
                            entity.count.vote = entity.count.vote - 1
                            entity.me.isCommunityArticleVote = false
                            voteCount.text = if (entity.count.vote > 0) entity.count.vote.toString() else "赞同"
                            setVoteAndCommentStyle(entity.transformAnswerEntity())
                            false
                        }
                    }
                }
            })
    }

    fun cancelArticleVote(entity: ArticleEntity) {
        entity.count.vote = entity.count.vote - 1
        entity.me.isCommunityArticleVote = false
        voteIcon.isChecked = false
        voteCount.setTextColor(R.color.text_subtitleDesc.toColor(voteCount.context))
        voteCount.text = if (entity.count.vote > 0) entity.count.vote.toString() else "赞同"

        RetrofitManager.getInstance().api
            .postCommunityArticleUnVote(entity.id)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<VoteEntity>() {
                override fun onResponse(response: VoteEntity?) {
                    Utils.toast(itemView.context, "取消赞同")
                }

                override fun onFailure(e: HttpException?) {
                    ErrorHelper.handleErrorWithCustomizedHandler(
                        itemView.context,
                        e?.response()?.errorBody()?.string(),
                        false
                    ) {
                        if (403008 == it) {
                            Utils.toast(itemView.context, R.string.ask_vote_hint)
                            true
                        } else if (403036 == it) {
                            Utils.toast(itemView.context, R.string.ask_vote_limit_hint)
                            true
                        } else if (404001 == it) {
                            Utils.toast(itemView.context, "内容可能已被删除")
                            entity.active = false
                            setVoteAndCommentStyle(entity.transformAnswerEntity())
                            true
                        } else {
                            entity.count.vote = entity.count.vote + 1
                            entity.me.isCommunityArticleVote = true
                            voteCount.text = if (entity.count.vote > 0) entity.count.vote.toString() else "赞同"
                            setVoteAndCommentStyle(entity.transformAnswerEntity())
                            false
                        }
                    }
                }
            })
    }

    fun followUser(entity: AnswerEntity, callback: EmptyCallback?) {
        RetrofitManager.getInstance().api
            .postFollowing(entity.user.id)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<ResponseBody>() {
                override fun onResponse(response: ResponseBody?) {
                    super.onResponse(response)
                    callback?.onCallback()
                }

                override fun onFailure(e: HttpException?) {
                    super.onFailure(e)
                    Utils.toast(itemView.context, R.string.loading_failed_hint)
                }
            })
    }

    private fun playVoteAnimation() {
        voteCount.setTextColor(R.color.theme_font.toColor(voteCount.context))
        voteIcon.isChecked = true
        voteIcon.visibility = View.GONE
        voteAnimation.visibility = View.VISIBLE
        voteAnimation.setAnimation("lottie/community_vote.json")
        voteAnimation.playAnimation()
        voteAnimation.doOnAnimationEnd {
            voteAnimation.visibility = View.GONE
            voteIcon.visibility = View.VISIBLE
        }
    }

    fun filterIllegalCommentStatus(commentable: Boolean, active: Boolean): Boolean {
        if (!commentable) {
            Utils.toast(itemView.context, "作者已关闭评论")
            return true
        }

        if (!active) {
            Utils.toast(itemView.context, "内容可能已被删除")
            return true
        }

        return false
    }

    fun filterIllegalVoteStatus(active: Boolean): Boolean {
        if (!active) {
            Utils.toast(itemView.context, "内容可能已被删除")
            return true
        }

        return false
    }

}