package com.zj365.health.fragment

import android.content.Context
import android.graphics.RectF
import android.view.View
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.github.mikephil.charting.charts.BarChart
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.formatter.IValueFormatter
import com.github.mikephil.charting.highlight.Highlight
import com.github.mikephil.charting.listener.OnChartValueSelectedListener
import com.github.mikephil.charting.utils.ViewPortHandler
import com.xty.base.fragment.BaseVmFrag
import com.xty.common.TimeUtils
import com.zj365.health.R
import com.zj365.health.act.HealthMainAct
import com.zj365.health.databinding.FragSleepStaticsWeekMonYearBinding
import com.zj365.health.vm.SleepVm
import com.xty.network.model.SleepStatistcBean


abstract class BaseSleepStatisticFrag<T: SleepVm>  : BaseVmFrag<SleepVm>(),

    OnChartValueSelectedListener {
    val binding by lazy { FragSleepStaticsWeekMonYearBinding.inflate(layoutInflater) }
    var id :String?  = ""
    var date :String?  = ""
    var type  = 2
    var defaultDate  = TimeUtils.getCurrentTime()
    var isDemonstrate: Boolean = false

    override fun setViewModel() = SleepVm()

    override fun initView() {
        super.initView()
        initChart()
        isDemonstrate = (requireActivity() as HealthMainAct).isDemonstrate
        id = arguments?.getString("id")
        if ( id.isNullOrEmpty()){
            id = ""
        }
        getData(defaultDate,isDemonstrate)
    }
    var lineValue = arrayListOf<Entry>()  //曲线数据

    open fun getData(date: String, isDemonstrate: Boolean) {
        mViewModel.getSleepStatistic(id,type,date,"",isDemonstrate)
    }

    override fun setLayout(): View = binding.root

    override fun observer() {
        mViewModel.sleeStatisticpLive.observe(this) {

            if (it.data == null) {
                return@observe
            }
            setChartData(it.data)
            update()
        }
    }

    fun update(){
        parentFragmentData?.let {
            if (it is SleepFrag){
                val sleepFrag = it as SleepFrag
                this.view?.let { it1 -> sleepFrag.updatePagerHeightForChild(it1) }
            }
        }
    }

    var parentFragmentData: Fragment?=null
    fun setParentFragment(parentFragment: Fragment?) {
        parentFragmentData = parentFragment
    }
    fun setChartData(statistcBean :SleepStatistcBean) {
        val values = java.util.ArrayList<BarEntry>()
        var mutableList = statistcBean.list


        statistcBean.avg?.let {
            var allTimeStr = TimeUtils.secToStrMinutes((it.toLong()))
            var content = context?.getString(R.string.sleep_time, allTimeStr[0], allTimeStr[1])
            binding.mChartInfo.mSleepTime.text = content
        }

        for (i in 0 until mutableList.size) {
            var sleepStatistcBean = mutableList.get(i)
            val val1 = sleepStatistcBean.deep?.toFloat()?.div(60)
            val val2= sleepStatistcBean.light?.toFloat()?.div(60)
            val1?.let {  data1 ->
                val2?.let { data2 ->
                    var data =  BarEntry(i.toFloat(), floatArrayOf(data1,data2))
                    values.add(data)
                }
            }

        }

        binding.mChartInfo.mBarChart.apply {
//
            val dataSet = BarDataSet(values,"")
            dataSet.setColors(getColors())
            dataSet.setDrawValues(false)
            var legend = getLegend();
            legend.setEnabled(false); // 隐藏颜色标签
            val barData = BarData(dataSet)
            barData.barWidth = getBarWidth()

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



            setData(barData)

            xAxis.position = XAxis.XAxisPosition.BOTTOM
            xAxis.setDrawGridLines(false)
            xAxis.labelCount = values.size
//            xAxis.enableGridDashedLine(10f, 10f, 0f);
//            xAxis.setGridColor(R.color.col_0F2);
            val leftAxis: YAxis = getAxisLeft()
            leftAxis.axisMinimum = 0f // 将Y轴最小值设置为

            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.mAxisMaximum = 10f
            dataSet.setValueFormatter(MyYAxisValueFormatter(context))
//            xAxis.labelRotationAngle = getRotate()
            xAxis.valueFormatter =
                IAxisValueFormatter { value, axis ->
                    val index = value.toInt()
                    if (index >= 0 && index < mutableList.size) {
                        mutableList.get(index).date?.let {
                            getXLable(it)
                        }
                    } else ""
                }
            xAxis.granularity =  1f

            val markerView = CustomMarkerView(activity, R.layout.custom_marker_view)
            setMarker(markerView)



            setPinchZoom(false); // 禁止缩放
            setDoubleTapToZoomEnabled(false); // 禁止双击缩放
            invalidate()

        }
    }

    open fun needZoom(): Boolean {
        return false
    }

    fun zoomChart(chart:BarChart){

    }
    open fun getBarWidth(): Float {
        return 0.3f
    }


    abstract fun getXLable(date:String):String
    enum class SleepEnum(var type:Int){
        WEEK(2),
        MONTH(3),
        YEAR(4),
    }
    private fun initChart() {
        binding.mChartInfo.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(false)

            // 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)

        }
    }

    /**
     * 修正数据  不要毫秒 要的秒
     */
    private fun getSecondTime(time: Long): Long {
        if (time > 9999999999) {
            return time / 1000
        }
        return time
    }

    fun getColors(): List<Int> {

        val colors = arrayOf(resources.getColor(R.color.col_9BDd),resources.getColor(R.color.col_3EA))
        return colors.toList()
    }

    class MyYAxisValueFormatter(var context:Context) : IValueFormatter {

        override fun getFormattedValue(
            value: Float,
            entry: Entry?,
            dataSetIndex: Int,
            viewPortHandler: ViewPortHandler?
        ): String {
            val all = value * 60
            var allTimeStr = TimeUtils.secToStrMinutes((all.toLong()))
            val content = context.getString(R.string.sleep_time, allTimeStr[0], allTimeStr[1])
            return content
        }
    }
    override fun onValueSelected(entry: Entry?, h: Highlight?) {
        entry?.let {
            val barEntry = it as BarEntry
            val bounds: RectF = binding.mChartInfo.mBarChart.getBarBounds(barEntry)
            val y = bounds.bottom -10f // 在柱状图顶部留出一点空隙
            val highlight: Highlight = Highlight(barEntry.x, y, 0)
            if (y == 0f){
                return
            }
            binding.mChartInfo.mBarChart.highlightValue(highlight, false) // 显
        }

    }

    override fun onNothingSelected() {
    }
    class CustomMarkerView(context: Context?, layoutResource: Int) : MarkerView(context, layoutResource) {
        private val mDeep: TextView
        private val mLight: TextView
        override fun refreshContent(e: Entry, highlight: Highlight) {
            // 在 refreshContent 方法中设置需要显示的内容。
            val barEntry = e as BarEntry
            val deepData = barEntry.yVals[0]
            val lightData = barEntry.yVals[1]
//
            String.format("%.1f", lightData)
            String.format("%.1f", deepData)
            mLight.setText( String.format("%.1f", lightData)+"小时")
            mDeep.setText( String.format("%.1f", deepData )+"小时")
            setOffset((-getWidth() / 2).toFloat(), (-getHeight()).toFloat() -10f);
        }

        init {
            // 在构造函数中获取 MarkerView 中的 TextView。
            mDeep= findViewById<View>(R.id.tvDeep) as TextView
            mLight = findViewById<View>(R.id.tvLight) as TextView
        }
    }
}