package com.module.backstage.chart

import android.graphics.Color
import android.graphics.Matrix
import android.graphics.Typeface
import android.util.Log
import com.github.mikephil.charting.animation.Easing
import com.github.mikephil.charting.charts.BarChart
import com.github.mikephil.charting.components.AxisBase
import com.github.mikephil.charting.components.Description
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.components.LimitLine
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.IAxisValueFormatter
import com.github.mikephil.charting.formatter.ValueFormatter
import com.github.mikephil.charting.utils.ViewPortHandler
import java.math.BigDecimal
import java.text.DecimalFormat

class BarChartManager(private val mBarChart: BarChart) {
    private val leftAxis: YAxis = mBarChart.axisLeft
    private val rightAxis: YAxis = mBarChart.axisRight
    private val xAxis: XAxis = mBarChart.xAxis
    private var mFormat: DecimalFormat? = null
    private  val TAG = "BarChartManager"
    /**
     * 初始化LineChart
     */
    private fun initLineChart() {
        mFormat = DecimalFormat("#,###.##")
        //背景颜色
        mBarChart.setBackgroundColor(Color.parseColor("#00000000"))
        //是否显示网格背景
        mBarChart.setDrawGridBackground(false)
        //显示每条背景阴影
        mBarChart.setDrawBarShadow(false)
        //设置图标边框的颜色
        mBarChart.setBorderColor(Color.parseColor("#00000000"))
        //        mBarChart.setHighlightFullBarEnabled(false);
        mBarChart.setTouchEnabled(true) // 所有触摸事件,默认true
        mBarChart.isDragEnabled = true // 可拖动,默认true
        mBarChart.setScaleEnabled(false) // 两个轴上的缩放,X,Y分别默认为true
        mBarChart.isScaleXEnabled = true // X轴上的缩放,默认true
        mBarChart.isScaleYEnabled = false // Y轴上的缩放,默认true
        mBarChart.setPinchZoom(false) // X,Y轴同时缩放，false则X,Y轴单独缩放,默认false
        mBarChart.isDoubleTapToZoomEnabled = true // 双击缩放,默认true
        mBarChart.isDragDecelerationEnabled = true // 抬起手指，继续滑动,默认true

        //设置后可以拖动，不知道为什么呢？？？？
        val m = Matrix()
        m.postScale(1f, 1f) //两个参数分别是x,y轴的缩放比例。例如：将x轴的数据放大为之前的1.5倍
        mBarChart.viewPortHandler.refresh(m, mBarChart, false) //将图表动画显示之前进行缩放
        mBarChart.animateX(1000)


        //显示边界
        mBarChart.setDrawBorders(false)
        //设置XY动画效果
        mBarChart.animateY(1000, Easing.Linear)
        mBarChart.animateX(1000, Easing.Linear)
        //      不显示描述信息:在右下角
        mBarChart.description.isEnabled = false
        //         图例设置
        val legend = mBarChart.legend
        //不显示图例
        legend.form = Legend.LegendForm.NONE
        //        图例文字的大小
        legend.textSize = 11f

        //显示位置
        legend.verticalAlignment = Legend.LegendVerticalAlignment.BOTTOM
        legend.horizontalAlignment = Legend.LegendHorizontalAlignment.LEFT
        legend.orientation = Legend.LegendOrientation.HORIZONTAL
        legend.setDrawInside(false)

        //XY轴的设置
        //X轴设置显示位置在底部
        xAxis.position = XAxis.XAxisPosition.BOTTOM
        //      X轴最小间距
        xAxis.granularity = 10f
        //      不绘制网格线
        xAxis.setDrawGridLines(false)
        //      X轴字体样式
        xAxis.typeface = Typeface.DEFAULT_BOLD
        //      设置X轴文字剧中对齐
        xAxis.setCenterAxisLabels(true)

        //       保证Y轴从0开始，不然会上移一点
        leftAxis.setDrawGridLines(false)
        rightAxis.axisMinimum = 0f
        leftAxis.axisMinimum = 0f
        leftAxis.textColor = Color.WHITE
        leftAxis.axisLineColor = Color.WHITE
        leftAxis.gridColor = Color.WHITE
        //        // 线跟数据都不显示
        rightAxis.isEnabled = false //右侧Y轴不显示
    }


    inner class MyYAxisValueFormatter(private val xValues: Array<String>) : IAxisValueFormatter {
        override fun getFormattedValue(value: Float, axis: AxisBase): String {
//            Log.e("TAG", "xValues[(int) value]====="+xValues[(int) value]);
            return mFormat!!.format(value.toDouble()) + "%"
        }
    }


    inner class XAxisValueFormatter(private val xValues: Array<String>) : IAxisValueFormatter {
        override fun getFormattedValue(value: Float, axis: AxisBase): String {
            Log.e("TAG", "============$value")
            val value1 = value.toInt()
            if (value < xValues.size) {
                return xValues[value1]
            }
            return ""
        }
    }

    /**
     * 展示柱状图(多条)
     * +-+
     *
     * @param xAxisValues
     * @param yAxisValues
     * @param labels
     * @param colours
     */
    fun showMoreBarChart(
        xAxisValues: List<Float>,
        yAxisValues: List<List<Float?>>,
        labels: List<String?>,
        colours: List<Int?>,
        xValues: Array<String?>,
        max: Float
    ) {
        initLineChart()


        //        设置Y轴的最小值和最大值
        //leftAxis.setAxisMaximum(100f);
        leftAxis.axisMaximum = max
        leftAxis.axisMinimum = 0f
        val data = BarData()
        for (i in yAxisValues.indices) {
            val entries = ArrayList<BarEntry>()
            for (j in yAxisValues[i].indices) {
                entries.add(BarEntry(xAxisValues[j], yAxisValues[i][j]!!))
            }
            val barDataSet = BarDataSet(entries, labels[i])

            barDataSet.color = colours[i]!!
            barDataSet.valueTextColor = colours[i]!!
            barDataSet.valueTextSize = 18f
            //设置柱上面的文字
            if (i == 0) {
                barDataSet.valueFormatter = object : ValueFormatter() {
                    override fun getFormattedValue(
                        value: Float,
                        entry: Entry,
                        dataSetIndex: Int,
                        viewPortHandler: ViewPortHandler
                    ): String {
                        return "￥" + entry.y.toInt() + ""
                    }
                }
            } else {
                barDataSet.valueFormatter = object : ValueFormatter() {
                    override fun getFormattedValue(
                        value: Float,
                        entry: Entry,
                        dataSetIndex: Int,
                        viewPortHandler: ViewPortHandler
                    ): String {
                        return "" + entry.y.toInt()
                    }
                }
            }
            val finalI = i
            barDataSet.valueFormatter = object : ValueFormatter() {
                override fun getFormattedValue(
                    value: Float,
                    entry: Entry,
                    dataSetIndex: Int,
                    viewPortHandler: ViewPortHandler
                ): String {
                    if (finalI == 0) {
                        val b = BigDecimal(entry.y.toString())
                        val d = b.toDouble()

                        return "￥$d"
                    } else {
                        return "" + entry.y.toInt()
                    }
                }
            }
            barDataSet.axisDependency = YAxis.AxisDependency.LEFT
            data.addDataSet(barDataSet)
        }
        val amount = yAxisValues.size

        val groupSpace = 0.3f //柱状图组之间的间距
        //        float barSpace = (float) ((1 - 0.12) / amount / 10); // x4 DataSet
//        float barWidth = (float) ((1 - 0.31) / amount / 10 * 9); // x4 DataSet
//
        val barWidth = (1f - groupSpace) / amount
        val barSpace = 0f
        // (0.2 + 0.02) * 4 + 0.08 = 1.00 -> interval per "group"
        xAxis.setLabelCount(xAxisValues.size - 1, false)
        xAxis.setDrawLabels(true)
        xAxis.textSize = 18f
        xAxis.textColor = Color.WHITE
        xAxis.granularity = 1f
        xAxis.setDrawLimitLinesBehindData(false)
        xAxis.axisLineColor = Color.WHITE
        leftAxis.axisLineColor = Color.WHITE
        leftAxis.textSize = 18f
        data.barWidth = barWidth
        //        final String[] xValues = {"2018-08-08", "2018-08-08", "2018-08-08", "2018-08-08", "2018-08-08", "2018-08-08", "2018-08-08"};
        xAxis.valueFormatter = object : ValueFormatter() {
            override fun getFormattedValue(value: Float): String {
                Log.d(TAG, "getFormattedValue size : "+xAxisValues.size)
                for (i in 0 until xAxisValues.size) {
                    Log.d(TAG, "getFormattedValue: "+value+":"+xAxisValues[i])
                    if (value == (xAxisValues[i] - 1)) {
                        return xValues[i]!!
                    }
                }
                return ""
            }
        }
        Log.d(TAG, "showMoreBarChart 執行了。: ")
        data.groupBars(0f, groupSpace, barSpace)
        mBarChart.data = data
        // mBarChart.setFitBars(true);
    }

    /**
     * 设置Y轴值
     *
     * @param max
     * @param min
     * @param labelCount
     */
    fun setYAxis(max: Float, min: Float, labelCount: Int) {
        if (max < min) {
            return
        }
        leftAxis.axisMaximum = max
        leftAxis.axisMinimum = min
        leftAxis.setLabelCount(labelCount, false)

        rightAxis.axisMaximum = max
        rightAxis.axisMinimum = min
        rightAxis.setLabelCount(labelCount, false)
        mBarChart.invalidate()
    }

    /**
     * 设置X轴的值
     *
     * @param max
     * @param min
     * @param labelCount
     */
    fun setXAxis(max: Float, min: Float, labelCount: Int) {
        xAxis.axisMaximum = max
        xAxis.axisMinimum = min
        xAxis.setLabelCount(labelCount, false)

        mBarChart.invalidate()
    }

    /**
     * 设置高限制线
     *
     * @param high
     * @param name
     */
    fun setHightLimitLine(high: Float, name: String?, color: Int) {
        var name = name
        if (name == null) {
            name = "高限制线"
        }
        val hightLimit = LimitLine(high, name)
        hightLimit.lineWidth = 4f
        hightLimit.textSize = 10f
        hightLimit.lineColor = color
        hightLimit.textColor = color
        leftAxis.addLimitLine(hightLimit)
        mBarChart.invalidate()
    }

    /**
     * 设置低限制线
     *
     * @param low
     * @param name
     */
    fun setLowLimitLine(low: Int, name: String?) {
        var name = name
        if (name == null) {
            name = "低限制线"
        }
        val hightLimit = LimitLine(low.toFloat(), name)
        hightLimit.lineWidth = 4f
        hightLimit.textSize = 10f
        leftAxis.addLimitLine(hightLimit)
        mBarChart.invalidate()
    }

    /**
     * 设置描述信息
     *
     * @param str
     */
    fun setDescription(str: String?) {
        val description = Description()
        description.text = str
        mBarChart.description = description
        mBarChart.invalidate()
    }
}