package com.miya.fastcashier.util

import android.content.Context
import android.text.SpannableString
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import androidx.core.content.ContextCompat
import android.text.Spanned
import android.text.style.StyleSpan
import android.graphics.Typeface
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.text.style.ClickableSpan
import android.text.TextPaint
import android.text.Html
import android.util.Log
import android.view.View
import java.lang.Exception
import java.util.regex.Pattern

object WordUtil {
    /**
     * 关键字变色
     *
     * @param context 上下文
     * @param color   变化的色值
     * @param text    文字
     * @param keyword 文字中的关键字
     * @return 结果SpannableString
     */
    fun matcherDiscolor(
        context: Context?,
        color: Int,
        text: String,
        keyword: String
    ): SpannableString {
        var text = text
        var keyword = keyword
        val s = SpannableString(text)
        keyword = escapeExprSpecialWord(keyword)
        text = escapeExprSpecialWord(text)
        if (!TextUtils.isEmpty(keyword) && text.contains(keyword)) {
            try {
                val p = Pattern.compile(keyword)
                val m = p.matcher(s)
                while (m.find()) {
                    val start = m.start()
                    val end = m.end()
                    //注意：请使用ContextCompat.getColor获取颜色值。
                    s.setSpan(
                        ForegroundColorSpan(ContextCompat.getColor(context!!, color)),
                        start,
                        end,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return s
    }

    fun matcherBold(context: Context?, text: String, keyword: String): SpannableString {
        var text = text
        var keyword = keyword
        val s = SpannableString(text)
        keyword = escapeExprSpecialWord(keyword)
        text = escapeExprSpecialWord(text)
        if (!TextUtils.isEmpty(keyword) && text.contains(keyword)) {
            try {
                val p = Pattern.compile(keyword)
                val m = p.matcher(s)
                while (m.find()) {
                    val start = m.start()
                    val end = m.end()
                    s.setSpan(
                        StyleSpan(Typeface.BOLD),
                        start,
                        end,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                    break
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return s
    }

    /**
     * 关键字高亮变色  添加点击链接并跳转
     *
     * @param context 上下文
     * @param color   变化的色值
     * @param text    文字
     * @param keyword 文字中的关键字
     */
    fun setClickableSpanAndLighted(
        context: Context,
        color: Int,
        text: String,
        keyword: String,
        intent: Intent?
    ): SpannableString {
        var text = text
        var keyword = keyword
        val s = SpannableString(text)
        keyword = escapeExprSpecialWord(keyword)
        text = escapeExprSpecialWord(text)
        if (!TextUtils.isEmpty(keyword) && text.contains(keyword)) {
            try {
                val p = Pattern.compile(keyword)
                val m = p.matcher(s)
                while (m.find()) {
                    val start = m.start()
                    val end = m.end()
                    val clickableSpan: ClickableSpan = object : ClickableSpan() {
                        override fun onClick(view: View) {
                            Log.e("setClickableSpan", "点击")
                            context.startActivity(intent)
                        }

                        //设置文字样式
                        override fun updateDrawState(ds: TextPaint) {
                            super.updateDrawState(ds)
                            ds.isUnderlineText = false
                            ds.bgColor = Color.WHITE
                            ds.color = ContextCompat.getColor(context, color)
                        }
                    }
                    s.setSpan(clickableSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return s
    }

    /**
     * 关键字高亮变色  添加点击链接并跳转
     *
     * @param context 上下文
     * @param color   变化的色值
     * @param keyword 文字中的关键字
     */
    fun setClickableSpanAndLighted(
        context: Context,
        color: Int,
        s: SpannableString?,
        keyword: String,
        intent: Intent?
    ): SpannableString? {
        var keyword = keyword
        if (s == null) {
            return null
        }
        keyword = escapeExprSpecialWord(keyword)
        if (!TextUtils.isEmpty(keyword) && s.toString().contains(keyword)) {
            try {
                val p = Pattern.compile(keyword)
                val m = p.matcher(s)
                while (m.find()) {
                    val start = m.start()
                    val end = m.end()
                    val clickableSpan: ClickableSpan = object : ClickableSpan() {
                        override fun onClick(view: View) {
                            Log.e("setClickableSpan", "点击")
                            context.startActivity(intent)
                        }

                        //设置文字样式
                        override fun updateDrawState(ds: TextPaint) {
                            super.updateDrawState(ds)
                            ds.isUnderlineText = false
                            ds.bgColor = Color.WHITE
                            ds.color = ContextCompat.getColor(context, color)
                        }
                    }
                    s.setSpan(clickableSpan, start, end, 0)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return s
    }

    /**
     * 转义正则特殊字符 （$()*+.[]?\^{},|）
     *
     * @param keyword
     * @return keyword
     */
    fun escapeExprSpecialWord(keyword: String): String {
        var keyword = keyword
        if (!TextUtils.isEmpty(keyword)) {
            val fbsArr =
                arrayOf("\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|")
            for (key in fbsArr) {
                if (keyword.contains(key)) {
                    keyword = keyword.replace(key, "\\" + key)
                }
            }
        }
        return keyword
    }

    /**
     * 通过Html.fromHtml方式修改颜色(解决SDK版本问题)
     *
     * @param html
     * @return
     */
    fun fromHtml(html: String?): Spanned {
        val result: Spanned
        result = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY)
        } else {
            Html.fromHtml(html)
        }
        return result
    }

    /**
     * 字体颜色修改
     *
     * @param content
     * @param color
     * @return
     */
    fun color(content: String, color: Int): String {
        return "<font color=\"#" + Integer.toHexString(color) + "\" >" + content + "</font>"
    }

    /**
     * 加粗字体
     *
     * @param content
     * @return
     */
    fun bold(content: String): String {
        return "<b>$content</b>"
    }
}