package com.gh.gamecenter.common.view

import android.graphics.*
import android.text.style.ReplacementSpan
import androidx.annotation.Dimension
import com.gh.gamecenter.common.HaloApp
import com.gh.gamecenter.core.utils.DisplayUtils


class GradientRoundBackgroundColorSpan(
    private val startColor: String,
    private val endColor: String,
    private val textColor: String,
    @Dimension(unit = Dimension.SP)
    private val textSize: Int = 0
) : ReplacementSpan() {


    override fun getSize(paint: Paint, text: CharSequence, start: Int, end: Int, fm: Paint.FontMetricsInt?): Int {
        return paint.measureText(text, start, end).toInt()
    }

    override fun draw(
        canvas: Canvas,
        text: CharSequence,
        start: Int,
        end: Int,
        x: Float,
        top: Int,
        y: Int,
        bottom: Int,
        paint: Paint
    ) {
        val originalColor = paint.color
        val originalTextSize = paint.textSize

        paint.style = Paint.Style.FILL

        val fontMetrics = paint.fontMetrics

        // 原文字宽度
        val originalTextWidth = paint.measureText(text, start, end).toInt()
        // 当目标字体大小与原字体大小不一样时，需要先用目标字体大小测量字体宽度
        if (textSize != 0) {
            paint.textSize = DisplayUtils.sp2px(HaloApp.getInstance(), textSize.toFloat()).toFloat()
        }
        // 目标文字宽度
        val textWidth = paint.measureText(text, start, end).toInt()

        // 用原字体大小画椭圆
        paint.textSize = originalTextSize
        //添加渐变Shader
        val mShader = LinearGradient(
            0F, top.toFloat(), x + originalTextWidth, top + fontMetrics.bottom - fontMetrics.top,
            Color.parseColor(startColor), Color.parseColor(endColor), Shader.TileMode.CLAMP
        )
        paint.shader = mShader
        canvas.drawRoundRect(
            RectF(
                x,
                top.toFloat(),
                x + originalTextWidth,
                top + fontMetrics.bottom - fontMetrics.top
            ),
            DisplayUtils.dip2px(HaloApp.getInstance(), 5f).toFloat(),
            DisplayUtils.dip2px(HaloApp.getInstance(), 5f).toFloat(),
            paint
        )

        //重置paint
        paint.color = Color.parseColor(this.textColor)
        //移除渐变Shader，否则绘制的文字也是渐变色
        paint.shader = null
        paint.style = Paint.Style.FILL

        // 用目标字体大小画字
        if (textSize != 0) {
            paint.textSize = DisplayUtils.sp2px(HaloApp.getInstance(), textSize.toFloat()).toFloat()
        }
        val offsetX = (originalTextWidth - textWidth) / 2
        canvas.drawText(text, start, end, x + offsetX, y.toFloat(), paint)

        paint.color = originalColor
    }
}
