package com.handset.serialportsensor.widget;

import android.animation.ArgbEvaluator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.handset.serialportsensor.R;
import com.handset.serialportsensor.utils.PixelUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;

import static android.graphics.Paint.Style.STROKE;

//@SuppressWarnings(value = "unused")
public class DashBoard extends View {
    private static final String logTag = "HANDSET-JE002-EX";

    private Paint paint;
    //最外层圆环的颜色
    private int circleColor;
    //圆环进度的颜色
    private int progressCircleColor;

    //圆环的厚度，即大小
    private float circleThickness;
    //最上面字体的颜色
    //private int topTextColor;
    //第二行字体的颜色
    private int secondTextColor;
    //第三行字体的颜色
    private int thirdTextColor;

    //RoundProgress开始的颜色，决定RoundProgress的渐变区间
    private int progressStartColor;
    //RoundProgress结束的颜色，决定RoundProgress的渐变区间
    private int ProgressEndColor;
    //进度的最大值，默认是1000
    private double maxProgress;
    //当前的进度，默认0
    private double currentProgress;
    //第二行字
    private String secondText;
    //第三行字
    private String thirdText = "kg";
    //最上面的字的大小
    //private float topTextSize;
    //第二行字的大小
    private float secondTextSize;
    //第三行字的大小
    private float thirdTextSize;
    //最外层圆的半径
    private int outerFirstCircleRadius;


    //文字颜色是否argb变化
    private boolean progressArgbColor;

    //小圆是否可用
    private boolean smallCircleEnable;

    private boolean customArc;

    private int startArc;
    private int center;

    private Float valueFloor;
    private Float valueCeiling;

    private int textPaintStroke;
    private ArgbEvaluator mArgbEvaluator;

    private boolean showOutText;
    protected Paint textStartPaint = new TextPaint();
    protected Paint textEndPaint = new TextPaint();
    protected RectF ringRect = new RectF();
    private float textStartSize;
    private float textEndSize;
    public String textStart;
    public String textEnd;
    private int textStartColor;
    private int textEndColor;
    private Context context;
    private int circlePadding;

    public DashBoard(Context context) {
        this(context, (null));
        this.context = context;
    }

    public DashBoard(Context context, AttributeSet attrs) {
        this(context, attrs, (0));
        this.context = context;
    }

    public DashBoard(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        paint = new Paint();

        mArgbEvaluator = new ArgbEvaluator();
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.DashBoard);

        //获取自定义属性和默认值
        circleColor = typedArray.getColor(R.styleable.DashBoard_circleColor, context.getResources().getColor(R.color.dashboard_gray));

        progressCircleColor = typedArray.getColor(R.styleable.DashBoard_progressCircleColor, context.getResources().getColor(R.color.dashboard_normal_end));

        progressStartColor = typedArray.getColor(R.styleable.DashBoard_progressStartColor, getResources().getColor(R.color.dashboard_normal_start));
        ProgressEndColor = typedArray.getColor(R.styleable.DashBoard_progressEndColor, getResources().getColor(R.color.dashboard_normal_end));

        circleThickness = typedArray.getDimension(R.styleable.DashBoard_circleThickness, PixelUtils.dp2px(context, 10));

        secondTextColor = typedArray.getColor(R.styleable.DashBoard_secondTextColor, Color.BLACK);
        thirdTextColor = typedArray.getColor(R.styleable.DashBoard_thirdTextColor, Color.BLACK);
        secondText = typedArray.getString(R.styleable.DashBoard_secondText);

        maxProgress = typedArray.getInt(R.styleable.DashBoard_maxProgress, 100);
        currentProgress = typedArray.getInt(R.styleable.DashBoard_currentProgress, 0);
        customArc = typedArray.getBoolean(R.styleable.DashBoard_customArc, false);
        startArc = typedArray.getInt(R.styleable.DashBoard_startArc, 0);
        showOutText = typedArray.getBoolean(R.styleable.DashBoard_showOutText, false);
        textStartSize = typedArray.getDimension(R.styleable.DashBoard_textStartSize, PixelUtils.sp2px(context, 10));
        textEndSize = typedArray.getDimension(R.styleable.DashBoard_textEndSize, PixelUtils.sp2px(context, 10));
        textStartColor = typedArray.getColor(R.styleable.DashBoard_textStartColor, context.getResources().getColor(R.color.dashboard_normal_end));
        textEndColor = typedArray.getColor(R.styleable.DashBoard_textEndColor, context.getResources().getColor(R.color.dashboard_normal_end));
        textStart = typedArray.getString(R.styleable.DashBoard_textStart);
        textEnd = typedArray.getString(R.styleable.DashBoard_textEnd);

        valueFloor = typedArray.getFloat(R.styleable.DashBoard_valueFloor, (0.0f));
        valueCeiling = typedArray.getFloat(R.styleable.DashBoard_valueCeiling, (0.0f));

        //设置第三行文字的默认文字
        String defaultThirdText = typedArray.getString(R.styleable.DashBoard_thirdText);
        if (defaultThirdText != null) {
            thirdText = defaultThirdText;
        }
        secondTextSize = typedArray.getDimension(R.styleable.DashBoard_secondTextSize, PixelUtils.sp2px(context, 45));
        thirdTextSize = typedArray.getDimension(R.styleable.DashBoard_thirdTextSize, PixelUtils.sp2px(context, 16));

        //控制颜色渐变的开关
        progressArgbColor = typedArray.getBoolean(R.styleable.DashBoard_progressArgbColor, false);
        smallCircleEnable = typedArray.getBoolean(R.styleable.DashBoard_smallCircleEnable, true);
        typedArray.recycle();
        circlePadding = PixelUtils.dp2px(context, 18);
    }

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

        int width = getWidth();
        int height = getHeight();

        //第1步：画出最外层的圆环
        drawOuterFirstCircle(canvas);

        //第2步，画出圆弧
        drawArc(canvas);

        //第3步，画出三行文字
        drawText(canvas);

        if (showOutText) {
            textStartPaint.setColor(textStartColor);
            textStartPaint.setTextSize(textStartSize);
            textStartPaint.setAntiAlias(true);

            textEndPaint.setColor(textEndColor);
            textEndPaint.setTextSize(textEndSize);
            textEndPaint.setAntiAlias(true);
        }

        float delta = circleThickness;
        int padding = PixelUtils.dp2px(getContext(), 10);
        ringRect.set(delta + padding,
                delta + padding,
                width - delta - padding,
                height - delta - padding);
        float ringWidth = ringRect.right - ringRect.left;
        //第5步，画出外面的文字
        if (showOutText && !TextUtils.isEmpty(textStart) && !TextUtils.isEmpty(textEnd)) {
            int endArc = startArc + (int) currentProgress;
            int startPadding = (int) textStartPaint.measureText(textEnd) / 2 + PixelUtils.dp2px(getContext(), 6);
            if (startArc <= 0 || startArc >= 180) {
                startPadding = 0;
            }
            int endPadding = (int) textEndPaint.measureText(textStart) / 3 + PixelUtils.dp2px(getContext(), 2);
            if (endArc > 180) {
                endPadding = 0 - endPadding;
            }
            canvas.drawText(textStart, ringWidth / 2.0f + (ringWidth - circlePadding) / 2 * sin(endArc) + endPadding, ringRect.top + ringWidth / 2 - ringWidth / 2 * cos(endArc), textStartPaint);
            canvas.drawText(textEnd, ringWidth / 2.0f + (ringWidth - circlePadding) / 2 * sin(startArc) + startPadding, ringRect.top + ringWidth / 2 - ringWidth / 2 * cos(startArc), textEndPaint);
        }
    }

    /**
     * 绘制最外层的圆
     *
     * @param canvas 画笔
     */
    private void drawOuterFirstCircle(Canvas canvas) {
        //设置圆的颜色
        paint.setColor(circleColor);

        //设置只绘制边框
        paint.setStyle(STROKE);
        //设置圆的宽度
        paint.setStrokeWidth(circleThickness / 2);
        //消除锯齿
        paint.setAntiAlias(true);
        //画出圆
        canvas.drawCircle(center, center, outerFirstCircleRadius, paint);
    }

    private void drawText(Canvas canvas) {
        paint.setStrokeWidth(textPaintStroke);
        paint.setStyle(Paint.Style.FILL);

        //画出第二行文本
        paint.setTextSize(secondTextSize);
        paint.setColor(secondTextColor);
        float textWidth2 = paint.measureText(secondText);
        canvas.drawText(secondText, center - textWidth2 / 2, center - secondTextSize / 4, paint); //画出卡路里数值

        //画出第三行文本
        paint.setTextSize(thirdTextSize);
        paint.setColor(thirdTextColor);
        if (thirdText != null) {
            float textWidth3 = paint.measureText(thirdText);
            canvas.drawText(thirdText, center - textWidth3 / 2, center + (float) outerFirstCircleRadius / 4 + thirdTextSize / 2, paint); //画出卡路里单位
        }

    }

    private void drawArc(Canvas canvas) {
        paint.setStrokeWidth(circleColor);

        paint.setStyle(STROKE);
        if (smallCircleEnable) {
            paint.setStrokeCap(Paint.Cap.BUTT);
        } else {
            paint.setStrokeCap(Paint.Cap.ROUND);
        }
        paint.setAntiAlias(true);

        //设置圆弧宽度
        paint.setStrokeWidth(circleThickness + 1);

        RectF oval2 = new RectF(center - outerFirstCircleRadius, center - outerFirstCircleRadius, center + outerFirstCircleRadius, center + outerFirstCircleRadius);  //用于定义的圆弧的形状和大小的界限

        double progress;
        //这里画圆环的时候第二个参数为开始角度，0表示右边中线，90表示底部，-outerFirstCircleRadius
        if (currentProgress < maxProgress) {
            progress = currentProgress;
            drawArcByColor(canvas, oval2, progress);
        } else {
            progress = maxProgress;
            drawArcByColor(canvas, oval2, progress);
        }
    }

    private void drawArcByColor(Canvas canvas, RectF oval2, double progress) {
        for (int i = 0; i < progress / maxProgress * 360; i++) {
            if (progressArgbColor) {//如果颜色渐变， 则改变色值
                progressCircleColor = (Integer) mArgbEvaluator.evaluate(i / 360f, progressStartColor, ProgressEndColor);//颜色插值器（level 11以上才可以用）
                secondTextColor = ProgressEndColor;
            }
            paint.setAntiAlias(true);
            paint.setColor(progressCircleColor);
            if (customArc) {
                if (i < maxProgress * 360) {
                    canvas.drawArc(oval2, (float) (-90 + i + startArc), 1.35f, false, paint);
                }
            } else {
                if (i < maxProgress * 360) {
                    canvas.drawArc(oval2, (float) (-90 + i), 1.35f, false, paint);
                }
            }
        }
    }


    /**
     * 当控件的宽高发生变化的时候调用的方法
     * 在这里得到控件的宽高,避免在onDraw的时候多次初始化
     */
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        //获取圆心的坐标，对于自身控件而言是1/2
        center = getMeasuredWidth() / 2;
        //原本是半径是等于中心点，但是由于设置画笔宽度的时候，这个宽度会根据当前的半径，往外部和内部各扩展1/2。
        //所以在设置半径是需要减去圆环宽度的一半。
        //这里减去整个圆环厚度是因为想让圆环距离本控件有左右间距，故意为之
        outerFirstCircleRadius = (int) (center - circleThickness - PixelUtils.dp2px(context, 18));
        //文字不用太大
        textPaintStroke = 1;
    }

    public float sin(int i) {
        return (float) Math.sin(i * Math.PI / 180);
    }

    public float cos(int i) {
        return (float) Math.cos(i * Math.PI / 180);
    }

    public void setTextStart(String textStart) {
        this.textStart = textStart;
        this.invalidate();
    }

    public void setTextEnd(String textEnd) {
        this.textEnd = textEnd;
        this.invalidate();
    }

    private final static String FLOAT_TYPE = "0.00";

    public void setSecondText(Float value) {
        BigDecimal tmp = new BigDecimal(value);
        BigDecimal floor = new BigDecimal(valueFloor);
        BigDecimal ceiling = new BigDecimal(valueCeiling);
        if (!(tmp.compareTo(floor) < 0 || tmp.compareTo(ceiling) > 0)) {
            this.secondText = new DecimalFormat(FLOAT_TYPE).format(value);
            invalidate();
            return;
        }
        Log.w(logTag, ("item: " + thirdText + ", value: " + value + " exceed!"));
    }

    public void setSecondText(Float value, boolean isNormal) {
        Log.i(logTag, "value: " + value);
        BigDecimal tmp = new BigDecimal(value);
        BigDecimal floor = new BigDecimal(valueFloor);
        BigDecimal ceiling = new BigDecimal(valueCeiling);
        if (!(tmp.compareTo(floor) < 0 || tmp.compareTo(ceiling) > 0)) {
            this.secondText = new DecimalFormat(FLOAT_TYPE).format(value);
            setProgressStartColor(getResources().getColor(isNormal ? R.color.progress_normal_start : R.color.progress_err_end));
            setProgressEndColor(getResources().getColor(isNormal ? R.color.progress_normal_end : R.color.progress_err_end));
            invalidate();
            return;
        }
        Log.w(logTag, ("item: " + thirdText + ", value: " + value + " exceed!"));
    }

    public void setSecondText(String value) {
        this.secondText = value;
        setProgressStartColor(getResources().getColor(R.color.progress_normal_start));
        setProgressEndColor(getResources().getColor( R.color.progress_normal_end ));
        invalidate();
    }

    /**
     * 控制RoundProgress颜色渐变
     * @param progressCircleColor  startColor
     */
    public void setProgressStartColor(int progressCircleColor) {
        this.progressStartColor = progressCircleColor;
    }

    /**
     * 控制RoundProgress颜色渐变
     * @param progressCircleColor  endColor
     */
    public void setProgressEndColor(int progressCircleColor) {
        this.ProgressEndColor = progressCircleColor;
    }
}
