package com.zj365.health.fragment

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.DashPathEffect
import android.graphics.Matrix
import android.graphics.RectF
import android.graphics.Typeface
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.bigkoo.pickerview.adapter.ArrayWheelAdapter
import com.blankj.utilcode.util.TimeUtils
import com.contrarywind.view.WheelView
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.IValueFormatter
import com.github.mikephil.charting.highlight.Highlight
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet
import com.github.mikephil.charting.listener.OnChartValueSelectedListener
import com.github.mikephil.charting.utils.MPPointF
import com.github.mikephil.charting.utils.ViewPortHandler
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.tamsiree.rxkit.RxTimeTool
import com.xty.base.fragment.BaseVmFrag
import com.xty.common.TimeSelectCompare
import com.xty.common.util.SpannableUtils
import com.xty.common.weight.tablayout.TabEntity
import com.xty.common.weight.tablayout.listener.CustomTabEntity
import com.xty.common.weight.tablayout.listener.OnTabSelectListener
import com.zj365.health.R
import com.zj365.health.adapter.CompareAdapter
import com.zj365.health.databinding.FragSleepCompareDataBinding
import com.zj365.health.databinding.SleepChartInfoLinechartBinding
import com.zj365.health.vm.SleepCompareVm
import com.zj365.health.weight.SleepCompareMarkView
import com.xty.network.model.ValueMap
import com.xty.network.model.SleepCompareBean
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
import kotlin.math.max
import kotlin.math.min


/**
 *  睡眠数据对比
 */
@Suppress("NAME_SHADOWING")
class SleepCompareDataFrag  : BaseVmFrag<SleepCompareVm>() ,
    OnChartValueSelectedListener {
    private var week: Int = 1//默认点击时间是选择时间还是对比时间 1，选择， 2 对比
    val binding by lazy { FragSleepCompareDataBinding.inflate(layoutInflater) }
    val adapter by lazy { CompareAdapter() }

    //    var bean= mutableListOf<SleepCompareBean>()
    val fomartStr by lazy { arrayOf("HH:mm", "HH:mm", "MM-dd", "MM-dd", "yy-MM") }
    val contentStr by lazy { arrayOf("日期", "总时长", "深睡时长", "浅睡时长", "清醒次数") }
    val contentStrNew by lazy {
        arrayOf(
            "日期",
            "累计天数",
            "平均时长",
            "最长时长",
            "最短时长",
            "平均深睡",
            "平均浅睡",
            "睡眠不足",
            "睡眠过多"
        )
    }

    val weeker by lazy { arrayOf("周一", "周二", "周三", "周四", "周五", "周六", "周日") }

    private val mTabEntities: ArrayList<CustomTabEntity> = ArrayList()
    private val mTitles = arrayOf(
        "日", "周", "月", "年"
    )

//    var barValue = arrayListOf<BarEntry>()  //柱形数据
//    var barValueCompare = arrayListOf<BarEntry>()  //柱形数据
    var id: String = ""
    var type = 1

    var dayDate = ""
    var weekDate = ""
    var mouthDate = ""
    var yearDate = ""
    private var timeSelect : TimeSelectCompare? = null
    private var timeSelectCompare : TimeSelectCompare? = null

    private var timeMonthSelect : TimeSelectCompare? = null

    private  var timeMonthSelectCompare: TimeSelectCompare? = null

    var timeYearSelect: TimeSelectCompare? = null

    var timeYearSelectCompare: TimeSelectCompare? = null


    private var bottomSheetDialog: BottomSheetDialog? = null

    @SuppressLint("SuspiciousIndentation")
    fun initBottomDialog() {
        if (bottomSheetDialog == null) {
            bottomSheetDialog = BottomSheetDialog(this.requireContext())
            bottomSheetDialog?.let { dialog ->
                val view = LayoutInflater.from(context).inflate(R.layout.bottom_sheet_layout, null)
                dialog.setContentView(view)
                val wheelView = view.findViewById<WheelView>(R.id.wheelView)
                wheelView.setCyclic(false)
                val list = buildWeekLower26();
                list.removeAt(0)
                wheelView.adapter = ArrayWheelAdapter(list)
                val windowHeight = (resources.displayMetrics.heightPixels * 0.6).toInt()
                dialog.behavior.peekHeight = windowHeight

                dialog.behavior.isHideable = false
                dialog.behavior.state = BottomSheetBehavior.STATE_EXPANDED

                val cancelButton = view.findViewById<TextView>(R.id.cancel_button)
                val confirmButton = view.findViewById<TextView>(R.id.confirm_button)

                cancelButton.setOnClickListener {
                    // 点击取消按钮的操作
                    dialog.dismiss()
                }

                confirmButton.setOnClickListener {
                    // 点击确定按钮的操作
                    val item = wheelView.adapter.getItem(wheelView.currentItem)
                    if (week == 1) {
                        binding.tvShowDate.text = item.toString()
                        weekDate = binding.tvShowDate.text.toString()
                        mViewModel.getXlData(
                            type,
                            binding.tvShowDate.text.toString(),
                            binding.tvHideDate.text.toString(), id
                        )
                    } else {
                        binding.tvHideDate.text = item.toString()
                        mViewModel.getXlData(
                            type,
                            binding.tvShowDate.text.toString(),
                            binding.tvHideDate.text.toString(), id
                        )
                    }
                    // 点击确定按钮的操作
                    dialog.dismiss()
                }
            }
        }
    }

    private fun buildWeekLower26(): MutableList<String> {
        val startDate = Calendar.getInstance()
        startDate.firstDayOfWeek = Calendar.MONDAY
        startDate.add(Calendar.YEAR, -1)
        val endDate = Calendar.getInstance()

        val dateRanges: MutableList<String> = ArrayList()
        var currentMonday = startDate.clone() as Calendar
        currentMonday.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY)

        while (currentMonday.before(endDate)) {
            val currentSunday = currentMonday.clone() as Calendar
            currentSunday.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY)

            val formattedDateRange =
                SimpleDateFormat("yyyy-MM-dd").format(currentMonday.time) + "至" + SimpleDateFormat(
                    "yyyy-MM-dd"
                ).format(
                    currentSunday.time
                )
            dateRanges.add(formattedDateRange)

            currentMonday.add(Calendar.WEEK_OF_YEAR, 1)
        }

        dateRanges.reverse()
        return dateRanges
    }

    override fun setLayout() = binding.root
    override fun initData() {
        super.initData()
        id = arguments?.getString("id").toString()
//        listdate = getXDate();
    }

    var listdate = ArrayList<String>()
    private fun initChart() {
        binding.mChartInfo.mBarChart.let { chart->
            chart.setOnChartValueSelectedListener(this)
            chart.description.isEnabled = 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)
            chart.setPinchZoom(false)
            chart.setDrawGridBackground(false)
            chart.setDrawBarShadow(false)
            chart.setDrawValueAboveBar(false)
            chart.isHighlightFullBarEnabled = false
            // change the position of the y-labels

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

        }
    }

    @SuppressLint("SimpleDateFormat")
    override fun initView() {
        super.initView()
        initTab()
        initChart()
        setTimeSelect()
        initRecycle()
        val calendar = Calendar.getInstance()
        binding.mChartInfo.mBarChart.setNoDataText(getString(R.string.line_chart_not_data))
        binding.mChartInfo.mBarChart.setNoDataTextColor(ContextCompat.getColor(requireContext(), R.color.col_455))
        binding.mChartInfo.title.visibility = View.GONE
        binding.mChartInfo.mSleepTime.visibility = View.GONE
        binding.mChartInfo.barDeepIv.setImageResource(R.mipmap.ic_shenshui)
        binding.mChartInfo.barLightIv.setImageResource(R.mipmap.ic_qianshui)

        binding.tvShowDate.setOnClickListener {
            when (type) {
                1 -> {
                    timeSelect?.selectTime(it, "yyyy-MM-dd")
                }
                2 -> {
                    week = 1
                    bottomSheetDialog?.show()
                }
                3 -> {
                    timeMonthSelect?.selectTimeWithYearMonth(it, "yyyy-MM")
                }
                4 -> {
                    timeYearSelect?.selectTimeWithYear(it, "yyyy")
                }
            }
        }

        binding.tvHideDate.setOnClickListener {
            when (type) {
                1 -> {
                    var calendar = Calendar.getInstance()
                    if (!TextUtils.isEmpty(timeSelect!!.selectTime)){
                        val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
                        val date = dateFormat.parse(timeSelect!!.selectTime )
                        if (date != null) {
                            calendar.time = date
                        }
                        calendar.add(Calendar.DAY_OF_YEAR, -1)

                    }else{
                        val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
                        val date = dateFormat.parse(binding.tvHideDate.text.toString())
                        if (date != null) {
                            calendar.time = date
                        }
                    }
                    timeSelectCompare!!.createPvTime(requireContext(),calendar,1) {
                        // 在选择时间后执行的逻辑
                        type = 1
//            dayDate = binding.tvHideDate.text.toString()
                        val selecCDate = binding.tvHideDate.text.toString()
                        mViewModel.getXlData(type,
                            binding.tvShowDate.text.toString(),
                            selecCDate  , id)
                    }
                    timeSelectCompare!!.selectTime(it, "yyyy-MM-dd" )
                }
                2 -> {
                    bottomSheetDialog?.show()
                    week = 2
                }
                3 -> {
                    var calendar = Calendar.getInstance()

                    val selectMonthDate = binding.tvShowDate.text.toString()
                    if (!TextUtils.isEmpty(selectMonthDate)){
                        val dateFormat = SimpleDateFormat("yyyy-MM", Locale.getDefault())
                        val date = dateFormat.parse(selectMonthDate)
                        if (date != null) {
                            calendar.time = date
                        }
                        if (  calendar!!.get(Calendar.MONTH) == Calendar.JANUARY) {
                            calendar.add(Calendar.YEAR, -1)
                            calendar.set(Calendar.MONTH, Calendar.DECEMBER)
                        }else {
                            calendar.add(Calendar.MONTH, -1)
                        }
                    }else{
                        val dateFormat = SimpleDateFormat("yyyy-MM", Locale.getDefault())
                        val date = dateFormat.parse(binding.tvHideDate.text.toString())
                        if (date != null) {
                            calendar.time = date
                        }
                    }


                    timeMonthSelectCompare!!.createPvTime(requireContext(),calendar ,3) {
                        // 在选择时间后执行的逻辑
                        type = 3
//                        mouthDate = binding.tvHideDate.text.toString()
                        mViewModel.getXlData(type,
                            binding.tvShowDate.text.toString()  ,
                            binding.tvHideDate.text.toString() , id)
                    }

                    timeMonthSelectCompare!!.selectTimeWithYearMonth(
                        it, "yyyy-MM"  )

                    // 如果当前月份是一月，将年份减一，并将月份设置为十二月
                }
                4 -> {
                    var calendar = Calendar.getInstance()

                    if (!TextUtils.isEmpty(timeYearSelect!!.selectTime)){
                        val dateFormat = SimpleDateFormat("yyyy", Locale.getDefault())
                        val date = dateFormat.parse(timeYearSelect!!.selectTime )
                        if (date != null) {
                            calendar.time = date
                        }
                        calendar.add(Calendar.YEAR, -1)
                    }else{
                        val dateFormat = SimpleDateFormat("yyyy", Locale.getDefault())
                        val date = dateFormat.parse(binding.tvHideDate.text.toString())
                        if (date != null) {
                            calendar.time = date
                        }
                    }
                    timeYearSelectCompare!!.createPvTime(requireContext(),calendar,4 ) {
                        // 在选择时间后执行的逻辑
                        type = 4
//                        mouthDate = binding.tvHideDate.text.toString()
                        mViewModel.getXlData(type,
                            binding.tvShowDate.text.toString()  ,
                            binding.tvHideDate.text.toString() , id)
                    }
                    timeYearSelectCompare!!.selectTimeWithYear(it, "yyyy")
                }
            }
        }
        initBottomDialog()
        mViewModel.getXlData(
            type,
            /* RxTimeTool.getCurTimeString(SimpleDateFormat("yyyy-MM-dd"))*/
            SimpleDateFormat("yyyy-MM-dd").format(getdateMunise(-1)),
            SimpleDateFormat("yyyy-MM-dd").format(getdateMunise(-2)), id
        )//TODO
    }

    private fun getdateMunise(int: Int): Date {
        val calendar = Calendar.getInstance()
        calendar.add(Calendar.DAY_OF_YEAR, int)
        return calendar.time
    }

    override fun setViewModel() = SleepCompareVm()
    private fun setViewShowOrHide(
        isShow: Boolean,
        mChartInfoCompare: SleepChartInfoLinechartBinding
    ) {
        mChartInfoCompare.mSleepTime.text= ""
        if (isShow){
            mChartInfoCompare.mStartAndEnd.visibility = View.VISIBLE
        } else {
            mChartInfoCompare.mSLeepShow.setData(0, mutableListOf())
            mChartInfoCompare.mStartAndEnd.visibility = View.GONE

        }
    }

    /**
     * 初始化时间选择器
     */
    @SuppressLint("SimpleDateFormat")
    private fun setTimeSelect() {

        var calendar = Calendar.getInstance()
        calendar.time = getdateMunise(-1)
        binding.tvShowDate.text = SimpleDateFormat("yyyy-MM-dd").format(calendar.time)
        binding.tvHideDate.text = SimpleDateFormat("yyyy-MM-dd").format(getdateMunise(-2))
        //日 的选择时间器
        timeSelect = TimeSelectCompare()
        timeSelect!!.createPvTime(requireContext(),calendar ,1) {
            // 在选择时间后执行的逻辑
            type = 1
            dayDate = binding.tvShowDate.text.toString()
            mViewModel.getXlData(type,
                dayDate,
                binding.tvHideDate.text.toString()  , id)
        }
        timeSelect!!.startDate.set(1922, 1, 1)
        timeSelect!!.endDate = calendar
        //日 的对比时间器
        timeSelectCompare = TimeSelectCompare()

//-------------------------------------------------月
        calendar = Calendar.getInstance()
        val dateFormat = SimpleDateFormat("yyyy-MM", Locale.getDefault())
        dateFormat.format(calendar.time)
        if ( calendar.get(Calendar.MONTH) == Calendar.JANUARY) {
            calendar.add(Calendar.YEAR, -1)
            calendar.set(Calendar.MONTH, Calendar.DECEMBER)
        }else {
            calendar.add(Calendar.MONTH, -1)
        }
        timeMonthSelect = TimeSelectCompare()
        timeMonthSelect!!.createPvTime(requireContext(),calendar ,3) {
            // 在选择时间后执行的逻辑
            type = 3
            mouthDate = binding.tvHideDate.text.toString()
            mViewModel.getXlData(type,
                binding.tvShowDate.text.toString()  ,
                binding.tvHideDate.text.toString() , id)
            timeMonthSelect?.selectTimeWithYearMonth( binding.tvShowDate, "yyyy-MM")
        }
        timeMonthSelect!!.startDate.set( Calendar.YEAR ,1922 )
        timeMonthSelect!!.startDate.set( Calendar.MONTH  , 1)
        timeMonthSelect!!.endDate = calendar


        calendar.add(Calendar.MONTH, -1)
        //月 的对比时间器
        timeMonthSelectCompare = TimeSelectCompare()
        timeMonthSelectCompare!!.startDate.set( Calendar.YEAR ,1922 )
        timeMonthSelectCompare!!.startDate.set( Calendar.MONTH  , 1)
        timeMonthSelectCompare!!.endDate = calendar
//-------------------------------------------------年
        val calendaryear = Calendar.getInstance()
        val lastYear = SimpleDateFormat("yyyy", Locale.getDefault()).format(calendaryear.time)
        val date = lastYear.format(calendaryear.time )
        timeYearSelect = TimeSelectCompare()
        timeYearSelect!!.createPvTime(requireContext(),calendaryear ,4) {
            // 在选择时间后执行的逻辑
            type = 4
            mouthDate = binding.tvHideDate.text.toString()
            mViewModel.getXlData(type,
                binding.tvShowDate.text.toString()  ,
                binding.tvHideDate.text.toString() , id)
            timeYearSelect?.selectTimeWithYearMonth( binding.tvShowDate, "yyyy")
        }

        timeYearSelect!!.startDate.set( Calendar.YEAR ,1922 )
        timeYearSelect!!.endDate = calendaryear
        //年 的对比时间器
        timeYearSelectCompare = TimeSelectCompare()
        calendaryear.add(Calendar.YEAR, -1)
        timeYearSelectCompare!!.createPvTime(requireContext(),calendaryear,4) {
            // 在选择时间后执行的逻辑
            type = 4
//            dayDate = binding.tvHideDate.text.toString()
            mViewModel.getXlData(type,
                binding.tvShowDate.text.toString(),
                binding.tvHideDate.text.toString()  , id)
        }
        timeYearSelectCompare!!.startDate.set( Calendar.YEAR ,1922 )
        timeYearSelectCompare!!.endDate = calendaryear

    }
    /**
     * 修正数据  不要毫秒 要的秒
     */
    private fun getSecondTime(time: Long): Long {
        if (time > 9999999999) {
            return time / 1000
        }
        return time
    }
    @SuppressLint("SetTextI18n", "SimpleDateFormat")
    override fun observer() {
        mViewModel.dataLive.observe(this) {
//            var list  =  it.data.model
//            var modelCompare  =  it.data.model
//            var list= mutableListOf<SleepCompareBean>()
//             adapter.setNewInstance(it.data.compareModel)

            if (type == 1) {
                it.data.sleepMap.let { model ->
                    if (model.model.startTime == 0) {
                        setViewShowOrHide(false, binding.mChartInfoDay)
                        return@let
                    }
                    setViewShowOrHide(true,binding.mChartInfoDay )
                    setdata(it.data.sleepMap,model.model,binding.mChartInfoDay  )
                }
                it.data.sleepCompareMap.let { model ->
                    if (model.model.startTime == 0) {
                        setViewShowOrHide(false, binding.mChartInfoCompare )
                        return@let
                    }
                    setViewShowOrHide(true,binding.mChartInfoCompare )
                    setdata(it.data.sleepCompareMap, model.model, binding.mChartInfoCompare  )
                }
            } else {
                if ((it.data.sleepMap.list == null || it.data.sleepMap.list.size == 0) && (it.data.sleepCompareMap.list == null || it.data.sleepCompareMap.list.size == 0)) {
                } else {

//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        when (type) {
                            1 -> {//日

                            }

                            2 -> {//周
//                                var split = binding.tvShowDate.text.toString().split("至")
//                                var start = split[0]
//                                var end = split[1]
//                                it.data.sleepMap.list =
//                                    it.data.fillMissingData(it.data.sleepMap.list, start, end)
//                                split = binding.tvHideDate.text.toString().split("至")
//                                start = split[0]
//                                end = split[1]
//                                it.data.sleepCompareMap.list =
//                                    it.data.fillMissingData(
//                                        it.data.sleepCompareMap.list,
//                                        start,
//                                        end
//                                    )
                            }

                            3 -> {//月
                                it.data.sleepMap.list = it.data.fillMissingDataNewMonth(
                                    it.data.sleepMap.list,binding.tvShowDate.text.toString()
                                )
                                it.data.sleepCompareMap.list = it.data.fillMissingDataNewMonth(
                                    it.data.sleepCompareMap.list,binding.tvHideDate.text.toString()
                                )
                            }

                            4 -> {//年
                                it.data.sleepMap.list =
                                    it.data.fillMissingData(it.data.sleepMap.list)
                                it.data.sleepCompareMap.list =
                                    it.data.fillMissingData(it.data.sleepCompareMap.list)
                            }
                        }
//                    }
                }
                setChartdata(it.data)
            }
            binding.comprehensiveContent.text = it.data.comprehensiveContent
            setAvgInfo(it.data)
        }
    }

    @SuppressLint("SetTextI18n")
    private fun setdata(
        sleepMap: SleepCompareBean.Value,
        model: SleepCompareBean.ModelDay,
        mChartInfoDay: SleepChartInfoLinechartBinding,
    ) {

        var allTimeSecond = ( model.endTime.toLong() -( model.startTime.toLong()))/60
        var sleepTimeSecond =( model.deepSleepTotal +  model.lightSleepTotal).toLong()
        var soberTimeSecond = (allTimeSecond - sleepTimeSecond)*60
        var allTimeStr =
            com.xty.common.TimeUtils.secToStrMinutes(sleepTimeSecond)//总睡眠时间

//        var lightSleep = model.model.lightSleepTotal
//                    max(model.deepSleepTotal, model.lightSleepTotal)//浅睡时长
//        var deepSleep = model.model.deepSleepTotal
//                    min(model.deepSleepTotal, model.lightSleepTotal)//深睡时长

        val content = getString(R.string.sleep_time, allTimeStr[0], allTimeStr[1])

        mChartInfoDay.mSleepTime.text = SpannableUtils.setStrSpan(content, 23,
            getColor(R.color.black), Typeface.BOLD,0, allTimeStr[0].length,
            content.length - 1 - allTimeStr[1].length, content.length - 1)


        mChartInfoDay.apply {
            var previousTime = 0L //上一个数据的结束时间 用以判断是否为清醒
            var allSleepTime = 0  //总睡眠时间含清醒时间  从开始睡觉-早上起床的时长
            var listTime = mutableListOf< SleepCompareBean.ModelDayItem>()
            var totalSoberSleepTime = 0L//清醒时间是分钟
             sleepMap.value.forEachIndexed { index, value ->
                if (index == 0) {
                    listTime.add(value)
                } else {
                    if (previousTime + 1 == getSecondTime(value.sleepStartTime)) {  //上次结束时间加一分钟为这次开始的时间表示中间无清醒
                        listTime.add(value)
                    } else {  // 清醒了
                        //计算清醒的数据 并插入（原始数据中并没有清醒数据 所以这里需要计算并插入清醒数据）
                        var soberSleepTime =
                            (getSecondTime(value.sleepStartTime) - previousTime).toInt() - 1
                        var bean = SleepCompareBean.ModelDayItem(
                            soberSleepTime,//清醒时长
                            previousTime + 1,//计算清醒开始时间
                            999
                        )
                        totalSoberSleepTime += soberSleepTime
                        //还要加清醒时间的时间段
                        allSleepTime += soberSleepTime //单位 秒

                        listTime.add(bean)
                        //添加原来的数据
                        listTime.add(value)
                    }

                }
                previousTime =
                    getSecondTime(value.sleepStartTime) + value.sleepLen //上一条数据的睡眠结束时间
                allSleepTime += value.sleepLen //单位 秒

            }
            if (listTime.isEmpty()) {
                mSLeepShow.visibility = View.GONE
            } else {
                mSLeepShow.setData(allSleepTime, listTime,1)
                mSLeepShow.visibility = View.VISIBLE

            }

            mStart.text = "入睡${
                RxTimeTool.milliseconds2String(
                     model.startTime  * 1000.toLong(),
                    SimpleDateFormat("HH:mm")
                )
            }"
            mEnd.text = "起床${
                RxTimeTool.milliseconds2String(
                     model.endTime * 1000.toLong(),
                    SimpleDateFormat("HH:mm")
                )
            }"

        }
    }
    private fun initTab() {

        val currentDay = Date()
        dayDate = TimeUtils.date2String(currentDay, "yyyy-MM-dd")
//        weekDate = "${TimeUtils.date2String(getDateAdd(6), "yyyy-MM-dd")}至$dayDate"
        mouthDate = TimeUtils.date2String(currentDay, "yyyy-MM")
        yearDate = TimeUtils.date2String(currentDay, "yyyy")
        mTabEntities.clear()
        mTitles.forEach {
            mTabEntities.add(
                TabEntity(
                    it, android.R.drawable.ic_delete, android.R.drawable.ic_delete
                )
            )
        }
        binding.commonTabLayout.setTabData(mTabEntities)
        binding.commonTabLayout.setOnTabSelectListener(object : OnTabSelectListener {
            @SuppressLint("SetTextI18n")
            override fun onTabSelect(position: Int) {
                binding.commonTabLayout.currentTab = position

                when (position) {
                    0 -> {
                        type = 1
                        binding.showTitle.text  = "选择日期"
                        binding.hideTitle.text  = "对比日期"
                        binding.tvShowDate.text =
                            SimpleDateFormat("yyyy-MM-dd").format(getdateMunise(-1))
                        binding.tvHideDate.text =
                            SimpleDateFormat("yyyy-MM-dd").format(getdateMunise(-2))
                        mViewModel.getXlData(
                            type,
                            /* RxTimeTool.getCurTimeString(SimpleDateFormat("yyyy-MM-dd"))*/
                            binding.tvShowDate.text.toString(),
                            binding.tvHideDate.text.toString(), id
                        )
                        binding.mChartInfoDay.sleepViewParent.visibility =View.VISIBLE
                        binding.mChartInfoCompare.sleepViewParent.visibility =View.VISIBLE
                        binding.mChartInfo.barParent.visibility = View.GONE
                        binding.point2.visibility =View.GONE
                        binding.point1.visibility =View.GONE
                    }

                    1 -> {
                        binding.showTitle.text  = "选择周"
                        binding.hideTitle.text  = "对比周"
                        binding.point2.visibility =View.VISIBLE
                        binding.point1.visibility =View.VISIBLE
                        type = 2
                        binding.tvShowDate.text = getPreviousWeekDateRange(1)
                        binding.tvHideDate.text = getPreviousWeekDateRange(2)
                        mViewModel.getXlData(
                            type,
                            /* RxTimeTool.getCurTimeString(SimpleDateFormat("yyyy-MM-dd"))*/
                            binding.tvShowDate.text.toString(),
                            binding.tvHideDate.text.toString(), id
                        )
                        binding.mChartInfo.barParent.visibility = View.VISIBLE
                        binding.mChartInfoDay.sleepViewParent.visibility =View.GONE
                        binding.mChartInfoCompare.sleepViewParent.visibility =View.GONE
                    }

                    2 -> {
                        binding.showTitle.text  = "选择月"
                        binding.hideTitle.text  = "对比月"
                        binding.point2.visibility =View.VISIBLE
                        binding.point1.visibility =View.VISIBLE
                        binding.tvShowDate.text = getPreviousMonthDateRange(1)
                        binding.tvHideDate.text = getPreviousMonthDateRange(2)
                        type = 3
                        mViewModel.getXlData(
                            type,
                            /* RxTimeTool.getCurTimeString(SimpleDateFormat("yyyy-MM-dd"))*/
                            binding.tvShowDate.text.toString(),
                            binding.tvHideDate.text.toString(), id
                        )
                        binding.mChartInfo.barParent.visibility = View.VISIBLE
                        binding.mChartInfoDay.sleepViewParent.visibility =View.GONE
                        binding.mChartInfoCompare.sleepViewParent.visibility =View.GONE

                    }

                    3 -> {
                        binding.showTitle.text  = "选择年"
                        binding.hideTitle.text  = "对比年"
                        binding.point2.visibility =View.VISIBLE
                        binding.point1.visibility =View.VISIBLE
                        val calendar = Calendar.getInstance()
                        calendar.add(Calendar.YEAR, -1)
                        val lastYear =
                            SimpleDateFormat("yyyy", Locale.getDefault()).format(calendar.time)
                        binding.tvShowDate.text = yearDate
                        binding.tvHideDate.text = lastYear
                        type = 4
                        mViewModel.getXlData(
                            type,
                            /* RxTimeTool.getCurTimeString(SimpleDateFormat("yyyy-MM-dd"))*/
                            binding.tvShowDate.text.toString(),
                            binding.tvHideDate.text.toString(), id
                        )
                        binding.mChartInfo.barParent.visibility = View.VISIBLE
                        binding.mChartInfoDay.sleepViewParent.visibility =View.GONE
                        binding.mChartInfoCompare.sleepViewParent.visibility =View.GONE
                    }
                }
//                mViewModel.getXlData(type, binding.tvShowDate.text.toString(), id)TODO
            }

            override fun onTabReselect(position: Int) {
            }

        })

    }

    /**
     * 获取上个月  monthCount 月数
     */
    fun getPreviousMonthDateRange(monthCount: Int): String {
        val calendar = Calendar.getInstance()
        calendar.add(Calendar.MONTH, -monthCount)

        val dateFormat = SimpleDateFormat("yyyy-MM", Locale.getDefault())
        val previousMonth = dateFormat.format(calendar.time)

        return previousMonth
    }

    /**
     * 获取上周的礼拜 周数
     */
    fun getPreviousWeekDateRange(weekCount: Int): String {
        val calendar = Calendar.getInstance()
        calendar.firstDayOfWeek = Calendar.MONDAY

        val currentDate = calendar.time

        val startOfWeek = calendar.clone() as Calendar
        startOfWeek.add(Calendar.WEEK_OF_YEAR, -weekCount)
        startOfWeek.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY)

        val endOfWeek = calendar.clone() as Calendar
        endOfWeek.add(Calendar.WEEK_OF_YEAR, -weekCount)
        endOfWeek.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY)

        val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        val startDate = dateFormat.format(startOfWeek.time)
        val endDate = dateFormat.format(endOfWeek.time)

        return startDate + "至$endDate"
    }

    private fun setChartdata(data: SleepCompareBean) {
        val values = java.util.ArrayList<BarEntry>()
        val valuesCompare = java.util.ArrayList<BarEntry>()
        val list = data.sleepMap.list
        val listCompare = data.sleepCompareMap.list
//        barValue.clear()
//        barValueCompare.clear()
        var rever: IntProgression = if (list.size < listCompare.size) {
            (listCompare.indices).reversed()
        } else {
            (list.indices).reversed()
        }
        if (type == 3) {
            var compare = listCompare.size - list.size
            if (compare > 0) {
                for (Int in 1..compare) {
                    list.add(list.size, SleepCompareBean.Model(listCompare[list.size].date, "0","0",0))
                }
            } else if (compare < 0) {
                compare = 0 - compare
                for (Int in 1..compare) {
                    listCompare.add(
                        listCompare.size,
                        SleepCompareBean.Model(list[listCompare.size].date, "0","0",0)
                    )
                }
            }
        }

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

        if (list.size>0) {
            for (i in 0 until list.size) {
                val val1 = list[i].deep?.toFloat()?.div(60)
                val val2 = list[i].light?.toFloat()?.div(60)
                val val1Compare = listCompare[i].deep.toFloat().div(60)
                val val2Compare = listCompare[i].light.toFloat().div(60)
                var listTipY = mutableListOf<String>()

                when (type) {
                    2 -> {
                        listTipY.add(weeker[i])
                        listTipY.add(val1.toString())
                        listTipY.add(val2.toString())
                        listTipY.add(val1Compare.toString())
                        listTipY.add(val2Compare.toString())
                        val1?.let { data1: Float ->
                            val2?.let { data2: Float ->
                                var data =
                                    BarEntry(i.toFloat(), floatArrayOf(data1, data2), listTipY)
                                values.add(data)
                            }
                        }

                        val1Compare?.let { data1: Float ->
                            val2Compare?.let { data2: Float ->
                                var data1 =
                                    BarEntry(i.toFloat(), floatArrayOf(data1, data2), listTipY)
                                valuesCompare.add(data1)
                            }
                        }

                    }

                    3 -> {
                        listTipY.add(list[i].date)
                        listTipY.add(val1.toString())
                        listTipY.add(val2.toString())
                        listTipY.add(val1Compare.toString())
                        listTipY.add(val2Compare.toString())
                        val1?.let { data1: Float ->
                            val2?.let { data2: Float ->
                                var data =
                                    BarEntry(i.toFloat(), floatArrayOf(data1, data2), listTipY)
                                values.add(data)
                            }
                        }

                        val1Compare?.let { data1: Float ->
                            val2Compare?.let { data2: Float ->
                                var data1 =
                                    BarEntry(i.toFloat(), floatArrayOf(data1, data2), listTipY)
                                valuesCompare.add(data1)
                            }
                        }
                    }

                    4 -> {
                        listTipY.add(list[i].date)
                        listTipY.add(val1.toString())
                        listTipY.add(val2.toString())
                        listTipY.add(val1Compare.toString())
                        listTipY.add(val2Compare.toString())
                        val1?.let { data1: Float ->
                            val2?.let { data2: Float ->
                                var data =
                                    BarEntry(i.toFloat(), floatArrayOf(data1, data2), listTipY)
                                values.add(data)
                            }
                        }
                        val1Compare?.let { data1: Float ->
                            val2Compare?.let { data2: Float ->
                                var data1 =
                                    BarEntry(i.toFloat(), floatArrayOf(data1, data2), listTipY)
                                valuesCompare.add(data1)
                            }
                        }
                    }


                }
            }
        }
        binding.mChartInfo.mBarChart.isScaleYEnabled = false
        binding.mChartInfo.mBarChart.apply {
//
            if (values.size == 0 && valuesCompare.size == 0) {
                binding.mChartInfo.mBarChart.clear()
                return@apply
            }
            val sets: java.util.ArrayList<IBarDataSet> = java.util.ArrayList()

            val dataSet = BarDataSet(values, "1")
            dataSet.colors = getColors()
            dataSet.setDrawValues(false)
            val legend = legend;
            legend.isEnabled = false; // 隐藏颜色标签
            sets.add(dataSet)
//            if (needZoom()) {
//                if (values.size > 15) {
//                    //倍率可以根据实际情况而定
//                    setScaleMinima(3.5f, 1.0f);
//                } else {
//                    setScaleMinima(0.5f, 1.0f);
//                }
//            }
            val dataSet1 = BarDataSet(valuesCompare, "2")
            dataSet1.colors = getColorsCompare()
            dataSet1.setDrawValues(false)
            legend.isEnabled = false; // 隐藏颜色标签
            sets.add(dataSet1)
            val d = BarData(sets)
            val spaceForBar: Float
            if (type == 3) {
                spaceForBar = 0.16f // 柱形图之间的间隔
                d.barWidth = calculateBarWidth(d.dataSetCount)
            } else {
                spaceForBar = 0.14f // 柱形图之间的间隔
                d.barWidth = 0.34f

            }
            d.groupBars(0f, spaceForBar, 0.03f)
            setChartData(values.size, binding.mChartInfo.mBarChart)

            setData(d)
            xAxis.position = XAxis.XAxisPosition.BOTTOM
            xAxis.setDrawGridLines(false)
//            xAxis.labelCount = values.size
//            xAxis.axisMinimum = 0f
//            xAxis.enableGridDashedLine(10f, 10f, 0f);
//            xAxis.setGridColor(R.color.col_0F2);
            val leftAxis: YAxis = axisLeft
            leftAxis.axisMinimum = 0f // 将Y轴最小值设置为
            leftAxis.gridColor = 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.valueFormatter = MyYAxisValueFormatter(context)
//            xAxis.label
            xAxis.setValueFormatter { value, axis ->
                var index = value.toInt()
                //Log.e("x轴", "$value")
                if (index < 0 || index >= values.size) {
                    ""
                } else {
                    (values[value.toInt()].data as MutableList<String>)[0]
                }
            }
            leftAxis.setGridDashedLine(DashPathEffect(floatArrayOf(5f, 5f), 0f))
            leftAxis.setLabelCount(6, false)
            xAxis.granularity = 1f
            axisRight.isEnabled = false
            axisLeft.setDrawGridLines(false)
            setTouchEnabled(true)
            setScaleEnabled(true)
//            zoom(scaleX, 1f, 0f, 0f)

            val markerView =
                SleepCompareMarkView(activity, R.layout.custom_marker_view_compare)
            marker = markerView
            markerView.chartView = this


            setPinchZoom(false); // 禁止缩放
            isDoubleTapToZoomEnabled = false; // 禁止双击缩放

            //--------------------------------------------------
            xAxis.setCenterAxisLabels(true)
            xAxis.axisMinimum = 0f //最小值 从0开始
            xAxis.axisMaximum = values.size.toFloat() //最大值

            val groupSpace = 0.2f
            val barSpace = 0.04f
            val barWidth = 0.36f
            //设置柱子宽度
            //关键的地方在于 需要满足该等式,标签才能居中：
            //(barSpace + barWidth) * 柱形图数量(比如我的是每组两个) + groupSpace = 1

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

            invalidate()

        }
    }

    @SuppressLint("SuspiciousIndentation")
    private fun setAvgInfo(valueData: SleepCompareBean) {
        var list: MutableList<ValueMap> = mutableListOf()
        list = if (type == 1) {
            setdataListDay(contentStr, valueData.sleepMap, valueData.sleepCompareMap, list)

        } else {
            setdataList(contentStrNew, valueData.sleepMap, valueData.sleepCompareMap, list)

        }
//        for (i in contentStr.indices) {

//        }
        adapter.setNewInstance(list)

    }

    private fun setdataList(
        contentStr: Array<String>,
        valueData: SleepCompareBean.Value,
        valueDataCompare: SleepCompareBean.Value,
        list: MutableList<ValueMap>
    ): MutableList<ValueMap> {
        // 标题头
        val data0 = ValueMap().apply {
            title = contentStr[0]
            if (type == 2) {
                var tv1 = binding.tvHideDate.text.toString()
                var tvarray = tv1.split("至")
                tv1 = tvarray[0].substring(5, tvarray[0].length)
                valueCompare = "对比周\n$tv1"
                tv1 = tvarray[1].substring(5, tvarray[0].length)
                valueCompare += "至$tv1"

                tv1 = binding.tvShowDate.text.toString()
                tvarray = tv1.split("至")
                tv1 = tvarray[0].substring(5, tvarray[0].length)
                value = "选择周\n$tv1"
                tv1 = tvarray[1].substring(5, tvarray[0].length)
                value += "至 $tv1"
            } else {
                when (type) {
                    3 -> {//月
                        valueCompare = "对比月\n" + binding.tvHideDate.text
                        value = "选择月\n" + binding.tvShowDate.text
                    }
                    4 -> {//年
                        valueCompare = "对比年\n" + binding.tvHideDate.text
                        value = "选择年\n" + binding.tvShowDate.text
                    }
                    else -> {//日
                        valueCompare = "对比日期\n" + binding.tvHideDate.text
                        value = "选择日期\n" + binding.tvShowDate.text
                    }
                }
            }
            state = 0

        }
        list.add(data0)


        //累计次数
        val data1 = ValueMap().apply {
            title = contentStr[1]
            state =
                if (valueData.count.toInt() > valueDataCompare.count.toInt()) 1 else if (valueData.count.toInt() < valueDataCompare.count.toInt()) 2 else if (valueData.count.toInt() == 0 && valueDataCompare.count.toInt() == 0) 3 else 0
            valueCompare = valueDataCompare.count + "天"
            value = valueData.count + "天"

        }
        list.add(data1)
        //平均时长
        val data2 = ValueMap().apply {
            title = contentStr[2]
            valueCompare = formatMinutesToHoursAndMinutes(valueDataCompare.avg.toInt())
            value = formatMinutesToHoursAndMinutes(valueData.avg.toInt() )
            state =
                if (valueData.avg.toInt() > valueDataCompare.avg.toInt()) 1 else if (valueData.avg.toInt() < valueDataCompare.avg.toInt()) 2 else 0

        }
        //最长时长
        list.add(data2)
        val data3 = ValueMap().apply {
            title = contentStr[3]
            valueCompare =   formatMinutesToHoursAndMinutes(valueDataCompare.max.toInt())
            value =  formatMinutesToHoursAndMinutes(valueData.max.toInt() )
            state =
                if (valueData.max.toInt() > valueDataCompare.max.toInt()) 1 else if (valueData.max.toInt() < valueDataCompare.max.toInt()) 2 else 0

        }
        //最短时长
        list.add(data3)
        val data4 = ValueMap().apply {
            title = contentStr[4]
            valueCompare =  formatMinutesToHoursAndMinutes(valueDataCompare.min.toInt() )
            value = formatMinutesToHoursAndMinutes(valueData.min.toInt() )
            state =
                if (valueData.min.toInt() > valueDataCompare.min.toInt()) 1 else if (valueData.min.toInt() < valueDataCompare.min.toInt()) 2 else 0

        }
        //平均深睡

        list.add(data4)
        val data5 = ValueMap().apply {
            title = contentStr[5]
            valueCompare = formatMinutesToHoursAndMinutes(valueDataCompare.deepAvg.toInt() )
            value =formatMinutesToHoursAndMinutes( valueData.deepAvg.toInt())
            state =
                if (valueData.deepAvg.toInt() > valueDataCompare.deepAvg.toInt()) 1 else if (valueData.deepAvg.toInt() < valueDataCompare.deepAvg.toInt()) 2 else 0

        }
        //平均浅睡
        list.add(data5)
        val data6 = ValueMap().apply {
            title = contentStr[6]
            valueCompare =  formatMinutesToHoursAndMinutes(valueDataCompare.lightAvg.toInt() )
            value = formatMinutesToHoursAndMinutes( valueData.lightAvg.toInt())
            state =
                if (valueData.lightAvg.toInt() > valueDataCompare.lightAvg.toInt()) 1 else if (valueData.lightAvg.toInt() < valueDataCompare.lightAvg.toInt()) 2 else 0

        }
        //睡眠不足
        list.add(data6)
        val data7 = ValueMap().apply {
            title = contentStr[7]
            valueCompare = valueDataCompare.sleepLackCount + "次"
            value = valueData.sleepLackCount + "次"
            state =
                if (valueData.sleepLackCount.toInt() > valueDataCompare.sleepLackCount.toInt()) 1 else if (valueData.sleepLackCount.toInt() < valueDataCompare.sleepLackCount.toInt()) 2 else 0

        }
        //睡眠过多
        list.add(data7)
        val data8 = ValueMap().apply {
            title = contentStr[8]
            valueCompare = valueDataCompare.sleepMuchCount + "次"
            value = valueData.sleepMuchCount + "次"
            state =
                if (valueData.sleepMuchCount .toInt() >valueDataCompare.sleepMuchCount.toInt()) 1 else if (valueData.sleepMuchCount.toInt() < valueDataCompare.sleepMuchCount.toInt()) 2 else 0

        }
        list.add(data8)
        return list
    }

    private fun setdataListDay(
        contentStr: Array<String>,
        valueData: SleepCompareBean.Value,
        valueDataCompare: SleepCompareBean.Value,
        list: MutableList<ValueMap>
    ): MutableList<ValueMap> {
        // 标题头
        val data0 = ValueMap().apply {
            title = contentStr[0]
            if (type==2){
                var tv1=  binding.tvHideDate.text.toString()
                var tvarray=  tv1.split("至")
                tv1= tvarray[0].substring(5,tvarray[0].length)
                valueCompare = "对比日期\n$tv1"
                tv1= tvarray[1].substring(5,tvarray[0].length)
                valueCompare += "至$tv1"

                tv1=  binding.tvShowDate.text.toString()
                tvarray=  tv1.split("至")
                tv1= tvarray[0].substring(5,tvarray[0].length)
                value = "选择日期\n$tv1"
                tv1= tvarray[1].substring(5,tvarray[0].length)
                value += "至$tv1"
            }else{
                valueCompare = "对比日期\n" + binding.tvHideDate.text
                value = "选择日期\n" + binding.tvShowDate.text
            }
            state = 0

        }
        list.add(data0)

        //总时长
        val data1 = ValueMap().apply {
            title = contentStr[1]
            val n = valueData.model.deepSleepTotal.toInt() + valueData.model.lightSleepTotal.toInt()
            val m =  valueDataCompare.model.deepSleepTotal.toInt()+valueDataCompare.model.lightSleepTotal.toInt()

            valueCompare = formatMinutesToHoursAndMinutes( m)
            value =  formatMinutesToHoursAndMinutes(n)
            state =
                if (n > m) 1 else if (n < m) 2  else 0

        }
        list.add(data1)
        //深睡时长
        val data2 = ValueMap().apply {
            title = contentStr[2]
            valueCompare = formatMinutesToHoursAndMinutes(valueDataCompare.model.deepSleepTotal.toInt())
            value = formatMinutesToHoursAndMinutes(valueData.model.deepSleepTotal.toInt())
            state =
                if (valueData.model.deepSleepTotal.toInt() > valueDataCompare.model.deepSleepTotal.toInt()) 1 else if (valueData.model.deepSleepTotal.toInt() < valueDataCompare.model.deepSleepTotal.toInt()) 2 else 0

        }
        list.add(data2)
        //浅睡时长
        val data3 = ValueMap().apply {
            title = contentStr[3]
            valueCompare = formatMinutesToHoursAndMinutes(valueDataCompare.model.lightSleepTotal.toInt())
            value = formatMinutesToHoursAndMinutes(valueData.model.lightSleepTotal.toInt())
            state =
                if (valueData.model.lightSleepTotal.toInt () > valueDataCompare.model.lightSleepTotal.toInt()) 1 else if (valueData.model.lightSleepTotal.toInt() < valueDataCompare.model.lightSleepTotal.toInt()) 2 else 0

        }
        list.add(data3)
        //清醒次数
        val data5 = ValueMap().apply {
            title = contentStr[4]
            val n = valueData.model.soberSleepCount;
            val m = valueDataCompare.model.soberSleepCount
            value = n.toString() + "次"
            valueCompare = m.toString() + "次"
            state = if (n > m) 1 else if (n < m) 2 else 0

        }
        list.add(data5)

        return list
    }
    private 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
    }
    private fun getListSize(value: List<SleepCompareBean.ModelDayItem>): String {
        var i = 0
        for (element in value) {
            if (element.sleepType == 999) {
                i++
            }
        }
        return "$i"
    }
    private fun setdataBarChart(){

    }

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

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

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

    fun initRecycle() {
        binding.mRecycle.layoutManager = LinearLayoutManager(requireContext())
        binding.mRecycle.adapter = adapter

    }
    fun formatMinutesToHoursAndMinutes(minutes: Int): String {
        val hours = minutes / 60
        val remainingMinutes = minutes % 60
        return  "${hours}小时${remainingMinutes}分"
    }

    fun getColors(): List<Int> {

        val colors = arrayOf(resources.getColor(R.color.col_9BDd),resources.getColor(R.color.col_3EA))
        return colors.toList()
    }
    fun getColorsCompare(): List<Int> {
        val colors = arrayOf(resources.getColor(R.color.col_EFF),resources.getColor(R.color.col_2FA))
        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 = com.xty.common.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() {
    }
    @SuppressLint("ViewConstructor")
    class CustomMarkerView(context: Context?, layoutResource: Int) : MarkerView(context, layoutResource) {
        private val mDeep: TextView
        private val mLight: TextView
        private val timeView: TextView

        init {
            // 使用inflate方法加载布局资源
            val view = View.inflate(context, layoutResource, null)
            mDeep = view.findViewById(R.id.tvDeep)
            mLight = view.findViewById(R.id.tvLight)
            timeView = view.findViewById(R.id.time)

            // 将初始化后的布局设置给MarkerView
            this.addView(view)
        }
        @SuppressLint("SetTextI18n")
        override fun refreshContent(e: Entry, highlight: Highlight) {
//            val barEntry = e as BarEntry
            var datas = e.data as MutableList<String>
            // 在 refreshContent 方法中设置需要显示的内容。
            timeView.text = datas[0]
            visibility  = View.VISIBLE
            mDeep.text = "深睡 "+String.format("%.1f", datas[1].toFloat())+"h  浅睡"+String.format("%.1f", datas[2].toFloat())+"h"
            mLight.text = "深睡 "+String.format("%.1f", datas[3].toFloat() )+"h  浅睡"+String.format("%.1f", datas[4].toFloat())+"h"
        }
        override fun getOffset(): MPPointF {
            // 偏移MarkerView以在图表上方显示
            return MPPointF((-width / 2).toFloat(), (-height - 10).toFloat())
        }

    }
}