package com.casic.dcms.ui;

import android.content.Context;
import android.os.CountDownTimer;
import android.view.View;

import androidx.core.content.ContextCompat;

import com.casic.dcms.R;
import com.casic.dcms.base.AndroidxBaseActivity;
import com.casic.dcms.databinding.ActivityTrendAnalysisBinding;
import com.casic.dcms.utils.Constant;
import com.casic.dcms.utils.TimeOrDateUtil;
import com.casic.dcms.widgets.CircleProgressBar;
import com.casic.dcms.widgets.DetailsMarkerView;
import com.github.mikephil.charting.components.Legend;
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.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

public class TrendAnalysisActivity extends AndroidxBaseActivity<ActivityTrendAnalysisBinding> {

    private static final String TAG = "TrendAnalysisActivity";
    private static final DecimalFormat decimalFormat = new DecimalFormat("##0");
    private static final String[] labelName = {"普通", "快速", "三包"};
    private final Context context = TrendAnalysisActivity.this;
    private final List<Entry> totalEntries = new ArrayList<>();
    private final List<Entry> handleEntries = new ArrayList<>();
    private final List<ILineDataSet> lineDataSets = new ArrayList<>();
    private final List<BarEntry> barEntries = new ArrayList<>();

    @Override
    protected void setupTopBarLayout() {
        viewBinding.titleBarLayout.titleView.setText("趋势分析");
        viewBinding.titleBarLayout.leftBackView.setOnClickListener(v -> finish());
    }

    @Override
    protected void initData() {
        //默认显示当前月的分析数据
        viewBinding.titleBarLayout.dateView.setText(TimeOrDateUtil.timestampToYearMonth(System.currentTimeMillis()));
        //完成率总览
        bindProgressAnimation(viewBinding.wholeProgressBar, 80);
        //初始化折线图
        initLineChart();
        //初始化柱状图
        initBarChart();
        //案卷核实率
        bindProgressAnimation(viewBinding.verifyProgressBar, 50);
        //案卷核查率
        bindProgressAnimation(viewBinding.checkProgressBar, 75);
        //案卷处理率
        bindProgressAnimation(viewBinding.handleProgressBar, 80);
        //案卷紧急率
        bindProgressAnimation(viewBinding.urgentProgressBar, 20);
        //案卷超时率
        bindProgressAnimation(viewBinding.overtimeProgressBar, 10);
    }

    private void initLineChart() {
        viewBinding.lineChart.setDrawGridBackground(false);
        viewBinding.lineChart.setDrawBorders(false);
        Calendar calendar = Calendar.getInstance();
        int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        //TODO 这是模拟数据
        for (int i = 0; i < maxDay; i++) {
            totalEntries.add(new Entry(i, new Random().nextInt(100), "total"));
        }
        for (int i = 0; i < maxDay; i++) {
            handleEntries.add(new Entry(i, new Random().nextInt(80), "handle"));
        }
        //设置样式
        YAxis rightAxis = viewBinding.lineChart.getAxisRight();
        //设置图表右边的y轴禁用
        rightAxis.setEnabled(false);
        YAxis leftAxis = viewBinding.lineChart.getAxisLeft();
        leftAxis.setAxisMinimum(0f);
        viewBinding.lineChart.setScaleYEnabled(false);//Y轴不可缩放
        //设置x轴
        XAxis xAxis = viewBinding.lineChart.getXAxis();
        xAxis.setTextColor(ContextCompat.getColor(context, R.color.textColor));
        xAxis.setTextSize(12f);
        xAxis.setAxisMinimum(0f);
        xAxis.setAxisMaximum(maxDay);
        xAxis.setDrawLabels(true);//绘制标签  指x轴上的对应数值
        xAxis.setDrawAxisLine(true);//是否绘制轴线
        xAxis.setDrawGridLines(false);//设置x轴上每个点对应的线
        xAxis.setGranularity(1f);//禁止放大后x轴标签重绘
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        viewBinding.lineChart.setExtraBottomOffset(5f);//解决X轴显示不完全问题
        //去掉描述
        viewBinding.lineChart.getDescription().setEnabled(false);
        //设置图例
        Legend legend = viewBinding.lineChart.getLegend();
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        //添加自定义Marker
        DetailsMarkerView detailsMarkerView = new DetailsMarkerView(this);
        detailsMarkerView.setChartView(viewBinding.lineChart);
        viewBinding.lineChart.setMarker(detailsMarkerView);
        //设置数据
        LineDataSet totalDataSet = new LineDataSet(totalEntries, "上报案卷");
        totalDataSet.setColor(ContextCompat.getColor(context, R.color.warnColor));//线条颜色
        totalDataSet.setCircleColor(ContextCompat.getColor(context, R.color.warnColor));//圆点颜色
        lineDataSets.add(totalDataSet);

        LineDataSet handleDataSet = new LineDataSet(handleEntries, "已处理案卷");
        handleDataSet.setColor(ContextCompat.getColor(context, R.color.onLineColor));//线条颜色
        handleDataSet.setCircleColor(ContextCompat.getColor(context, R.color.onLineColor));//圆点颜色
        lineDataSets.add(handleDataSet);

        LineData lineData = new LineData(lineDataSets);
        lineData.setDrawValues(false);
        viewBinding.lineChart.setData(lineData);
        viewBinding.lineChart.invalidate();
    }

    private void initBarChart() {
        viewBinding.barChart.setDrawGridBackground(false);
        viewBinding.barChart.setDrawBorders(false);
        viewBinding.barChart.setScaleEnabled(false);
        //去掉描述
        viewBinding.barChart.getDescription().setEnabled(false);
        //去掉图例
        viewBinding.barChart.getLegend().setEnabled(false);
        //TODO 这是模拟数据
        for (int i = 0; i < 3; i++) {
            barEntries.add(new BarEntry(i, new Random().nextInt(150)));
        }
        XAxis xAxis = viewBinding.barChart.getXAxis();
        xAxis.setTextColor(ContextCompat.getColor(context, R.color.textColor));
        xAxis.setTextSize(12f);
        xAxis.setDrawLabels(true);//绘制标签  指x轴上的对应数值
        xAxis.setLabelCount(3);  // 设置x轴上的标签个数
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                return labelName[(int) value];
            }
        });
        xAxis.setDrawAxisLine(true);//是否绘制轴线
        xAxis.setDrawGridLines(false);//设置x轴上每个点对应的线
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        viewBinding.barChart.setExtraBottomOffset(5f);//解决X轴显示不完全问题
        //设置样式
        YAxis rightAxis = viewBinding.barChart.getAxisRight();
        //设置图表右边的y轴禁用
        rightAxis.setEnabled(false);
        YAxis leftAxis = viewBinding.barChart.getAxisLeft();
        leftAxis.setAxisMinimum(0f);
        //绑定数据
        BarDataSet barDataSet = new BarDataSet(barEntries, "");
        barDataSet.setColor(ContextCompat.getColor(context, R.color.mainThemeColor));
        barDataSet.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                return decimalFormat.format(value);
            }
        });
        BarData barData = new BarData(barDataSet);
        barData.setBarWidth(0.5f);
        viewBinding.barChart.setData(barData);
        viewBinding.barChart.invalidate();
    }

    @Override
    protected void initEvent() {
        viewBinding.titleBarLayout.rightImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new TimePickerDialog.Builder()
                        .setThemeColor(ContextCompat.getColor(context, R.color.mainThemeColor))
                        .setTitleStringId("选择日期")
                        .setWheelItemTextSize(16)
                        .setCyclic(false)
                        .setMinMillseconds(System.currentTimeMillis() - Constant.FIVE_YEARS)
                        .setMaxMillseconds(System.currentTimeMillis())
                        .setType(Type.YEAR_MONTH)
                        .setCallBack(new OnDateSetListener() {
                            @Override
                            public void onDateSet(TimePickerDialog timePickerView, long millSeconds) {
                                String date = TimeOrDateUtil.timestampToYearMonth(millSeconds);
                                viewBinding.titleBarLayout.dateView.setText(date);
                            }
                        }).build().show(getSupportFragmentManager(), "year_month");
            }
        });
    }

    private void bindProgressAnimation(CircleProgressBar bar, int value) {
        new CountDownTimer(value * 10L, 10) {

            @Override
            public void onTick(long l) {
                bar.setCurrentValue(value - (int) (l / 10));
            }

            @Override
            public void onFinish() {
                bar.setCurrentValue(value);
            }
        }.start();
    }
}
