package com.gh.gamecenter.qa.article.detail

import android.annotation.SuppressLint
import android.app.Activity
import android.graphics.Bitmap
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.view.Gravity
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebView
import android.widget.ImageView
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.editor.OnLinkClickListener
import com.gh.gamecenter.qa.entity.ArticleDetailEntity
import splitties.views.dsl.core.add
import splitties.views.dsl.core.lParams
import splitties.views.dsl.core.wrapContent
import java.util.*

class ArticleDetailContentViewHolder(
    var binding: ItemArticleDetailContentBinding,
    var viewModel: ArticleDetailViewModel
) : RecyclerView.ViewHolder(binding.root) {

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

    @SuppressLint("AddJavascriptInterface")
    fun bindView(article: ArticleDetailEntity) {
        binding.run {
            root.setBackgroundColor(R.color.background_white.toColor(binding.root.context))
            divider.setBackgroundColor(R.color.divider.toColor(binding.root.context))
            forumContainer.background = R.drawable.bg_shape_f5_radius_6.toDrawable(binding.root.context)
            userNameTv.setTextColor(R.color.text_title.toColor(binding.root.context))
            badgeTv.setTextColor(R.color.text_subtitleDesc.toColor(binding.root.context))
            lastEditTimeTv.setTextColor(R.color.text_subtitleDesc.toColor(binding.root.context))
            followBtn.setTextColor(R.color.theme_font.toColor(binding.root.context))
            approvalStatusTv.setTextColor(R.color.theme_green.toColor(binding.root.context))
            titleTv.setTextColor(R.color.text_title.toColor(binding.root.context))
            gameName.setTextColor(R.color.text_subtitleDesc.toColor(binding.root.context))

            richEditor.enableForceDark(DarkModeUtils.isDarkModeOn(binding.root.context))
            richEditor.setTransparentBackground()
            richEditor.setInputEnabled(false)
            richEditor.setPadding(16, 4, 16, 4)
            richEditor.addJavascriptInterface(JsInterface(article.status ?: ""), "imagelistener")
            richEditor.addJavascriptInterface(
                OnLinkClickListener(
                    root.context,
                    article.title,
                    article.status ?: "",
                    mEntrance,
                    "帖子详情"
                ), "OnLinkClickListener"
            )
            richEditor.setLayoutCallback(object : EmptyCallback {
                override fun onCallback() {
                    viewModel.articleRenderedLiveData.postValue(true)
                }
            })
            richEditor.setPageFinishedListener {
                viewModel.articlePageFinishedLiveData.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(article.status == "pass")
            statusContainer.visibleIf(article.status != "pass")
            when (article.status) {
                "pending" -> {
                    approvalStatusTv.text = "内容审核中"
                    approvalStatusTv.setTextColor(R.color.theme_green.toColor(approvalStatusTv.context))
                    approvalStatusTv.background =
                        R.drawable.bg_approval_status_pending.toDrawable(approvalStatusTv.context)
                }
                "fail" -> {
                    approvalStatusTv.text = "审核不通过"
                    approvalStatusTv.setTextColor(R.color.theme_red.toColor(approvalStatusTv.context))
                    approvalStatusTv.background =
                        R.drawable.bg_approval_status_fail.toDrawable(approvalStatusTv.context)
                }
            }
            if (article.status != "pass") {
                (statusContainer.layoutParams as LinearLayout.LayoutParams).apply {
                    topMargin = 7f.dip2px()
                    statusContainer.layoutParams = this
                }
            }

            val bbsType = if (article.type == "game_bbs") "游戏论坛" else "综合论坛"
            followBtn.setOnClickListener {
                MtaHelper.onEvent("帖子详情", "内容区域", "关注")
                NewLogUtils.logArticleDetailClick(
                    "click_article_detail_follow", article.user.id
                        ?: "", "帖子", article.community.id, bbsType
                )
                root.context.ifLogin("帖子详情-[关注]用户") {
                    if (followBtn.text == "关注") {
                        viewModel.follow()
                    } else {
                        DialogHelper.showDialog(
                            root.context,
                            "取消关注",
                            "确定要取消关注 ${article.user.name} 吗？",
                            "确定取消",
                            "暂不取消",
                            { viewModel.unfollow() },
                            extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                        )
                    }
                }
            }
            userNameTv.setOnClickListener {
                MtaHelper.onEvent("帖子详情", "内容区域", "用户名字")
                NewLogUtils.logArticleDetailClick(
                    "click_article_detail_nickname", article.user.id
                        ?: "", "帖子", article.community.id, bbsType
                )
                DirectUtils.directToHomeActivity(
                    root.context,
                    article.user.id,
                    1,
                    mEntrance,
                    "帖子详情"
                )
            }
            userIconIv.setOnClickListener {
                MtaHelper.onEvent("帖子详情", "内容区域", "用户头像")
                NewLogUtils.logArticleDetailClick(
                    "click_article_detail_profile_photo", article.user.id
                        ?: "", "帖子", article.community.id, bbsType
                )
                DirectUtils.directToHomeActivity(
                    root.context,
                    article.user.id,
                    1,
                    mEntrance,
                    "帖子详情"
                )
            }
            titleTv.text = if (article.getSimplifyChoicenessStatus() == "pass" || article.original == "yes") {
                SpannableStringBuilder(" ${article.title}").apply {
                    getLabelBitmap(article)?.let {
                        setSpan(
                            CenterImageSpan(
                                binding.root.context,
                                it
                            ), 0, 1, Spanned.SPAN_EXCLUSIVE_INCLUSIVE
                        )
                    }
                }
            } else {
                article.title
            }
            userNameTv.text = article.user.name
            userIconIv.display(article.user.border, article.user.icon, article.user.auth?.icon)
            richEditor.setContentOwner(article.me.isContentOwner)
            // 避免列表频繁刷新
            if (richEditor.currentContent != article.content) {
                richEditor.setHtml(article.content, true)
            }

            regionTv.goneIf(article.source?.region.isNullOrEmpty())
            regionTv.text = article.source?.region
            lastEditTimeTv.text = NewsUtils.getFormattedTime(article.time.edit)
            lastEditTimeTv.setDrawableEnd(
                if (article.time.create != article.time.edit) AppCompatResources.getDrawable(
                    lastEditTimeTv.context,
                    R.drawable.icon_revise
                ) else null
            )
            lastEditTimeTv.setOnClickListener {
                if (lastEditTimeTv.context is AppCompatActivity && article.time.editHistory.isNotEmpty()) {
                    val timeList = ArrayList(article.time.editHistory)
                    // 需加上首次发布时间
                    if (article.time.create != 0L) {
                        timeList.add(article.time.create)
                    }
                    EditHistoryDialog.show(lastEditTimeTv.context as AppCompatActivity, timeList)
                }
            }

            richEditor.visibility = View.VISIBLE
            article.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_article_detail_forum",
                        entity.id,
                        bbsType
                    )
                }
            }

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

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

            badgeIv.goneIf(article.user.badge == null)
//            badgeTv.goneIf(article.user.badge == null)
            badgeTv.text = article.user.badge?.name
            ImageUtils.display(badgeIv, article.user.badge?.icon)
            badgeIv.setOnClickListener {
                DialogUtils.showViewBadgeDialog(root.context, article.user.badge, object : ConfirmListener {
                    override fun onConfirm() {
                        MtaHelper.onEvent(
                            "进入徽章墙_用户记录",
                            "帖子详情",
                            "${article.user.name}（${article.user.id}）"
                        )
                        MtaHelper.onEvent("徽章中心", "进入徽章中心", "帖子详情")
                        DirectUtils.directToBadgeWall(
                            root.context,
                            viewModel.detailEntity?.user?.id,
                            article.user.name,
                            article.user.icon
                        )
                    }
                })
            }
            badgeTv.setOnClickListener { badgeIv.performClick() }

        }
    }

    private fun getLabelBitmap(article: ArticleDetailEntity): Bitmap? {
        val context = binding.root.context
        return LinearLayout(binding.root.context).apply {
            setVerticalGravity(Gravity.CENTER)
            if (article.getSimplifyChoicenessStatus() == "pass") {
                add(ImageView(context).apply {
                    setImageResource(R.drawable.ic_essence)
                }, lParams(wrapContent, wrapContent) {
                    setMargins(0, 0, 4F.dip2px(), 0)
                })
            }
            if (article.original == "yes") {
                add(ImageView(context).apply {
                    setImageResource(R.drawable.label_original)
                }, lParams(wrapContent, wrapContent) {
                    setMargins(0, 0, 8F.dip2px(), 0)
                })
            }
        }.convertViewToBitmap()
    }

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

    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)
            }
        }
    }


    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 = articleImgUrlList.size
                        while (i < size) {
                            if (url.contains(articleImgUrlList.get(i))) {
                                current = i
                            }
                            i++
                        }
                        val intent = ImageViewerActivity.getIntent(
                            binding.root.context, articleImgUrlList, 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 (!articleImgUrlList.contains(defUrl) && !url.contains("web_load_dfimg_icon.png")) {
                articleImgUrlList.add(defUrl)
            }
        }
    }
}