package com.ux.video.file.filerecovery.utils

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import com.ux.video.file.filerecovery.R

class CircleImageProgressView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : View(context, attrs) {

    private val paintBg = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        strokeWidth = 20f
        color = Color.parseColor("#9CC0EC") // 背景浅蓝
    }

    private val paintProgress = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        strokeWidth = 20f
        color = Color.parseColor("#0014F0")
        strokeCap = Paint.Cap.ROUND // 圆角进度条
    }

    private var progress = 0 // 0 - 100
    private var centerBitmap: Bitmap? = null
    private var imageScale = 1f

    init {
        context.theme.obtainStyledAttributes(attrs, R.styleable.CircleImageProgressView, 0, 0).apply {
            try {
                imageScale = getFloat(R.styleable.CircleImageProgressView_centerImageScale, 0.5f)
            } finally {
                recycle()
            }
        }
    }

    fun setProgress(value: Int) {
        progress = value.coerceIn(0, 100)
        invalidate()
    }

    fun setCenterImage(resId: Int) {
        centerBitmap = BitmapFactory.decodeResource(resources, resId)
        invalidate()
    }

    @SuppressLint("DrawAllocation")
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)


        val stroke = paintBg.strokeWidth
        val radius = (width / 2f) - (stroke / 2f)

        val rect = RectF(
            (width / 2f) - radius,
            (height / 2f) - radius,
            (width / 2f) + radius,
            (height / 2f) + radius
        )

        // 1. 背景圆环
        canvas.drawArc(rect, 0f, 360f, false, paintBg)

        // 2. 中心图片（圆形裁剪）
        centerBitmap?.let {
            val innerRadius = radius - stroke / 2f   // 图片只占内圆，不盖住圆环

            val left = (width / 2f) - innerRadius
            val top = (height / 2f) - innerRadius
            val right = (width / 2f) + innerRadius
            val bottom = (height / 2f) + innerRadius
            val rectDst = RectF(left, top, right, bottom)

            val saveCount = canvas.save()
            val path = Path().apply {
                addCircle(width / 2f, height / 2f, innerRadius, Path.Direction.CW)
            }
            canvas.clipPath(path)
            canvas.drawBitmap(it, null, rectDst, null)
            canvas.restoreToCount(saveCount)
        }

        // 3. 进度圆弧
        val sweepAngle = progress * 360f / 100f
        canvas.drawArc(rect, -90f, sweepAngle, false, paintProgress)

    }
}
