package com.img.rabbit.utils

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.text.Spannable
import android.text.SpannableString
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import android.widget.TextView
import androidx.core.graphics.toColorInt
import androidx.core.net.toUri

object AgreementTextHelper {

    fun setupAgreementTextView(fullText: String, targets: Map<String, String>, textView: TextView, isUnderlineText: Boolean = true, onAgreementClick: (String) -> Unit) {
        val spannableString = SpannableString(fullText)

        // 设置各个协议的点击区域
        targets.forEach { (targetKey, target) ->
            setClickableSpan(spannable = spannableString, target = target, isUnderlineText = isUnderlineText, color = "#FF767676".toColorInt()) {
                onAgreementClick(targetKey)
            }
        }

        textView.text = spannableString
        textView.movementMethod = LinkMovementMethod.getInstance()
        textView.highlightColor = Color.TRANSPARENT

        // 设置长按不显示复制菜单
        textView.setOnLongClickListener { true }
    }

    private fun setClickableSpan(
        spannable: Spannable,
        target: String,
        isUnderlineText: Boolean,
        color: Int,
        onClick: () -> Unit
    ) {
        val start = spannable.indexOf(target)
        if (start >= 0) {
            val end = start + target.length
            val clickableSpan = object : ClickableSpan() {
                override fun onClick(widget: View) {
                    onClick()
                }

                override fun updateDrawState(ds: TextPaint) {
                    super.updateDrawState(ds)
                    ds.color = color
                    ds.isUnderlineText = isUnderlineText
                    ds.typeface = Typeface.DEFAULT_BOLD
                }
            }
            spannable.setSpan(clickableSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        }
    }
}