package com.file.clean.q.view.custom;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.ProgressBar;

import com.file.clean.q.R;

public class CircleProgressBar extends ProgressBar {

    private Paint backgroundPaint;
    private Paint progressPaint;
    private int progressColor = Color.parseColor("#2F55F0");
    private int backgroundColor = Color.parseColor("#E8EAFC");
    private int strokeWidth = 6;

    public CircleProgressBar(Context context) {
        super(context);
        init();
    }

    public CircleProgressBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        initAttributes(attrs);
        init();
    }

    public CircleProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAttributes(attrs);
        init();
    }

    private void initAttributes(AttributeSet attrs) {
        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.CircleProgressBar);
        progressColor = typedArray.getColor(R.styleable.CircleProgressBar_progressColor, progressColor);
        backgroundColor = typedArray.getColor(R.styleable.CircleProgressBar_backgroundColor, backgroundColor);
        strokeWidth = typedArray.getDimensionPixelSize(R.styleable.CircleProgressBar_strokeWidth, strokeWidth);
        typedArray.recycle();
    }

    private void init() {
        backgroundPaint = new Paint();
        backgroundPaint.setAntiAlias(true);
        backgroundPaint.setColor(backgroundColor);
        backgroundPaint.setStyle(Paint.Style.STROKE);
        backgroundPaint.setStrokeWidth(strokeWidth);

        progressPaint = new Paint();
        progressPaint.setAntiAlias(true);
        progressPaint.setColor(progressColor);
        progressPaint.setStyle(Paint.Style.STROKE);
        progressPaint.setStrokeWidth(strokeWidth);
        progressPaint.setStrokeCap(Paint.Cap.ROUND); // 可以设置为直角或圆形
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int width = getWidth();
        int height = getHeight();
        int radius = Math.min(width, height) / 2 - strokeWidth / 2;

        // 画背景圆
        canvas.drawCircle(width / 2, height / 2, radius, backgroundPaint);

        // 画进度圆
        float startAngle = 270; // 从顶部开始
        float sweepAngle = 360 * getProgress() / getMax(); // 根据进度计算扫过的角度

        canvas.drawArc(width / 2 - radius, height / 2 - radius, width / 2 + radius, height / 2 + radius,
                startAngle, sweepAngle, false, progressPaint);
    }
}
