package com.zj365.health.fragment.bloodlipid

import android.content.Context
import android.graphics.Color
import android.graphics.DashPathEffect
import android.graphics.Matrix
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.text.isDigitsOnly
import com.github.mikephil.charting.charts.BarChart
import com.github.mikephil.charting.charts.LineChart
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.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.IFillFormatter
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet
import com.xty.common.LogUtils
import com.zj365.health.R
import com.zj365.health.weight.CustomXAxisRenderer
import com.zj365.health.weight.ICompareMarkView
import com.zj365.health.weight.IMarkView
import java.text.SimpleDateFormat
import java.util.ArrayList
import java.util.Calendar
import java.util.Locale

object BaseChartInitUtils {

    fun initLineChart(
        context: Context, lineChart: LineChart, min: Float, max: Float, lineValue: ArrayList<Entry>,
        mark: IMarkView.MarkPage, unit: String, offset: Float
    ) {
        lineChart.let {
            LogUtils.e("BloodFatFragment", it.toString())
            it.clear()
            it.setNoDataText(context.getString(R.string.line_chart_not_data))
            it.setNoDataTextColor(ContextCompat.getColor(context, R.color.col_455))
            it.setLayerType(View.LAYER_TYPE_SOFTWARE, null)

            it.setBackgroundColor(Color.WHITE) ///color
            it.description.isEnabled = false
            it.setTouchEnabled(true)

            it.setScaleEnabled(false)
            it.setPinchZoom(false)

            it.setDrawGridBackground(false)
            it.maxHighlightDistance = 300f


            it.isDragEnabled = true
            val m = Matrix()
            m.postScale(1.5f, 1f)
            it.viewPortHandler.refresh(m, it, false)
            it.isScaleXEnabled = true                 //支持x轴缩放
            it.isScaleYEnabled = false

            val x = it.xAxis
            x.granularity = 1f  //精准设置
            x.textColor = ContextCompat.getColor(context, R.color.col_92a)
            x.isEnabled = true
            x.setDrawGridLines(false)  //不绘制y
            x.setDrawAxisLine(false)
            //   x.setLabelCount(lineValue.size,false)
            // x.labelRotationAngle=-45f
            x.position = XAxis.XAxisPosition.BOTTOM
            x.setAvoidFirstLastClipping(false)
            x.setValueFormatter { value, axis ->
                val index = value.toInt()
                //Log.e("x轴", "$value")
                if (index < 0 || index >= lineValue.size) {
                    ""
                } else {
                    "${lineValue[value.toInt()].data}"
                }
            }

            //y轴
            val y = it.axisLeft
            y.setLabelCountAndMaxMinValue(
                6,
                false,
                if (min - offset > 0f) min - offset else min,
                if (max >= 0f) max + offset else max
            )
            y.textColor = ContextCompat.getColor(context, R.color.col_92a)
            y.setDrawAxisLine(false)
            y.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
            y.gridColor = ContextCompat.getColor(context, R.color.col_0F2)
            y.setGridDashedLine(DashPathEffect(floatArrayOf(5f, 0f), 0f))
            y.setDrawGridLines(true)  //绘制横者的x轴
            y.setDrawZeroLine(true)

            val markerView = IMarkView(
                context, R.layout.mark_view, unit,
                mark
            )
            it.marker = markerView
            markerView.chartView = it
            it.axisRight.isEnabled = false
            it.legend.isEnabled = false

            //   it.animateXY(2000, 2000)  //设置xy轴进入的动画
            it.invalidate()
        }
    }


    fun calculateBarWidth(dataCount: Int): Float {
        val maximumBarWidth = 0.3f // 设置最大柱形图宽度
        val minimumBarWidth = 0.3f // 设置最小柱形图宽度

        val defaultBarWidth = 0.3f // 默认柱形图宽度
        val availableWidth = 1.0f - (dataCount + 1) * 0.1f // 可用宽度减去间距占用

        val calculatedBarWidth = availableWidth / dataCount.toFloat()
        return java.lang.Float.max(
            minimumBarWidth,
            java.lang.Float.min(maximumBarWidth, calculatedBarWidth)
        )
    }

    fun initBarChart(
        context: Context, barChart: BarChart, min: Float, max: Float, barValue: ArrayList<BarEntry>,
        mark: IMarkView.MarkPage, type: Int, unit: String, offset: Float
    ) {
        barChart.let {
            it.clear()
            it.setNoDataText(context.getString(R.string.line_chart_not_data))
            it.setNoDataTextColor(ContextCompat.getColor(context, R.color.col_455))
            it.setLayerType(View.LAYER_TYPE_SOFTWARE, null)

            it.setBackgroundColor(Color.WHITE) ///color
            it.description.isEnabled = false
            it.setTouchEnabled(true)
            it.setPinchZoom(true)//柱形图的横坐标缩放，

            it.setDrawGridBackground(false)//背景网格是否绘制
            it.maxHighlightDistance = 300f//设置高亮（Highlight）的最大距离


            it.isDragEnabled = true//是否启用拖动（drag）功能。
            val m = Matrix()
            m.postScale(
                when (type) {
                    1 -> {
                        0.5f
                    }

                    3 -> {
                        3.5f
                    }

                    else -> {
                        1f
                    }
                }, 0f
            )
            it.viewPortHandler.refresh(m, it, false)
            it.isScaleXEnabled = true  //支持x轴缩放
            it.isScaleYEnabled = false //支持Y轴缩放

            val x = it.xAxis
            x.granularity = 1f  //精准设置
            x.textColor = ContextCompat.getColor(context, R.color.col_92a)
            x.textSize = 9f
            x.axisMinimum = -0.5f
            x.axisMaximum = (barValue.size - 0.5).toFloat()
//                x.labelCount = 6
            x.isEnabled = true
            x.setDrawGridLines(false)  //不绘制y
            x.setDrawAxisLine(false)
            x.xOffset = 0f
            x.position = XAxis.XAxisPosition.BOTTOM
            x.setValueFormatter { value, axis ->
                var index = value.toInt()
                //Log.e("x轴", "$value")
                if (index < 0 || index >= barValue.size) {
                    ""
                } else {
                    "${barValue[value.toInt()].data}"
                }
            }
            val y = it.axisLeft
            y.setLabelCountAndMaxMinValue(
                6,
                false,
                if (min - offset > 0f) min - offset else min,
                if (max >= 0f) max + offset else max
            )
            y.textColor = ContextCompat.getColor(context, R.color.col_92a)
            y.setDrawAxisLine(false)
            y.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
            y.gridColor = ContextCompat.getColor(context, R.color.col_0F2)
            y.setGridDashedLine(DashPathEffect(floatArrayOf(5f, 0f), 0f))
            y.setDrawGridLines(true)  //绘制横者的x轴
            y.setDrawZeroLine(true)
            var markerView = IMarkView(
                context, R.layout.mark_view, unit,
                mark
            )
            it.marker = markerView
            markerView.chartView = it
            it.axisRight.isEnabled = false
            it.legend.isEnabled = false
        }
    }

    fun initBarChartTwo(
        context: Context,
        barChart: BarChart,
        min: Float,
        max: Float,
        barValue: ArrayList<BarEntry>,
        barValueCompare: ArrayList<BarEntry>,
        mark: ICompareMarkView.MarkPage,
        unit: String,
        type: Int,
        offset: Float
    ) {
        barChart.let {
            it.clear()
            it.setNoDataText(context.getString(R.string.line_chart_not_data))
            it.setNoDataTextColor(ContextCompat.getColor(context, R.color.col_455))
            it.setLayerType(View.LAYER_TYPE_SOFTWARE, null)
            if (barValue.size == 0 && barValueCompare.size == 0) {
                return@let
            }
            it.setBackgroundColor(Color.WHITE) ///color
            it.description.isEnabled = false
            it.setTouchEnabled(true)
            it.setPinchZoom(true)//柱形图的横坐标缩放，

            val minScale = 2f // 最小缩放比例
            val maxScale = 10f // 最大缩放比例

            it.setVisibleXRangeMaximum(maxScale)
            it.setVisibleXRangeMinimum(minScale)
            it.setDrawGridBackground(false)//背景网格是否绘制
            it.maxHighlightDistance = 300f//设置高亮（Highlight）的最大距离


            it.isDragEnabled = true//是否启用拖动（drag）功能。
//                val m = Matrix()
//                m.postScale(1.5f, 1f)
//                it.viewPortHandler.refresh(m, it, false)
            setChartData(barValue.size, it)
            it.isScaleXEnabled = true  //支持x轴缩放
            it.isScaleYEnabled = false //支持Y轴缩放

            val x = it.xAxis
            x.granularity = 1f  //精准设置
            x.textColor = ContextCompat.getColor(context, R.color.col_92a)
            x.textSize = 9f
            x.axisMinimum = 0f

//                x.labelCount = 6
            x.isEnabled = true
            x.setDrawGridLines(false)  //不绘制y
            x.setDrawAxisLine(false)
            x.xOffset = 0.6f
            x.position = XAxis.XAxisPosition.BOTTOM
            x.setValueFormatter { value, axis ->
                var index = value.toInt()
                //Log.e("x轴", "$value")
                if (index < 0 || index >= barValue.size) {
                    ""
                } else {
                    "${(barValue[value.toInt()].data as MutableList<String>)[0]}"
                }
            }
            //y轴
            val y = it.axisLeft
            y.setLabelCountAndMaxMinValue(
                6,
                true,
                if (min - offset > 0f) min - offset else min,
                if (max >= 0f) max + offset else max
            )
            y.textColor = ContextCompat.getColor(context, R.color.col_92a)
            y.setDrawAxisLine(false)
            y.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
            y.gridColor = ContextCompat.getColor(context, R.color.col_92a)
            y.setGridDashedLine(DashPathEffect(floatArrayOf(5f, 5f), 0f))
            y.setDrawGridLines(true)  //绘制横者的x轴
            y.setDrawZeroLine(true)
            y.xOffset = 5f
            val markerView = ICompareMarkView(
                context, R.layout.mark_view_compare, unit,
                mark
            )
            it.marker = markerView
            markerView.chartView = it
            it.axisRight.isEnabled = false
            it.legend.isEnabled = false

            //   it.animateXY(2000, 2000)  //设置xy轴进入的动画
//                binding.mBarChart.moveViewToX(gbpBarValue[gbpBarValue.size - 1].x)
            val sets: java.util.ArrayList<IBarDataSet> = java.util.ArrayList()
            val set1 = BarDataSet(barValue, "DataSet 1")
            set1.setDrawValues(false) // 不显示值
            set1.valueTextColor = ContextCompat.getColor(context, R.color.col_9BDd)
            set1.highLightColor =
                ContextCompat.getColor(context, R.color.col_C6B)  //设置点后高亮颜色
            set1.color =
                ContextCompat.getColor(context, R.color.col_9BDd) //xian de yanse
            sets.add(set1)

            //--------------------------

            val set2 = BarDataSet(barValueCompare, "DataSet2")
            set2.valueTextColor = ContextCompat.getColor(context, R.color.col_8c6)
            set2.highLightColor =
                ContextCompat.getColor(context, R.color.col_8c6)  //设置点后高亮颜色
            set2.color =
                ContextCompat.getColor(context, R.color.col_9BD) //xian de yanse
            val data2 = BarData(set2)
            sets.add(set2)
            var d = BarData(sets)
            d.setValueTextSize(9f)
            d.setDrawValues(false)
            val spaceForBar: Float
            if (type == 2) {
                spaceForBar = 0.14f // 柱形图之间的间隔
                d.barWidth = 0.34f
            } else {
                spaceForBar = 0.14f // 柱形图之间的间隔
                d.barWidth = calculateBarWidth(d.dataSetCount)
            }
            d.groupBars(0f, spaceForBar, 0.03f)
            x.setCenterAxisLabels(true)
            x.axisMinimum = 0f //最小值 从0开始

            x.axisMaximum = barValueCompare.size.toFloat() //最大值


            val groupSpace = 0.2f
            val barSpace = 0.04f
            val barWidth = 0.36f
            //设置柱子宽度
            //关键的地方在于 需要满足该等式,标签才能居中：
            //(barSpace + barWidth) * 柱形图数量(比如我的是每组两个) + groupSpace = 1
            d.barWidth = barWidth
            //三个参数分别代表  X轴起点 组与组之间的间隔  组内柱子的间隔
            d.groupBars(0f, groupSpace, barSpace)


            it.data = d
            it.invalidate()
        }
    }

    fun setChartData(count: Int, mChart: BarChart) {
        val m = Matrix()
        m.postScale(scaleNum(count), 1f) //两个参数分别是x,y轴的缩放比例。例如：将x轴的数据放大为之前的1.5倍
        mChart.viewPortHandler.refresh(m, mChart, false) //将图表动画显示之前进行缩放
    }

    //30个横坐标时，缩放4f是正好的。
    private val scalePercent = 4f / 30f

    private fun scaleNum(xCount: Int): Float {
        return xCount * scalePercent
    }

    fun convertTimeToIndex(time: String, cur: Int, type: Int, showTime: String?): Int {
        var index = 0
        when (type) {
            1 -> {
                index = 0
            }

            2 -> {
                val split = showTime!!.split("至")
                val rangeStart = split[0]
                val rangeEnd = split[1]
                val formatter = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
                try {
                    val startDate = formatter.parse(rangeStart)
                    val endDate = formatter.parse(rangeEnd)
                    val inputDateObj = formatter.parse(time)
                    if (startDate == null || endDate == null || inputDateObj == null) {
                        LogUtils.w("data formatter result is null")
                        return 0
                    }
                    val calendar = Calendar.getInstance()
                    calendar.time = startDate
                    while (calendar.time <= endDate) {
                        if (calendar.time == inputDateObj) {
                            println("Index: $index")
                            break
                        }
                        calendar.add(Calendar.DATE, 1)
                        index++
                    }

                } catch (e: java.text.ParseException) {
                    e.printStackTrace()
                }
            }

            3 -> {
                // 将08-01格式转换为序号
                if (time.isNotEmpty()) {
                    val parts = time.split("-")
                    val month = parts[0].toInt()
                    val day = parts[1].toInt()
                    index = day - 1
                }
            }

            else -> {
                index = if (time.isDigitsOnly()) (time.toInt() - 1) else 0
            }
        }

        return if (index < 0) cur + 1 else index
    }


    fun initLineChartWithCompare(
        context: Context, min: Float, max: Float, chart: LineChart, lineValue: ArrayList<Entry>,
        lineValueCompare: ArrayList<Entry>, markerView: MarkerView
    ) {
        chart.let {
            it.clear()
            it.setNoDataText(context.getString(R.string.line_chart_not_data))
            it.setNoDataTextColor(ContextCompat.getColor(context, R.color.col_455))
            it.setLayerType(View.LAYER_TYPE_SOFTWARE, null)

            it.setBackgroundColor(Color.WHITE) ///color
            it.description.isEnabled = false
            it.setTouchEnabled(true)

            it.setScaleEnabled(true)
            it.setPinchZoom(false)

            val minScale = 2f // 最小缩放比例
            val maxScale = 10f // 最大缩放比例

            it.setVisibleXRangeMaximum(maxScale)
            it.setVisibleXRangeMinimum(minScale)
            it.setDrawGridBackground(false)
            it.maxHighlightDistance = 300f

            it.isDragEnabled = true
            val m = Matrix()
            m.postScale(0.5f, 1f)
            it.viewPortHandler.refresh(m, it, false)
            it.isScaleXEnabled = true                 //支持x轴缩放
            it.isScaleYEnabled = false

            //注释x轴换行显示
            it.extraBottomOffset = 3 * 9f
            it.setXAxisRenderer(
                CustomXAxisRenderer(
                    it.viewPortHandler,
                    it.xAxis,
                    it.getTransformer(YAxis.AxisDependency.LEFT)
                )
            )
//            x.labelCount = lineList.size
//            x.textSize = 9f

            val x = it.xAxis
            x.granularity = 1f  //精准设置

            x.textColor = ContextCompat.getColor(context, R.color.col_92a)
            x.isEnabled = true
            x.setDrawGridLines(false)  //不绘制y
            x.setDrawAxisLine(false)
            x.position = XAxis.XAxisPosition.BOTTOM
            x.setAvoidFirstLastClipping(false)
            x.setValueFormatter { value, axis ->
                val index = value.toInt()
                //Log.e("x轴", "$value")
                if (index < 0 || index >= lineValue.size) {
                    ""
                } else {
                    "${(lineValue[value.toInt()].data as MutableList<String>)[0]}"
                }
            }
            //y轴
            val y = it.axisLeft
            y.setLabelCountAndMaxMinValue(6, false, min - 1, max + 1)
            y.textColor = ContextCompat.getColor(context, R.color.col_92a)
            y.setDrawAxisLine(false)
            y.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
            y.gridColor = ContextCompat.getColor(context, R.color.col_92a)
            y.setGridDashedLine(DashPathEffect(floatArrayOf(5f, 5f), 0f))
            y.setDrawGridLines(true)  //绘制横者的x轴
            y.setDrawZeroLine(true)

            it.marker = markerView
            markerView.chartView = it


            it.axisRight.isEnabled = false
            it.legend.isEnabled = false

            //   it.animateXY(2000, 2000)  //设置xy轴进入的动画
            it.invalidate()
        }

    }

    /**
     * isShadow 是否需要阴影
     */
    fun setLineDataStyleOne(
        context: Context, values: List<Entry>?,
        lineChartList: LineChart, lineWidth: Float, circleRadius: Float, isShadow: Boolean
    ): LineDataSet {
        val lineDataSet: LineDataSet
        if (lineChartList.data != null && lineChartList.data.dataSetCount > 0) {
            lineDataSet = lineChartList.data.getDataSetByIndex(0) as LineDataSet
            lineDataSet.values = values
            lineChartList.data.notifyDataChanged()
            lineChartList.notifyDataSetChanged()
        } else {
            // create a dataset and give it a type
            lineDataSet = LineDataSet(values, values.toString())
            lineDataSet.mode = LineDataSet.Mode.LINEAR
            lineDataSet.cubicIntensity = 0.2f
            if (isShadow) {
                lineDataSet.setDrawFilled(true)
                // 分段后，数据若有一个点需要显示
                lineDataSet.setDrawCircles(values?.size == 1)
            } else {
                lineDataSet.setDrawFilled(false)
                lineDataSet.setDrawCircleHole(false)

            }
            lineDataSet.lineWidth = lineWidth

            lineDataSet.circleRadius = circleRadius
            lineDataSet.highLightColor =
                ContextCompat.getColor(context, R.color.col_e0b)  //设置点后高亮颜色
            lineDataSet.enableDashedHighlightLine(10f, 5f, 0f)
            lineDataSet.setCircleColor(
                ContextCompat.getColor(
                    context,
                    R.color.col_41c
                )
            )    //#41C4AF
            lineDataSet.color =
                ContextCompat.getColor(context, R.color.col_9BDd) //xian de yanse
            //set1.setFillColor(Color.WHITE);
//            set1.fillAlpha = 100
            if (isShadow) {
                val drawable = ContextCompat.getDrawable(context, R.drawable.shape_curve)
                lineDataSet.fillDrawable = drawable
                lineDataSet.fillAlpha = 100
            }
            lineDataSet.setDrawHorizontalHighlightIndicator(false)
            lineDataSet.fillFormatter =
                IFillFormatter { _, _ -> lineChartList.axisLeft.axisMinimum }
            lineDataSet.setValueFormatter { value, _, _, _ ->
                "$value"
            }
            if (isShadow) {
                val data = LineData(lineDataSet)
                //data.setValueTypeface(tfLight)
                data.setValueTextSize(9f)
                data.setDrawValues(false)
            }

        }
        return lineDataSet
    }

    fun setLineDataStyleTwo(
        context: Context,
        values: List<Entry>?,
        lineChartList: LineChart
    ): LineDataSet {
        val lineDataSet: LineDataSet
        if (lineChartList.data != null && lineChartList.data.dataSetCount > 0) {
            lineDataSet = lineChartList.data.getDataSetByIndex(0) as LineDataSet
            lineDataSet.values = values
            lineChartList.data.notifyDataChanged()
            lineChartList.notifyDataSetChanged()
        } else {
            // create a dataset and give it a type
            lineDataSet = LineDataSet(values, values.toString())
            lineDataSet.mode = LineDataSet.Mode.LINEAR
            lineDataSet.cubicIntensity = 0.2f
            lineDataSet.setDrawFilled(false)
            lineDataSet.lineWidth = 2.5f
            lineDataSet.setDrawCircleHole(false)
            lineDataSet.circleRadius = 3.5f
            lineDataSet.highLightColor =
                ContextCompat.getColor(context, R.color.col_e0b)  //设置点后高亮颜色
            lineDataSet.enableDashedHighlightLine(10f, 5f, 0f)
            lineDataSet.setCircleColor(
                ContextCompat.getColor(
                    context,
                   R.color.col_9BD
                )
            )    //#41C4AF
            lineDataSet.color =
                ContextCompat.getColor(context, R.color.col_9BD) //xian de yanse
            //set1.setFillColor(Color.WHITE);
//            set1.fillAlpha = 100
            lineDataSet.setDrawHorizontalHighlightIndicator(false)
            lineDataSet.fillFormatter =
                IFillFormatter { _, _ -> lineChartList.axisLeft.axisMinimum }
            lineDataSet.setValueFormatter { value, _, _, _ ->
                "$value"
            }

        }
        return lineDataSet
    }


}