package com.gh.gamecenter.qa.questions.newdetail

import android.annotation.SuppressLint
import android.app.Activity
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebView
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.DefaultUrlHandler
import com.gh.common.util.*
import com.gh.common.util.LogUtils
import com.gh.common.util.NewLogUtils
import com.gh.common.view.RichEditor
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.runOnUiThread
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.databinding.ItemArticleDetailContentBinding
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.qa.article.detail.EditHistoryDialog
import com.gh.gamecenter.qa.editor.OnLinkClickListener
import com.gh.gamecenter.qa.entity.QuestionsDetailEntity
import java.util.*

class QuestionDetailContentViewHolder(
    var binding: ItemArticleDetailContentBinding,
    var viewModel: NewQuestionDetailViewModel
) : RecyclerView.ViewHolder(binding.root) {

    private var mEntrance = ""
    val questionImgUrlList = ArrayList<String>()

    @SuppressLint("AddJavascriptInterface")
    fun bindView(question: QuestionsDetailEntity) {
        binding.run {
            richEditor.setInputEnabled(false)
            richEditor.enableForceDark(DarkModeUtils.isDarkModeOn(binding.root.context))
            richEditor.setTransparentBackground()
            richEditor.setPadding(16, 4, 16, 4)
            richEditor.addJavascriptInterface(JsInterface(question.status), "imagelistener")
            richEditor.addJavascriptInterface(
                OnLinkClickListener(
                    root.context, question.title
                        ?: "", question.status, mEntrance, "问题详情"
                ), "OnLinkClickListener"
            )
            richEditor.setLayoutCallback(object : EmptyCallback {
                override fun onCallback() {
                    viewModel.questionRenderedLiveData.postValue(true)
                }
            })
            richEditor.setPageFinishedListener {
                viewModel.questionPageFinishedLiveData.postValue(true)
            }
            richEditor.setChromeClientListener(object : RichEditor.WebChromeClientListener {
                override fun onPageFinished(view: WebView?, url: String?) {

                }

                override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                    return DefaultUrlHandler.interceptUrl(binding.root.context, url ?: "", "问题详情")
                }
            })
            approvalStatusTv.goneIf(question.status == "pass")
            statusContainer.visibleIf(question.status != "pass")
            when (question.status) {
                "pending" -> {
                    approvalStatusTv.text = "内容审核中"
                    approvalStatusTv.setTextColor(R.color.theme_green.toColor(approvalStatusTv.context))
                    approvalStatusTv.background = R.drawable.bg_approval_status_pending.toDrawable()
                }
                "fail" -> {
                    approvalStatusTv.text = "审核不通过"
                    approvalStatusTv.setTextColor(R.color.theme_red.toColor(approvalStatusTv.context))
                    approvalStatusTv.background = R.drawable.bg_approval_status_fail.toDrawable()
                }
            }
            if (question.status != "pass") {
                (statusContainer.layoutParams as LinearLayout.LayoutParams).apply {
                    topMargin = 7f.dip2px()
                    statusContainer.layoutParams = this
                }
            }

            val bbsType = if (question.type == "game_bbs") "游戏论坛" else "综合论坛"
            followBtn.setOnClickListener {
                root.context.ifLogin("问题详情-[关注]用户") {
                    if (followBtn.text == "关注") {
                        viewModel.follow()
                    } else {
                        DialogHelper.showDialog(
                            root.context,
                            "取消关注",
                            "确定要取消关注 ${question.user.name} 吗？",
                            "确定取消",
                            "暂不取消",
                            { viewModel.unFollow() },
                            extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                        )
                    }
                    NewLogUtils.logQuestionDetailClick(
                        "click_question_detail_follow", question.user.id
                            ?: "", "提问帖", question.community.id, bbsType
                    )
                }
            }

            userNameTv.setOnClickListener {
                DirectUtils.directToHomeActivity(
                    root.context,
                    question.user.id,
                    1,
                    mEntrance,
                    "问题详情"
                )
                NewLogUtils.logQuestionDetailClick(
                    "click_question_detail_nickname", question.user.id
                        ?: "", "提问帖", question.community.id, bbsType
                )
            }
            userIconIv.setOnClickListener {
                DirectUtils.directToHomeActivity(
                    root.context,
                    question.user.id,
                    1,
                    mEntrance,
                    "问题详情"
                )
                NewLogUtils.logQuestionDetailClick(
                    "click_question_detail_profile_photo", question.user.id
                        ?: "", "提问帖", question.community.id, bbsType
                )
            }
            titleTv.text = SpannableStringBuilder("  ${question.title}").apply {
                setSpan(
                    CenterImageSpan(
                        binding.root.context,
                        if (question.finish) R.drawable.ic_ask_solved_label else R.drawable.ic_ask_unsolved_label
                    ), 0, 1, Spanned.SPAN_EXCLUSIVE_INCLUSIVE
                )
            }
            userNameTv.text = question.user.name
            userIconIv.display(question.user.border, question.user.icon, question.user.auth?.icon)
            richEditor.setContentOwner(question.me.isContentOwner)
            // 避免列表频繁刷新
            if (richEditor.currentContent != question.description) {
                richEditor.setHtml(question.description, true)
            }

            regionTv.goneIf(question.source?.region.isNullOrEmpty())
            regionTv.text = question.source?.region
            lastEditTimeTv.text = NewsUtils.getFormattedTime(question.time.edit)
            lastEditTimeTv.setDrawableEnd(
                if (question.time.create != question.time.edit) AppCompatResources.getDrawable(
                    lastEditTimeTv.context,
                    R.drawable.icon_revise
                ) else null
            )
            lastEditTimeTv.setOnClickListener {
                if (lastEditTimeTv.context is AppCompatActivity && question.time.editHistory.isNotEmpty()) {
                    EditHistoryDialog.show(lastEditTimeTv.context as AppCompatActivity, question.time.editHistory)
                }
            }

            richEditor.visibility = View.VISIBLE
            question.community.let { entity ->
                gameName.text = entity.name
                val icon = if (!entity.icon.isNullOrEmpty()) entity.icon else entity.game?.getIcon()
                val iconSubscript =
                    if (!entity.iconSubscript.isNullOrEmpty()) entity.iconSubscript else entity.game?.iconSubscript
                forumIconView.displayGameIcon(icon, iconSubscript, entity.game?.iconFloat)
                forumContainer.setOnClickListener {
                    DirectUtils.directForumDetail(forumContainer.context, entity.id, "问题详情")
                    LogUtils.uploadAccessToBbs(entity.id, "文章内所属论坛")
                    NewLogUtils.logArticleOrQuestionDetailForumClick(
                        "提问帖详情",
                        "click_question_detail_forum",
                        entity.id,
                        bbsType
                    )
                }
            }

            followBtn.visibility = View.VISIBLE
            if (question.user.id == UserManager.getInstance().userId) {
                followBtn.visibility = View.GONE
            } else {
                followBtn.isEnabled = true
                updateFollowBtn(question.me.isFollower)
            }

            tagContainer.isVisible = question.sections.isNotEmpty() || question.activityTag != null
            if (question.sections.isNotEmpty() && question.sections[0].id.isNotEmpty() && question.sections[0].name.isNotEmpty()) {
                sectionNameTv.text = question.sections[0].name
                sectionNameTv.visibility = View.VISIBLE
                sectionNameTv.setOnClickListener {
                    DirectUtils.directForumDetailSection(
                        binding.root.context,
                        question.community.id,
                        question.sections[0].id,
                        mEntrance
                    )
                }
            } else {
                sectionNameTv.visibility = View.GONE
            }
            if (question.activityTag != null) {
                activityNameTv.text = question.activityTag.name
                activityNameTv.visibility = View.VISIBLE
                activityNameTv.setOnClickListener {
                    question.activityTag.link?.let {
                        DirectUtils.directToLinkPage(binding.root.context, it, mEntrance, "话题标签")
                    }
                }
            } else {
                activityNameTv.visibility = View.GONE
            }

            badgeIv.goneIf(question.user.badge == null)
//            badgeTv.goneIf(question.user.badge == null)
            badgeTv.text = question.user.badge?.name
            ImageUtils.display(badgeIv, question.user.badge?.icon)
            badgeIv.setOnClickListener {
                DialogUtils.showViewBadgeDialog(root.context, question.user.badge, object : ConfirmListener {
                    override fun onConfirm() {
                        DirectUtils.directToBadgeWall(
                            root.context,
                            question.user.id,
                            question.user.name,
                            question.user.icon
                        )
                    }
                })
            }
            badgeTv.setOnClickListener { badgeIv.performClick() }
        }
    }

    fun updateFollowBtn(isFollowed: Boolean) {
        binding.run {
            if (isFollowed) {
                if (followBtn.visibility == View.GONE) return
                followBtn.text = "已关注"
                followBtn.background = null
                followBtn.setTextColor(ContextCompat.getColor(root.context, R.color.text_subtitleDesc))
            } else {
                followBtn.setRoundedColorBackground(R.color.text_EEF5FB, 14F)
                followBtn.setTextColor(ContextCompat.getColor(root.context, R.color.theme_font))
                followBtn.setText(R.string.concern)
            }
        }
    }

    /**
     * 回调列表视频播放结束时的时间
     */
    fun onVideoPlayedCallback(url: String, position: Int) {
        binding.richEditor.onVideoPlayedCallback(url, position)
    }

    inner class JsInterface(val status: String) {
        @JavascriptInterface
        fun imageClick(url: String) {
            when {
                url.contains("web_load_dfimg_icon.png") -> {
                    runOnUiThread { binding.richEditor.replaceAllDfImageExcludeGif() }
                }
//                url.contains(RichEditor.IMAGE_FLAG_THUMBNAIL) -> {
//                    runOnUiThread { binding.richEditor.replaceDfImageByUrl(url) }
//                }
                else -> {
                    clickToastByStatus(status) {
                        var current = 0
                        var i = 0
                        val size = questionImgUrlList.size
                        while (i < size) {
                            if (url.contains(questionImgUrlList.get(i))) {
                                current = i
                            }
                            i++
                        }
                        val intent = ImageViewerActivity.getIntent(
                            binding.root.context, questionImgUrlList, current,
                            mEntrance + "+(问题详情[" + binding.titleTv.text.toString() + "])"
                        )
                        (binding.root.context as Activity).startActivityForResult(
                            intent,
                            ImageViewerActivity.REQUEST_FOR_VIEWED_IMAGE
                        )
                    }
                }
            }
        }

        @JavascriptInterface
        fun imageArr(url: String) {
            val defUrl = url.split("\\?".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0]
            if (!questionImgUrlList.contains(defUrl) && !url.contains("web_load_dfimg_icon.png")) {
                questionImgUrlList.add(defUrl)
            }
        }
    }
}