package com.xty.common.weight

import android.content.Context
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.View
import com.xty.common.R

class GaugeView(context: Context, attrs: AttributeSet?) : View(context, attrs) {
    private val bgDrawable: Drawable? // 背景图片资源
    private val pointerDrawable: Drawable? // 指针图片资源
    private var value = 0 // 当前的数值

    init {
        bgDrawable = context.getDrawable(R.mipmap.bg_tongue_point) // 背景图片资源
        pointerDrawable = context.getDrawable(R.mipmap.ic_tongue_point) // 指针图片资源

        // 获取自定义属性
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.GaugeView)
        value = typedArray.getInt(R.styleable.GaugeView_value, 0)
        typedArray.recycle()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val centerX = width / 2f
        val centerY = height.toFloat() // 指针底部在布局底部

        // 绘制背景图片
        bgDrawable?.let {
            it.setBounds(0, 0, width, height)
            it.draw(canvas)
        }

        // 计算指针旋转角度
        var rotate = mapValueToDegrees(value)
        if (rotate > 95) {
            rotate -= 5
        }
        val rotationAngle = mapValueToDegrees(value)

        // 绘制指针
        pointerDrawable?.let {
            val pointerWidth = it.intrinsicWidth
            val pointerHeight = it.intrinsicHeight
            val left = centerX - pointerWidth
            val top = centerY - pointerHeight // 指针尾部在底部
            val right = left + pointerWidth
            val bottom = centerY

            it.setBounds(left.toInt(), top.toInt(), right.toInt(), bottom.toInt())
            canvas.save()
            canvas.rotate(rotationAngle, centerX, centerY) // 指针的旋转点在底部
            it.draw(canvas)
            canvas.restore()
        }
    }

    // 将0-100的值映射到0-180的角度
    private fun mapValueToDegrees(value: Int): Float {
        return value * 1.6f + 10
    }

    // 设置当前的数值
    fun setValue(newValue: Int) {
        value = newValue
        invalidate()
    }
}