package com.zj365.health.act.exception

import android.content.Context
import android.view.View
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
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.IAxisValueFormatter
import com.github.mikephil.charting.highlight.Highlight
import com.tamsiree.rxkit.RxTimeTool
import com.xty.common.arouter.ARouterUrl
import com.zj365.health.R
import com.zj365.health.fragment.BaseSleepStatisticFrag
import com.zj365.health.vm.ExceptionVm
import com.xty.network.model.ExceptionBean
import java.text.SimpleDateFormat
import kotlin.math.max
import kotlin.math.min

/**
 *  血压异常数据
 */
@Route(path = ARouterUrl.XUEYA_EXCEPTION_DATA_ACT)
class XueyaExceptionDataAct : BaseExceptionDataAct<ExceptionVm>() {
    var xueyaHighResult = mutableListOf<ExceptionBean>()
    var xueyaLowResult = mutableListOf<ExceptionBean>()
    override fun getUnit(): String {
        return "mmHg"
    }

    override fun getHint(): String {
        return ""
    }


    override fun initView() {
        super.initView()
        binding.tvHint.visibility = View.GONE
        binding.llHint.visibility = View.VISIBLE
    }

    override fun initData() {
        super.initData()
        result?.let {
            for (exceptionBean in it) {
                val split = exceptionBean.data.split("/")
                val high = split[0]
                val low = split[1]
                var highData = ExceptionBean(exceptionBean.index, high, exceptionBean.time)
                xueyaHighResult.add(highData)
                var lowData = ExceptionBean(exceptionBean.index, low, exceptionBean.time)
                xueyaLowResult.add(lowData)
            }
        }
    }

    override fun initBarChart() {
        binding.mBarChart.let { chart ->
            chart.setOnChartValueSelectedListener(this)

            chart.getDescription().setEnabled(false)

            // if more than 60 entries are displayed in the chart, no values will be
            // drawn

            // if more than 60 entries are displayed in the chart, no values will be
            // drawn
            chart.setMaxVisibleValueCount(40)

            // scaling can now only be done on x- and y-axis separately

            // scaling can now only be done on x- and y-axis separately
            chart.setPinchZoom(false)

            chart.setDrawGridBackground(false)
            chart.setDrawBarShadow(false)

            chart.setDrawValueAboveBar(false)
            chart.setHighlightFullBarEnabled(true)

            // change the position of the y-labels

            // change the position of the y-labels
            val leftAxis: YAxis = chart.getAxisLeft()
//            leftAxis.valueFormatter = MyAxisValueFormatter()
//            leftAxis.setAxisLineWidth(dp2px(5).toFloat())
            chart.getAxisRight().setEnabled(false)

        }

        val values1 = java.util.ArrayList<BarEntry>()
        val values2 = java.util.ArrayList<BarEntry>()


        result.reverse()
        xueyaHighResult.reverse()
        xueyaHighResult.reverse()
        for (i in 0 until xueyaHighResult.size) {
            var sleepStatistcBean = xueyaHighResult.get(i)
            var data = BarEntry(i.toFloat(), sleepStatistcBean.data.toFloat())
            values1.add(data)
        }
        for (i in 0 until xueyaLowResult.size) {
            var sleepStatistcBean = xueyaLowResult.get(i)
            var data = BarEntry(i.toFloat(), sleepStatistcBean.data.toFloat())
            values2.add(data)
        }
        binding.mBarChart.apply {
//
            val dataSet = BarDataSet(values1, "")
            dataSet.color = resources.getColor(R.color.col_9BDd)
            dataSet.setDrawValues(false)
            var legend = getLegend();
            legend.setEnabled(false); // 隐藏颜色标签

            val dataSet1 = BarDataSet(values2, "")
            dataSet1.color = resources.getColor(R.color.col_96D)
            dataSet1.setDrawValues(false)
            var legend1 = getLegend();
            legend1.setEnabled(false); // 隐藏颜色标签

            xAxis.setCenterAxisLabels(true);
            var groupSpace = 0.1f
            var barSpace = 0.1f
            var barWidth = 0.35f
            if (values1.size <= 1) {
                barWidth = 0.1f
                barSpace = 0.1f
                groupSpace = 0.7f
            }
            //(barSpace + barWidth) * 柱形图数量(比如我的是每组两个) + groupSpace = 1
            var barData = BarData(dataSet, dataSet1)
            barData.barWidth = barWidth
            val spaceForBar =groupSpace // 柱形图之间的间隔
//            barData.barWidth =calculateBarWidth(barData.dataSetCount)
            barData.groupBars(0f, spaceForBar, barSpace)
            data = barData
            getXAxis().setAxisMinimum(0f);

            setScaleYEnabled(false)
            xAxis.position = XAxis.XAxisPosition.BOTTOM
            xAxis.setDrawGridLines(false)
            xAxis.labelCount = values1.size
            xAxis.setAxisMinimum(0f);                               //最小值 从0开始
            xAxis.setAxisMaximum(values1.size.toFloat());

            //最大值
//            xAxis.enableGridDashedLine(10f, 10f, 0f);
//            xAxis.setGridColor(R.color.col_0F2);
            val leftAxis: YAxis = getAxisLeft()
            leftAxis.axisMinimum = 0f // 将Y轴最小值设置为


            if (values1.size > 7) {
//                //倍率可以根据实际情况而定
                setScaleMinima(3.5f, 1.0f);
            } else {
                setScaleMinima(0.5f, 1.0f);
            }

                leftAxis.setGridColor(resources.getColor(R.color.col_0F2));
            leftAxis.setDrawAxisLine(false);  // 隐藏左侧Y轴线
            leftAxis.setDrawLabels(true);     // 显示左侧Y轴标签文字
            leftAxis.textColor = resources.getColor(R.color.col_c7c)
            leftAxis.setLabelCountAndMaxMinValue(6,false,0f,180f)
//            leftAxis.mAxisMaximum = 10f
            dataSet.setValueFormatter(BaseSleepStatisticFrag.MyYAxisValueFormatter(context))
//            xAxis.labelRotationAngle = getRotate()
            xAxis.valueFormatter =
                IAxisValueFormatter { value, axis ->
                    val index = value.toInt()
                    if (index >= 0 && index < result.size) {
                        RxTimeTool.milliseconds2String(
                            result.get(index).time.toLong() * 1000,
                            SimpleDateFormat("HH:mm")
                        )+" " +
                                RxTimeTool.milliseconds2String(
                                    result.get(index).time.toLong() * 1000,
                                    SimpleDateFormat("MM-dd"))

                    } else ""
                }
            xAxis.granularity = 1f

            val markerView =
                CustomMarkerViewXueya(
                    this@XueyaExceptionDataAct,
                    R.layout.custom_marker_view1, result
                )
            setMarker(markerView)



            setPinchZoom(false); // 禁止缩放
            setDoubleTapToZoomEnabled(false); // 禁止双击缩放
            setExtraOffsets(0f,0f,0f,20f)
            invalidate()

        }
    }

    override fun setLabelCount(leftAxis: YAxis) {

    }

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

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

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

    class CustomMarkerViewXueya(
        context: Context?,
        layoutResource: Int,
        var result: MutableList<ExceptionBean>
    ) :
        MarkerView(context, layoutResource) {
        private val mData: TextView
        private val mTime: TextView

        override fun refreshContent(e: Entry, highlight: Highlight) {
            // 在 refreshContent 方法中设置需要显示的内容。
            val barEntry = e as BarEntry
            val x = barEntry.x
            val get = result.get(x.toInt())
            var data = get.data + "mmHg"

            mData.setText(data)
            mTime.setText(
                RxTimeTool.milliseconds2String(
                    get.time.toLong() * 1000,
                    SimpleDateFormat("HH :mm")
                )
            )
            setOffset((-getWidth() / 2).toFloat(), (-getHeight()).toFloat() - 10f);
        }

        init {
            // 在构造函数中获取 MarkerView 中的 TextView。
            mData = findViewById<View>(R.id.tvData) as TextView
            mTime = findViewById<View>(R.id.tvTime) as TextView

        }
    }

    override fun getRangeMaxmum(): Float {
        return 0f
    }

    override fun getRangeMinmum(): Float {
        return 0f
    }

}