package com.unis.sxzcl.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.MarkerView;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.utils.MPPointF;
import com.unis.sxzcl.R;
import com.xyxsbj.mylibrary.tool.DPTool;

import java.util.List;

/**
 * 包名: com.unis.sxzcl.widget
 * 类名: MyBarChart
 * 作用描述:
 * 创建人: mQ
 * 创建时间: 2020/11/17 10:03
 * 更新人:
 * 更新时间: 2020/11/17 10:03
 * 更新说明:
 * 版本号: 1.0
 */
public class MyBarChart {

    private Context mContext;
    private BarChart mBarChart;

    List<String> mLabels;
    String[] mBarLabels;

    public MyBarChart(Context context, BarChart barChart) {
        mContext = context;
        mBarChart = barChart;
        initView();
    }

    private void initView() {
        // 禁止缩放
        mBarChart.setScaleEnabled(false);

        //隐藏说明
        mBarChart.getDescription().setEnabled(false);
        //图例
        Legend legend = mBarChart.getLegend();
        legend.setEnabled(true);
        legend.setForm(Legend.LegendForm.CIRCLE);
        legend.setTextColor(getColorForResId(R.color.colorText55));
        legend.setTextSize(getTextSize(R.attr.textSizeX));
        //偏移量
        mBarChart.setExtraOffsets(10, 10, 10, 10);
        //是否可触摸
//        mBarChart.setTouchEnabled(false);
        //动画时长
        mBarChart.animateXY(0, 1000);
        //充分显示出柱状图
        mBarChart.setFitBars(true);

        mBarChart.setNoDataText("暂无数据");
        mBarChart.setNoDataTextColor(getColorForResId(R.color.colorText55));

        // 添加Marker
        MyMarker marker = new MyMarker(mBarChart.getContext());
        marker.setChartView(mBarChart);
        mBarChart.setMarker(marker);

        //获取 x 轴
        XAxis xAxis = mBarChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//轴显示位置
        xAxis.setDrawGridLines(false);//隐藏纵向网格
        xAxis.setAxisLineWidth(2f);//第一个轴线宽度
        xAxis.setAxisLineColor(getColorForResId(R.color.colorText99));//轴线颜色
//        xAxis.setLabelCount(5);//标签数
        xAxis.setTextSize(getTextSize(R.attr.textSizeX));//字体大小
        xAxis.setTextColor(getColorForResId(R.color.colorText55));//字体颜色
        xAxis.setLabelRotationAngle(35f);//标签旋转角度
        //自定义格式
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                //有标签集合  根据索引取值
                if (mLabels != null) {
                    try {
                        return mLabels.get((int) value);
                    } catch (Exception ignored) {
                    }
                }
                //返回原值
                return value + "";
            }
        });

        mBarChart.getAxisRight().setEnabled(false);//隐藏 右侧 y 轴

        // 获取 左边 y 轴
        YAxis mLAxis = mBarChart.getAxisLeft();
        mLAxis.setDrawAxisLine(false);//取消左侧轴线
        mLAxis.setDrawGridLines(true);//显示横向网格
        mLAxis.setGridColor(getColorForResId(R.color.colorText99));
//        mLAxis.setAxisMinimum(0);//最小值
//        mLAxis.setAxisMaximum(160);//最大值
        mLAxis.setLabelCount(5);//标签数
        mLAxis.setTextSize(getTextSize(R.attr.textSizeX));//文字大小
        mLAxis.setTextColor(getColorForResId(R.color.colorText55));//文字颜色
        mLAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                return (int) value + "";
            }
        });
    }

    /**
     * 单类型柱状图
     *
     * @param bottomLabels 底部标签
     * @param values       数据源
     */
    public void showChart(List<String> bottomLabels, List<BarEntry> values) {
        mBarChart.getLegend().setEnabled(false);
        showChart(bottomLabels, values, null, null);
    }

    /**
     * 堆叠柱状图
     *
     * @param bottomLabels 底部标签
     * @param values       数据源
     * @param colors       柱颜色
     * @param barLabels    类型名称
     */
    public void showChart(List<String> bottomLabels, List<BarEntry> values,
                          List<Integer> colors, String[] barLabels) {
        mLabels = bottomLabels;
        mBarLabels = barLabels;
        // 强制标签数
        if (mLabels != null) {
            mBarChart.getXAxis().setLabelCount(mLabels.size());
        }

        if (mBarChart.getData() != null &&
                mBarChart.getData().getDataSetCount() > 0) {
            BarDataSet set1;
            set1 = (BarDataSet) mBarChart.getData().getDataSetByIndex(0);
            set1.setValues(values);
            mBarChart.getData().notifyDataChanged();
            mBarChart.notifyDataSetChanged();
        } else {
            // 创建数据
            BarDataSet barDataSet = new BarDataSet(values, "");
            if (colors != null) {
                barDataSet.setColors(colors);
            } else {
                // 设置柱渐变色
                barDataSet.setGradientColor(
                        getColorForResId(R.color.colorThemeL),
                        getColorForResId(R.color.colorTheme));
            }
            if (barLabels != null) {
                barDataSet.setStackLabels(barLabels);
            }
            barDataSet.setValueTextSize(getTextSize(R.attr.textSizeX));//文字大小
            barDataSet.setValueTextColor(getColorForResId(R.color.colorText55));//文字颜色
            barDataSet.setValueFormatter(new ValueFormatter() {
                @Override
                public String getFormattedValue(float value) {
                    return (int) value + "";
                }
            });
            BarData barData = new BarData(barDataSet);
            barData.setBarWidth(0.3f);//柱子宽度
            // 添加数据
            mBarChart.setData(barData);
        }

        mBarChart.invalidate();
    }

    private int getColorForResId(int resId) {
        return ContextCompat.getColor(mBarChart.getContext(), resId);
    }

    class MyMarker extends MarkerView {

        private TextView mTvTitle, mTvContent;

        public MyMarker(Context context) {
            super(context, R.layout.layout_chart_marker);
            mTvTitle = findViewById(R.id.tv_title);
            mTvContent = findViewById(R.id.tv_content);
        }

        @Override
        public void refreshContent(Entry e, Highlight highlight) {
            super.refreshContent(e, highlight);
            BarEntry entry = (BarEntry) e;
            if (mLabels != null)
                mTvTitle.setText(mLabels.get((int) e.getX()));

            StringBuilder sb = new StringBuilder();
            float[] yVals = entry.getYVals();
            if (yVals != null) {
                for (int i = 0; i < yVals.length; i++) {
                    float val = yVals[i];
                    String label = mBarLabels[i];
                    sb.append(label).append(":").append((int) val);
                    if (i < yVals.length - 1)
                        sb.append("\n");
                }
            } else {
                float y = entry.getY();
                sb.append((int) y);
            }


            mTvContent.setText(sb.toString());
        }

        //该方法用于定义覆盖物的描述
        //getWidth() / 2 ：居中，负表示对齐折点
        //getHeight() - 10：离折点10的距离，正数表示在折点，负数表示在上面
        @Override
        public MPPointF getOffset() {
            return new MPPointF(-(getWidth() / 2), -getHeight() - 10);
        }
    }


    private int getTextSize(int resId) {
        TypedArray typedArray = mContext.getTheme().obtainStyledAttributes(new int[]{resId});
        return DPTool.px2sp(mContext, typedArray.getDimension(0, 0));
    }
}
