package com.gh.common.util

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import com.gh.common.util.CommentUtils.copyText
import com.gh.gamecenter.CommentDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.json.json
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.common.utils.DialogHelper
import com.gh.gamecenter.common.utils.ifLogin
import com.gh.gamecenter.common.utils.showAutoOrientation
import com.gh.gamecenter.common.view.BugFixedPopupWindow
import com.gh.gamecenter.entity.CommentEntity
import com.gh.gamecenter.entity.MeEntity
import com.gh.gamecenter.entity.Permissions
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.qa.comment.OnCommentOptionClickListener
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import com.lightgame.utils.Utils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.HttpException

object CommentHelper {

    @JvmStatic
    fun showCommunityArticleCommentOptions(
        view: View,
        commentEntity: CommentEntity,
        showConversation: Boolean,
        articleId: String,
        communityId: String,
        isShowTop: Boolean = false,
        ignoreModerator: Boolean = false,
        listener: OnCommentOptionClickListener?
    ) {
        showCommentOptions(
            view = view,
            commentEntity = commentEntity,
            showConversation = showConversation,
            articleId = articleId,
            communityId = communityId,
            isShowTopOrAccept = isShowTop,
            ignoreModerator = ignoreModerator,
            listener = listener
        )
    }

    @JvmStatic
    fun showAnswerCommentOptions(
        view: View,
        commentEntity: CommentEntity,
        showConversation: Boolean,
        answerId: String,
        listener: OnCommentOptionClickListener?
    ) {
        showCommentOptions(
            view = view,
            commentEntity = commentEntity,
            showConversation = showConversation,
            answerId = answerId,
            listener = listener
        )
    }

    @JvmStatic
    fun showVideoCommentOptions(
        view: View,
        commentEntity: CommentEntity,
        showConversation: Boolean,
        videoId: String,
        isVideoAuthor: Boolean,
        isShowTop: Boolean = false,
        listener: OnCommentOptionClickListener?
    ) {
        showCommentOptions(
            view = view,
            commentEntity = commentEntity,
            showConversation = showConversation,
            videoId = videoId,
            isVideoAuthor = isVideoAuthor,
            isShowTopOrAccept = isShowTop,
            listener = listener
        )
    }

    fun showQuestionCommentOption(
        view: View,
        commentEntity: CommentEntity,
        questionId: String,
        isShowTop: Boolean = false,
        listener: OnCommentOptionClickListener?
    ) {
        showCommentOptions(
            view = view,
            commentEntity = commentEntity,
            showConversation = false,
            questionId = questionId,
            isShowTopOrAccept = isShowTop,
            ignoreModerator = true,
            listener = listener
        )
    }

    fun showGameCollectionCommentOption(
        view: View,
        commentEntity: CommentEntity,
        gameCollectionId: String,
        listener: OnCommentOptionClickListener?
    ) {
        showCommentOptions(
            view = view,
            commentEntity = commentEntity,
            gameCollectionId = gameCollectionId,
            showConversation = false,
            ignoreModerator = true,
            listener = listener
        )
    }

    private fun showCommentOptions(
        view: View,
        commentEntity: CommentEntity,
        showConversation: Boolean,
        articleId: String? = null,
        communityId: String? = null,
        answerId: String? = null,
        questionId: String? = null,
        videoId: String? = null,
        gameCollectionId: String? = null,
        isShowTopOrAccept: Boolean = false,
        ignoreModerator: Boolean = false,
        isVideoAuthor: Boolean = false,
        listener: OnCommentOptionClickListener? = null
    ) {
        val context = view.context
        val dialogOptions = ArrayList<String>()
        val isContentAuthor = commentEntity.me?.isContentAuthor == true

        if (isShowTopOrAccept && (articleId != null || questionId != null || videoId != null) && isContentAuthor) {
            dialogOptions.add(if (commentEntity.isTop) "取消置顶" else "置顶")
        }
        if (isShowTopOrAccept && questionId != null && isContentAuthor) {
            if (commentEntity.accept) {
                dialogOptions.add("取消采纳")
            } else {
                dialogOptions.add("采纳")
            }
        }

        dialogOptions.add("复制")
        if (commentEntity.user.id != UserManager.getInstance().userId) {
            dialogOptions.add("投诉")
        }
        if (questionId != null &&
            commentEntity.me?.isModerator == true &&
            (commentEntity.me?.moderatorPermissions?.highlightAnswer
                ?: Permissions.GUEST) > Permissions.GUEST && !commentEntity.choiceness
        ) {
            dialogOptions.add("加精选")
        }
        if (questionId != null &&
            commentEntity.me?.isModerator == true &&
            (commentEntity.me?.moderatorPermissions?.cancelChoicenessAnswer
                ?: Permissions.GUEST) > Permissions.GUEST &&
            commentEntity.choiceness
        ) {
            dialogOptions.add("取消精选")
        }
        if (commentEntity.user.id == UserManager.getInstance().userId || commentEntity.me?.isModerator == true || isContentAuthor) {
            dialogOptions.add("删除评论")
        }

        if (commentEntity.parentUser != null && showConversation) {
            dialogOptions.add("查看对话")
        }

        val inflater = LayoutInflater.from(context)
        val layout = inflater.inflate(R.layout.layout_popup_container, null)
        val popupWindow = BugFixedPopupWindow(
            layout,
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        val container = layout.findViewById<LinearLayout>(R.id.container)
        for (text in dialogOptions) {
            val item = inflater.inflate(R.layout.layout_popup_option_item, container, false)
            container.addView(item)

            val hitText = item.findViewById<TextView>(R.id.hint_text)
            hitText.text = text

            item.setOnClickListener {
                popupWindow.dismiss()
                listener?.onCommentOptionClick(commentEntity, text)
                when (text) {
                    "复制" -> copyText(commentEntity.content, context)

                    "投诉" -> {
                        context.ifLogin("回答详情-评论-投诉") {
                            showReportTypeDialog(context) { reportType ->
                                val commentListener =
                                    object : PostCommentUtils.PostCommentListener {
                                        override fun postSuccess(response: JSONObject?) {
                                            Utils.toast(context, "感谢您的投诉")
                                        }

                                        override fun postFailed(error: Throwable?) {
                                            if (error == null) {
                                                Utils.toast(context, "投诉失败，请稍后重试")
                                            } else {
                                                if (error is HttpException) {
                                                    ErrorHelper.handleError(
                                                        HaloApp.getInstance().application,
                                                        error.response().errorBody()?.string()
                                                    )
                                                }
                                            }
                                        }
                                    }

                                when {
                                    answerId != null -> {
                                        PostCommentUtils.postAnswerReportData(
                                            commentEntity.id,
                                            answerId,
                                            reportType,
                                            commentListener
                                        )
                                    }
                                    articleId != null -> {
                                        PostCommentUtils.reportCommunityArticleComment(
                                            commentEntity.id,
                                            reportType,
                                            commentListener
                                        )
                                    }
                                    questionId != null -> {
                                        PostCommentUtils.reportQuestionComment(
                                            questionId,
                                            commentEntity.id,
                                            reportType,
                                            commentListener
                                        )
                                    }
                                    gameCollectionId != null -> {
                                        PostCommentUtils.reportGameCollectionComment(
                                            gameCollectionId,
                                            commentEntity.id,
                                            reportType,
                                            commentListener
                                        )
                                    }
                                    else -> {
                                        PostCommentUtils.reportVideoComment(
                                            videoId,
                                            commentEntity.id,
                                            reportType,
                                            commentListener
                                        )
                                    }
                                }
                            }
                        }
                    }

                    "查看对话" -> {
                        if (answerId != null) {
                            context.startActivity(
                                CommentDetailActivity
                                    .getAnswerCommentIntent(
                                        context,
                                        commentEntity.id,
                                        answerId,
                                        null
                                    )
                            )
                        } else if (articleId != null) {
                            context.startActivity(
                                CommentDetailActivity
                                    .getCommunityArticleCommentIntent(
                                        context,
                                        articleId,
                                        commentEntity.id,
                                        communityId,
                                        null
                                    )
                            )
                        } else {
                            context.startActivity(
                                CommentDetailActivity
                                    .getVideoCommentIntent(
                                        context,
                                        commentEntity.id,
                                        videoId,
                                        isVideoAuthor,
                                        null
                                    )
                            )
                        }
                    }
                }
            }
        }
        popupWindow.isTouchable = true
        popupWindow.isFocusable = true

        popupWindow.showAutoOrientation(view)
    }

    private fun showControlDialog(
        context: Context,
        answerId: String? = null,
        articleId: String? = null,
        communityId: String? = null,
        comment: CommentEntity,
        me: MeEntity
    ) {
        val dialogOptions = arrayListOf<String>()
        val highlight = "置顶评论"
        val hide = "隐藏评论"

        var canHighlightCommentDirectly = false
        var canHideCommentDirectly = false

        if (me.isModerator || me.moderatorPermissions.topAnswerComment > Permissions.GUEST
            || me.moderatorPermissions.topCommunityArticleComment > Permissions.GUEST
        ) {
            dialogOptions.add(highlight)
            if (me.moderatorPermissions.topAnswerComment > Permissions.REPORTER
                || me.moderatorPermissions.topCommunityArticleComment > Permissions.REPORTER
            ) {
                canHighlightCommentDirectly = true
            }
        }

        if (me.isModerator || me.moderatorPermissions.hideAnswerComment > Permissions.GUEST
            || me.moderatorPermissions.hideCommunityArticleComment > Permissions.GUEST
        ) {
            dialogOptions.add(hide)
            if (me.moderatorPermissions.hideAnswerComment > Permissions.REPORTER
                || me.moderatorPermissions.hideCommunityArticleComment > Permissions.REPORTER
            ) {
                canHideCommentDirectly = true
            }
        }

        val highlightDialogHintContent = if (canHighlightCommentDirectly) {
            "你的操作将立即生效，确定提交吗？（你的管理权限为：高级）"
        } else {
            "你的操作将提交给小编审核，确定提交吗？"
        }

        val hideDialogHintContent = if (canHideCommentDirectly) {
            "你的操作将立即生效，确定提交吗？（你的管理权限为：高级）"
        } else {
            "你的操作将提交给小编审核，确定提交吗？"
        }

        val disabledOptions = arrayListOf<String>()

        if (comment.priority != 0) {
            disabledOptions.add(highlight)
        }

        comment.me?.let {
            if (it.isCommentOwner) {
                disabledOptions.add(highlight)
            }
        }

        DialogUtils.showListDialog(context, dialogOptions, disabledOptions) {
            when (it) {
                highlight -> {
                    if (comment.priority != 0) {
                        Utils.toast(context, "评论已经置顶")
                        return@showListDialog
                    }

                    comment.me?.let { me ->
                        if (me.isCommentOwner) {
                            Utils.toast(context, "不能置顶自己的评论")
                            return@showListDialog
                        }
                    }

                    val highlightObserver = object : Response<ResponseBody>() {
                        override fun onResponse(response: ResponseBody?) {
                            if (canHighlightCommentDirectly) {
                                Utils.toast(context, "置顶成功，请刷新列表")
                            } else {
                                Utils.toast(context, "提交成功")
                            }
                        }

                        override fun onFailure(e: HttpException?) {
                            super.onFailure(e)
                            e?.let { httpException ->
                                if (httpException.code() == 403) {
                                    val string = e.response().errorBody()?.string()
                                    val errorJson = JSONObject(string)
                                    val errorCode = errorJson.getInt("code")
                                    if (errorCode == 403059) {
                                        Utils.toast(
                                            HaloApp.getInstance().application,
                                            "权限错误，请刷新后重试"
                                        )
                                        return
                                    } else {
                                        Utils.toast(HaloApp.getInstance().application, e.message())
                                    }
                                }
                            }
                        }
                    }

                    if (answerId != null) {
                        DialogHelper.showDialog(
                            context, highlight, highlightDialogHintContent,
                            "确定", "取消", {
                                RetrofitManager.getInstance().api
                                    .highlightAnswerComment(answerId, comment.id)
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribeOn(Schedulers.io())
                                    .subscribe(highlightObserver)
                            },
                            extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                        )
                    } else {
                        DialogHelper.showDialog(
                            context, highlight, highlightDialogHintContent,
                            "确定", "取消", {
                                RetrofitManager.getInstance().api
                                    .highlightCommunityArticleComment(comment.id)
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribeOn(Schedulers.io())
                                    .subscribe(highlightObserver)
                            },
                            extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                        )
                    }
                }

                hide -> {
                    val hideObserver = object : Response<ResponseBody>() {
                        override fun onResponse(response: ResponseBody?) {
                            if (canHideCommentDirectly) {
                                Utils.toast(context, "隐藏成功，请刷新列表")
                            } else {
                                Utils.toast(context, "提交成功")
                            }
                        }

                        override fun onFailure(e: HttpException?) {
                            super.onFailure(e)
                            e?.let { httpException ->
                                if (httpException.code() == 403) {
                                    val string = e.response().errorBody()?.string()
                                    val errorJson = JSONObject(string)
                                    val errorCode = errorJson.getInt("code")
                                    if (errorCode == 403059) {
                                        Utils.toast(
                                            HaloApp.getInstance().application,
                                            "权限错误，请刷新后重试"
                                        )
                                        return
                                    } else {
                                        Utils.toast(HaloApp.getInstance().application, e.message())
                                    }
                                }
                            }
                        }
                    }

                    if (answerId != null) {
                        DialogHelper.showDialog(
                            context, hide, hideDialogHintContent,
                            "确定", "取消", {
                                RetrofitManager.getInstance().api
                                    .hideAnswerComment(answerId, comment.id)
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribeOn(Schedulers.io())
                                    .subscribe(hideObserver)
                            },
                            extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                        )
                    } else {
                        DialogHelper.showDialog(
                            context, hide, hideDialogHintContent,
                            "确定", "取消", {
                                RetrofitManager.getInstance().api
                                    .hideCommunityArticleComment(comment.id)
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribeOn(Schedulers.io())
                                    .subscribe(hideObserver)
                            },
                            extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                        )
                    }
                }
            }
        }
    }

    private fun showReportTypeDialog(
        context: Context,
        reportCallback: (reportType: String) -> Unit
    ) {
        DialogUtils.showReportReasonDialog(
            context,
            Constants.REPORT_LIST.toList() as ArrayList<String>
        ) { reason, desc ->
            val json = json {
                "reason" to if (reason != "其他原因") reason else desc
            }
            reportCallback.invoke(json.toString())
        }
    }

}