package ezviz.ezopensdkcommon.common;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

/**
 * 圆形进度环控件
 * 参照 h5 原型：宽粗环 + 圆头端点（stroke-linecap: round）
 */
public class CircularProgressView extends View {

    private Paint mBgPaint;
    private Paint mProgressPaint;
    private RectF mArcRect;
    private int mProgress = 0;
    private int mMax = 100;

    // 环的宽度（dp → px 在 init 中转换）
    private float mStrokeWidth;

    public CircularProgressView(Context context) {
        this(context, null);
    }

    public CircularProgressView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

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

    private void init() {
        float density = getContext().getResources().getDisplayMetrics().density;
        mStrokeWidth = 14 * density; // 14dp 宽度

        // 背景环画笔
        mBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mBgPaint.setStyle(Paint.Style.STROKE);
        mBgPaint.setStrokeWidth(mStrokeWidth);
        mBgPaint.setStrokeCap(Paint.Cap.ROUND);
        mBgPaint.setColor(Color.parseColor("#E0E8F8"));

        // 进度弧画笔
        mProgressPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mProgressPaint.setStyle(Paint.Style.STROKE);
        mProgressPaint.setStrokeWidth(mStrokeWidth);
        mProgressPaint.setStrokeCap(Paint.Cap.ROUND);
        mProgressPaint.setColor(Color.parseColor("#5B8DEF"));

        mArcRect = new RectF();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        float padding = mStrokeWidth / 2f;
        mArcRect.set(padding, padding, w - padding, h - padding);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 画背景环（完整圆）
        canvas.drawArc(mArcRect, 0, 360, false, mBgPaint);
        // 画进度弧（从顶部开始，顺时针）
        float sweepAngle = 360f * mProgress / mMax;
        if (sweepAngle > 0) {
            canvas.drawArc(mArcRect, -90, sweepAngle, false, mProgressPaint);
        }
    }

    /**
     * 设置进度（0-100）
     */
    public void setProgress(int progress) {
        if (progress < 0) progress = 0;
        if (progress > mMax) progress = mMax;
        mProgress = progress;
        invalidate();
    }

    public int getProgress() {
        return mProgress;
    }

    public void setMax(int max) {
        mMax = max;
    }
}
