package com.zj365.health.weight
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.data.Entry

class CustomLineChart @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0
) : LineChart(context, attrs, defStyle) {

    private val mCustomRenderPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)

    init {
        mCustomRenderPaint.style = Paint.Style.STROKE
        mCustomRenderPaint.strokeWidth = 2f
        // 设置其他绘制属性，例如颜色和虚线效果
    }

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

        // 绘制连接线
        if (data != null) {
            for (dataSet in data.dataSets) {
                drawLinear(canvas, dataSet)
            }
        }
    }

    private fun drawLinear(c: Canvas, dataSet: com.github.mikephil.charting.interfaces.datasets.ILineDataSet) {
        val entryCount = dataSet.entryCount
        val path = Path()
        var hasMovedToPoint = false

        for (i in 0 until entryCount) {
            val e: Entry = dataSet.getEntryForIndex(i)

            if (!e.y.isNaN()) {
                // 绘制有效数据点的连接线
                if (!hasMovedToPoint) {
                    path.moveTo(e.x, e.y)
                    hasMovedToPoint = true
                } else {
                    path.lineTo(e.x, e.y)
                }
            } else {
                // 对于空数据点，绘制单独的点
                if (hasMovedToPoint) {
                    c.drawPath(path, mCustomRenderPaint)
                    path.reset()
                    hasMovedToPoint = false
                }
                c.drawPoint(e.x, e.y, mCustomRenderPaint)
            }
        }

        // 绘制路径
        if (!path.isEmpty) {
            c.drawPath(path, mCustomRenderPaint)
        }
    }
}

