package com.zj365.health.fragment

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.DashPathEffect
import android.graphics.Matrix
import android.os.Build
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.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.github.mikephil.charting.interfaces.datasets.ILineDataSet
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.LogUtils
import com.xty.common.TimeSelectCompare
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.FragXlCompareDataBinding
import com.zj365.health.vm.BreathCompareVm
import com.zj365.health.weight.ICompareMarkView
import com.xty.network.model.BreathCompareBean
import com.xty.network.model.ValueMap
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 BreathCompareDataFrag  : BaseVmFrag<BreathCompareVm>() {
    private var week: Int=1//默认点击时间是选择时间还是对比时间 1，选择， 2 对比
    val binding by lazy{ FragXlCompareDataBinding.inflate(layoutInflater)}
    val adapter by lazy{ CompareAdapter() }
//    var bean= mutableListOf<BreathCompareBean>()
    val fomartStr by lazy { arrayOf("HH:mm", "HH:mm", "MM-dd", "MM-dd", "yy-MM") }
    val contentStr by lazy { arrayOf("日期", "累计次数", "平均呼吸率", "最高呼吸率", "最低呼吸率","正常次数","呼吸过速","呼吸过缓") }
    val weeker by lazy { arrayOf("周一", "周二", "周三", "周四", "周五","周六", "周日" ) }

    private val mTabEntities: ArrayList<CustomTabEntity> = ArrayList()
    private val mTitles = arrayOf(
        "日", "周", "月", "年"
    )
    var lineValue = arrayListOf<Entry>()  //曲线数据
    var lineValueCompare = arrayListOf<Entry>()  //曲线数据

    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
    private var weekWheelView:WheelView? = 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)
                weekWheelView = view.findViewById<WheelView>(R.id.wheelView)
                weekWheelView?.setCyclic(false)
                val list = buildWeekLower26(null)
                list.removeAt(0)
                weekWheelView?.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 {
                    if (weekWheelView == null) {
                        return@setOnClickListener
                    }
                    // 点击确定按钮的操作
                    val item = weekWheelView!!.adapter.getItem(weekWheelView!!.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 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 buildWeekLower26(shouldEnd: Date?): MutableList<String> {
        val startDate = Calendar.getInstance()
        startDate.firstDayOfWeek = Calendar.MONDAY
        startDate.add(Calendar.YEAR, -1)
        val endDate = Calendar.getInstance()
        if (shouldEnd != null) {
            endDate.time = shouldEnd
        }
        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>()
    @SuppressLint("SimpleDateFormat")
    override fun initView() {
        super.initView()
        initTab()
        binding.mLineChart.setNoDataText(getString(R.string.line_chart_not_data))
        binding.mLineChart.setNoDataTextColor(
            ContextCompat.getColor(
                requireContext(),
                R.color.col_455
            )
        )
        setTimeSelect()
        initRecycle()


//        timeSelect?.setHide()?.setOnDismissListener{
//            binding.nestedScrollView.scrollTo(0,0)
//        }
//        timeSelectCompare?.setHide()?.setOnDismissListener{
//            binding.nestedScrollView.scrollTo(0,0)
//
//        }
//        timeMonthSelect.setHide().setOnDismissListener{
//            binding.nestedScrollView.scrollTo(0,0)
//        }
//        timeMonthSelectCompare.setHide().setOnDismissListener{
//            binding.nestedScrollView.scrollTo(0,0)
//        }
//        timeYearSelect.setHide().setOnDismissListener{
//            binding.nestedScrollView.scrollTo(0,0)
//        }
//        timeYearSelectCompare.setHide().setOnDismissListener{
//            binding.nestedScrollView.scrollTo(0,0)
//        }
        binding.tvShowDate.setOnClickListener {
            when (type) {
                1 -> {
                    timeSelect?.selectTime(it, "yyyy-MM-dd")
                }
                2 -> {
                    week = 1
                    val list = buildWeekLower26(null)
                    weekWheelView?.adapter = ArrayWheelAdapter(list)
                    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()
                        mViewModel.getXlData(type,
                            binding.tvShowDate.text.toString(),
                            binding.tvHideDate.text.toString()  , id)
                    }
                    timeSelectCompare!!.selectTime(it, "yyyy-MM-dd" )
                }
                2 -> {
                    val selectedDateStr = binding.tvShowDate.text
                    if(selectedDateStr!=null){
                        val selectedDateSpit = selectedDateStr.split("至")
                        selectedDateSpit.let { split ->
                            if (split.size >= 2) {
                                val selectedStartStr = split[0]
                                val list = buildWeekLower26(
                                    SimpleDateFormat("yyyy-MM-dd").parse(selectedStartStr)
                                )
                                weekWheelView?.adapter = ArrayWheelAdapter(list)
                            }
                        }
                    }
                    bottomSheetDialog?.show()
                    week = 2
                }
                3 -> {
                    var calendar = Calendar.getInstance()

                    timeMonthSelect!!.selectTime
                    if (!TextUtils.isEmpty(timeMonthSelect!!.selectTime)){
                        val dateFormat = SimpleDateFormat("yyyy-MM", Locale.getDefault())
                        val date = dateFormat.parse(timeMonthSelect!!.selectTime )
                        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()= BreathCompareVm ()

    override fun observer() {
        mViewModel.dataLive .observe(this){
//            var list  =  it.data.model
//            var modelCompare  =  it.data.model
//            var list= mutableListOf<BreathCompareBean>()
//             adapter.setNewInstance(it.data.compareModel)
            if (it.data.model.size == 0 && it.data.modelCompare.size == 0) {

            }else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    when (type) {
                        1 -> {//日
                            it.data.model = it.data.mapDataToTimeNodes(it.data.model)
                            it.data.modelCompare = it.data.mapDataToTimeNodes(it.data.modelCompare)
                        }

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

                        3 -> {//月
                            it.data.model = it.data.fillMissingData(
                                it.data.model,
                                binding.tvShowDate.text.toString()
                            )
                            it.data.modelCompare = it.data.fillMissingData(
                                it.data.modelCompare,
                                binding.tvHideDate.text.toString()
                            )
                        }

                        4 -> {//年
                            it.data.model = it.data.fillMissingData(it.data.model)
                            it.data.modelCompare = it.data.fillMissingData(it.data.modelCompare)
                        }
                    }
                }
            }
            setChartdata(it.data)
            binding.comprehensiveContent.text = it.data.comprehensiveContent
        }
    }
    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.mLineChart.visibility = View.VISIBLE
                        binding.mBarChart.visibility = View.GONE

                    }
                    1 -> {
                        binding.showTitle.text  = "选择周"
                        binding.hideTitle.text  = "对比周"
                        binding.tvShowDate.text = weekDate
                        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.mLineChart.visibility = View.GONE
                        binding.mBarChart.visibility = View.VISIBLE
                    }

                    2 -> {
                        binding.showTitle.text  = "选择月"
                        binding.hideTitle.text  = "对比月"
                        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.mLineChart.visibility = View.GONE
                        binding.mBarChart.visibility = View.VISIBLE

                    }
                    3 -> {
                        binding.showTitle.text  = "选择年"
                        binding.hideTitle.text  = "对比年"
                        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.mLineChart.visibility = View.GONE
                        binding.mBarChart.visibility = View.VISIBLE
                    }
                }
//                mViewModel.getXlData(type, binding.tvShowDate.text.toString(), id)TODO
            }

            override fun onTabReselect(position: Int) {
            }

        })

    }
    /**
     * 初始化时间选择器
     */
    @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

    }

    fun convertTimeToIndex(time: String): Int {
        // 将时间格式转换为小时和分钟
        val parts = time.split(":")
        val hours = parts[0].toInt()
        val minutes = parts[1].toInt()

        // 计算对应的分钟数
        val totalMinutes = hours * 60 + minutes

        // 计算对应的索引值
        val index = totalMinutes / 10

        return index
    }


    fun splitDataIntoSegments(dataList: MutableList<BreathCompareBean.Model>): MutableList<MutableList<BreathCompareBean.Model>> {
        val segments = mutableListOf<MutableList<BreathCompareBean.Model>>()
        var currentSegment = mutableListOf<BreathCompareBean.Model>()

        for (model in dataList) {
            if (model.value.toFloat().isNaN()) {
                // 遇到 Float.NaN，如果当前线段不为空，则添加到结果中，并开始新的线段
                if (currentSegment.isNotEmpty()) {
                    segments.add(currentSegment)
                    currentSegment = mutableListOf()
                }
            } else {
                // 遇到有效数据，将其添加到当前线段中
                currentSegment.add(model)
            }
        }

        // 将最后一个线段添加到结果中
        if (currentSegment.isNotEmpty()) {
            segments.add(currentSegment)
        }

        return segments
    }
    private fun checkData(segmentsCompare: MutableList<MutableList<BreathCompareBean.Model>>): MutableList<MutableList<BreathCompareBean.Model>> {
        if (segmentsCompare[0][0].time != "00:00"){
            val d = mutableListOf<BreathCompareBean.Model>()
            val b =  BreathCompareBean.Model("00:00",0f)
            d.add(b)
            segmentsCompare.add(d)
        }
        if (segmentsCompare[segmentsCompare.size-1][segmentsCompare[segmentsCompare.size-1].size-1].time != "23:50"){
            val d = mutableListOf<BreathCompareBean.Model>()
            val b =  BreathCompareBean.Model("23:50",0f)
            d.add(b)
            segmentsCompare.add(d)
        }

        return segmentsCompare
    }
    /**
     * 获取上个月  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"
    }
    lateinit var list :MutableList <BreathCompareBean.Model>
    private lateinit var listCompare:MutableList <BreathCompareBean.Model>


    private fun setChartdata(data: BreathCompareBean) {
        if (data == null) {
            return
        }
        setAvgInfo(data )
         list  =   data.model
        listCompare = data.modelCompare
        lineValue.clear()
        lineValueCompare.clear()
        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  ,BreathCompareBean.Model(listCompare[list.size].time,0f ))
                }
            }else if(compare<0){
                compare = 0-compare
                for (Int in 1  ..   compare) {
                    listCompare.add(listCompare.size  ,BreathCompareBean.Model(list[listCompare.size].time,0f ))
                }
            }
        }
        for (i in rever) {

//            if (selectDay()) {//如果是当天才操作
//                getOrganStatu(list[i].hrData)
//            }
//            var strTime:String
//            var times :Long
//            if (  list[i] !=null){
//                  times = list[i]!!.time.toLong() * 1000
//                 strTime = RxTimeTool.milliseconds2String(times, SimpleDateFormat(fomartStr[type]))
//            }else  {
//                times = listCompare[i]!!.time.toLong() * 1000
//                strTime = RxTimeTool.milliseconds2String(times, SimpleDateFormat(fomartStr[type]))
//            }

//            LogUtils.d("时间:$strTime")
            //中间两端在x轴显示尺度 其他情况下不显示
            if (type==1) {
                var listTipG = mutableListOf<String>()
                listTipG.add(list[list.size - 1 - i].time)
                listTipG.add("0")
                listTipG.add(list[list.size - 1 - i].value.toString() )
                listTipG.add( listCompare[listCompare.size - 1 - i].value.toString())
                if(list[list.size - 1 - i].value.toFloat()==0f) {
                    list[list.size - 1 - i].value= Float.NaN
                }
                else {
                    list[list.size - 1 - i].value.toFloat()
                }
                lineValue.add(
                    Entry(
                        (list.size - 1 - i).toFloat(),
                        list[list.size - 1 - i].value.toFloat() ,
                        listTipG
                    )
                )
//                }
//                if (listCompare[i].value==0){
//                    lineValueCompare.add(
//                        Entry(
//                            (listCompare.size - 1 - i).toFloat(),
//                            Float.NaN,
//                            listTipG
//                        )
//                    )
//                }else{
                if(listCompare[listCompare.size - 1 - i].value.toFloat()==0f)
                    listCompare[listCompare.size - 1 - i].value = Float.NaN
                else
                    listCompare[listCompare.size - 1 - i].value.toFloat()

                lineValueCompare.add(
                    Entry(
                        (listCompare.size - 1 - i).toFloat(),
                        listCompare[listCompare.size - 1 - i].value.toFloat(),
                        listTipG
                    )
                )
            }else if(type==2){
                var listTipW = mutableListOf<String>()
                listTipW.add(weeker[weeker.size-i-1])
                listTipW.add("0")
                listTipW.add(list[list.size - 1 - i].value.toString() )
                listTipW.add( listCompare[listCompare.size - 1 - i].value.toString())
                barValue.add(
                    BarEntry(
                        (list.size - 1 - i).toFloat(),
                        list[list.size - 1 - i].value.toFloat(),
                        listTipW

                    )
                )
                barValueCompare.add(
                    BarEntry(
                        (listCompare.size - 1 - i).toFloat(),
                        listCompare[listCompare.size - 1 - i].value.toFloat(),
                        listTipW
                    )
                )
            }else if(type==3){

                var listTipY = mutableListOf<String>()
                listTipY.add(list[list.size - 1 - i].time)
                listTipY.add("0")
                listTipY.add(list[list.size - 1 - i].value.toString() )
                listTipY.add( listCompare[listCompare.size - 1 - i].value.toString())
                barValue.add(
                    BarEntry(
                        (list.size - 1 - i).toFloat(),
                        list[list.size - 1 - i].value.toFloat(),
                        listTipY
                    )
                )
                barValueCompare.add(
                    BarEntry(
                        (listCompare.size - 1 - i).toFloat(),
                        listCompare[listCompare.size - 1 - i].value.toFloat(),
                        listTipY
                    )
                )
            }else{
                var listTipY = mutableListOf<String>()
                listTipY.add(list[list.size - 1 - i].time)
                listTipY.add("0")
                listTipY.add(list[list.size - 1 - i].value.toString() )
                listTipY.add( listCompare[listCompare.size - 1 - i].value.toString())
                barValue.add(
                    BarEntry(
                        (list.size - 1 - i).toFloat(),
                        list[list.size - 1 - i].value.toFloat(),
                        listTipY
                    )
                )
                barValueCompare.add(
                    BarEntry(
                        (listCompare.size - 1 - i).toFloat(),
                        listCompare[listCompare.size - 1 - i].value.toFloat(),
                        listTipY
                    )
                )
            }
        }
//        if (selectDay()) {//如果是当天才操作
//            setOrganStatu()
//        }
        binding.mLineChart.clear()
        binding.mBarChart.clear()
        val min :Float
        val max :Float
        if (data.value.min.toInt()==0&&data.value.compareMin.toInt()!=0){
            min = data.value.compareMin.toFloat()
        }else if(data.value.compareMin.toInt()==0&&data.value.min.toInt()!=0){
            min = data.value.min.toFloat()
        }else{
            min = min(data.value.min.toFloat(), data.value.compareMin.toFloat())
        }

        if (data.value.max.toInt()==0&&data.value.compareMax.toInt()!=0){
            max = data.value.compareMax.toFloat()
        }else if(data.value.compareMax.toInt()==0&&data.value.max.toInt()!=0){
            max = data.value.max.toFloat()
        }else{
            max =   max(data.value.max.toFloat(), data.value.compareMax.toFloat())
        }
//        if (type==1){
//            initChart(  min  ,max)
//        }else{
//            initChart(  9f  , 22f )
//        }
        initChart(  min  ,max)
    }

    @SuppressLint("SuspiciousIndentation")
    private fun setAvgInfo(valueData: BreathCompareBean) {
        var list: MutableList<ValueMap> = mutableListOf()
        list = setdataList(valueData.value, list)
//        for (i in contentStr.indices) {

//        }
             adapter.setNewInstance( list)

    }

    private fun setdataList(
        valueData: BreathCompareBean.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()>valueData.compareCount.toInt()) 1 else if (valueData.count.toInt()<valueData.compareCount.toInt()) 2 else 0
            valueCompare = valueData.compareCount+"次"
            value = valueData.count+"次"

        }
        list.add(data1)
        //平均心率
        val data2 =  ValueMap().apply {
            title = contentStr[2]
            valueCompare = valueData.compareAvg+"次/分"
            value = valueData.avg+"次/分"
            state = if (valueData.avg.toInt()>valueData.compareAvg.toInt()) 1 else if (valueData.avg.toInt()<valueData.compareAvg.toInt()) 2 else 0

        }
        //最高心率
        list.add(data2)
        val data3 =  ValueMap().apply {
            title = contentStr[3]
            valueCompare = valueData.compareMax+"次/分"
            value = valueData.max+"次/分"
            state = if (valueData.max.toInt()>valueData.compareMax.toInt()) 1 else if (valueData.max.toInt()<valueData.compareMax.toInt()) 2 else 0

        }
        //最低心率
        list.add(data3)
        val data4 =  ValueMap().apply {
            title =contentStr[4]
            valueCompare =  valueData.compareMin+"次/分"
            value =  valueData.min+"次/分"
            state = if (valueData.min.toInt()>valueData.compareMin.toInt()) 1 else if (valueData.min.toInt()<valueData.compareMin.toInt()) 2 else 0

        }
        //正常次数

        list.add(data4)
        val data5 = ValueMap().apply {
            title =contentStr[5]
            valueCompare =  valueData.compareNormal+"次"
            value = valueData.normal+"次"
            state = if (valueData.normal.toInt()>valueData.compareNormal.toInt()) 1 else if (valueData.normal.toInt()<valueData.compareNormal.toInt()) 2 else 0

        }
        //心动过速
        list.add(data5)
        val data6 =  ValueMap().apply {
            title =contentStr[6]
            valueCompare = valueData.tachypneaCompare.toString()+"次"
            value = valueData.tachypnea.toString()+"次"
            state = if (valueData.tachypnea.toInt()>valueData.tachypneaCompare.toInt()) 1 else if (valueData.tachypnea.toInt()<valueData.tachypneaCompare.toInt()) 2 else 0

        }
        //心动过缓
        list.add(data6)
        val data7 =  ValueMap().apply {
            title =contentStr[7]
            valueCompare =valueData.oligopneaCompare.toString()+"次"
            value = valueData.oligopnea.toString()+"次"
            state = if (valueData.oligopnea.toInt()>valueData.oligopneaCompare.toInt()) 1 else if (valueData.oligopnea.toInt()<valueData.oligopneaCompare.toInt()) 2 else 0

        }
        list.add(data7)
        return  list
    }

    private fun initChart(min: Float, max: Float) {
        if (type == 1) {
            binding.mLineChart.let {
                it.clear()
                it.setNoDataText(getString(R.string.line_chart_not_data))
                it.setNoDataTextColor(ContextCompat.getColor(requireContext(), 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(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(requireContext(), 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 ->
                    var 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.axisMaximum=max
//            y.axisMinimum=min
                y.setLabelCountAndMaxMinValue(6, false, min , max )
                y.textColor = ContextCompat.getColor(requireContext(), R.color.col_92a)
                y.setDrawAxisLine(false)
                y.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
                y.gridColor = ContextCompat.getColor(requireContext(), R.color.col_92a)
                y.setGridDashedLine(DashPathEffect(floatArrayOf(5f, 5f), 0f))
                y.setDrawGridLines(true)  //绘制横者的x轴
                y.setDrawZeroLine(true)


                var markerView = ICompareMarkView(
                    requireContext(), R.layout.mark_view_compare, "次/分",
                    ICompareMarkView.MarkPage.Breath
                )
                it.marker = markerView
                markerView.chartView = it
                it.axisRight.isEnabled = false
                it.legend.isEnabled = false

                //   it.animateXY(2000, 2000)  //设置xy轴进入的动画
                it.invalidate()
                if (!lineValue.isNullOrEmpty()) {
                    val barsetsNew: java.util.ArrayList<ILineDataSet> = java.util.ArrayList()

                    var segments  = splitDataIntoSegments(list)
                    if (segments.size>0) {
                        segments = checkData(segments)
                    }
                    val dataSets = segments.mapNotNull { segment ->
                        if (segment.isEmpty()) return@mapNotNull null

                        val entries = segment.mapIndexed { index, model ->
                            Entry(convertTimeToIndex(model.time).toFloat(), model.value,lineValue[convertTimeToIndex(model.time)].data)
                        }
                        return@mapNotNull setData(entries)
                    }
                    var segmentsCompare  = splitDataIntoSegments(listCompare)
                    if (segmentsCompare.size>0) {
                        segmentsCompare = checkData(segmentsCompare)
                    }
                    val dataSetsCompare = segmentsCompare.mapNotNull { segment ->
                        if (segment.isEmpty()) return@mapNotNull null

                        val entries = segment.mapIndexed { index, model ->
                            Entry(convertTimeToIndex(model.time).toFloat(), model.value,lineValueCompare[convertTimeToIndex(model.time)].data)
                        }
                        return@mapNotNull setData2(entries)
                    }
                    barsetsNew.addAll(dataSets)
                    barsetsNew.addAll(dataSetsCompare)
                    val lineData = LineData(barsetsNew)
                    lineData.setValueTextSize(9f)
                    lineData.setDrawValues(false)
                    it.data = lineData

                    it.moveViewToX(lineValue[lineValue.size - 1].x)
                }


            }
        }else{
            binding.mBarChart.let {
                it.clear()
                it.setNoDataText(getString(R.string.line_chart_not_data))
                it.setNoDataTextColor(ContextCompat.getColor(requireContext(), 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)//柱形图的横坐标缩放，

                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)
                it.isScaleXEnabled = true  //支持x轴缩放
                it.isScaleYEnabled = false //支持Y轴缩放

                val x = it.xAxis
                x.granularity = 1f  //精准设置
                x.textColor = ContextCompat.getColor(requireContext(), R.color.col_92a)
                x.textSize = 9f
                x.axisMinimum = 0f
                setChartData(barValue.size,it)
//                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]}"
                    }
                }
//                x.setValueFormatter { value, axis ->
//                    var index = value.toInt()
////                LogUtils.d("x轴:$value")
//                    if (index < 0 || index >= dbpBarValue.size) {
//                        ""
//                    } else {
//                        "${(dbpBarValue[value.toInt()].data as MutableList<String>)[0]}"
//                    }
//                }
                //y轴
                val y = it.axisLeft
                y.setLabelCountAndMaxMinValue(6, false, min, max)
                y.textColor = ContextCompat.getColor(requireContext(), R.color.col_92a)
                y.setDrawAxisLine(false)
                y.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
                y.gridColor = ContextCompat.getColor(requireContext(), R.color.col_92a)
                y.setGridDashedLine(DashPathEffect(floatArrayOf(5f, 5f), 0f))
                y.setDrawGridLines(true)  //绘制横者的x轴
                y.setDrawZeroLine(true)
                y.xOffset= 5f
                var markerView = ICompareMarkView(
                    requireContext(), R.layout.mark_view_compare, "次/分",
                    ICompareMarkView.MarkPage.Breath
                )
                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(requireContext(), R.color.col_9BDd)
                set1.highLightColor =
                    ContextCompat.getColor(requireContext(), R.color.col_C6B)  //设置点后高亮颜色
                set1.color = ContextCompat.getColor(requireContext(), R.color.col_9BDd) //xian de yanse
                sets.add(set1)

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

                val set2 = BarDataSet(barValueCompare, "DataSet2")
                set2.valueTextColor = ContextCompat.getColor(requireContext(), R.color.col_8c6)
                set2.highLightColor =
                    ContextCompat.getColor(requireContext(), R.color.col_8c6)  //设置点后高亮颜色
                set2.color = ContextCompat.getColor(requireContext(), R.color.col_9BD) //xian de yanse
                val data2 = BarData(set2)
                sets.add(set2)
//            sets.add(setBarData())
//            sets.add(setBarOtherData())
//            setLegend()min.toFloat()
//            setAxis()
                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

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

                binding.mBarChart.data = d
                binding.mBarChart.invalidate()

            }

        }
    }
    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))
    }
    private fun setData(values: List<Entry>?) :LineDataSet{

        val set1: LineDataSet
        if (binding.mLineChart!!.data != null && binding.mLineChart!!.data.dataSetCount > 0) {
            set1 = binding.mLineChart!!.data.getDataSetByIndex(0) as LineDataSet
            set1.values = values
            binding.mLineChart!!.data.notifyDataChanged()
            binding.mLineChart!!.notifyDataSetChanged()
        } else {
            // create a dataset and give it a type
            set1 = LineDataSet(values, "DataSet 1")
            set1.mode = LineDataSet.Mode.LINEAR
            set1.cubicIntensity = 0.2f
            set1.setDrawFilled(false)
            set1.lineWidth = 2.5f
            set1.setDrawCircleHole(false)
            set1.setDrawCircles(true)
            set1.circleRadius =1.5f
            set1.highLightColor =
                ContextCompat.getColor(requireContext(), R.color.col_e0b)  //设置点后高亮颜色
            set1.enableDashedHighlightLine(10f, 5f, 0f)
            set1.setCircleColor(
                ContextCompat.getColor(
                    requireContext(),
                    R.color.col_41c
                )
            )    //#41C4AF
            set1.color = ContextCompat.getColor(requireContext(), R.color.col_9BDd) //xian de yanse
            //set1.setFillColor(Color.WHITE);
//            set1.fillAlpha = 100
            set1.setDrawHorizontalHighlightIndicator(false)
            set1.fillFormatter =
                IFillFormatter { _, _ -> binding.mLineChart.axisLeft.axisMinimum }

            set1.setValueFormatter { value, entry, dataSetIndex, viewPortHandler ->
                "$value"
            }
            // create a data object with the data sets
            val data = LineData( )
            //data.setValueTypeface(tfLight)
            data.setValueTextSize(9f)
            data.setDrawValues(false)

            // set data
            binding.mLineChart!!.data = data

        }
        return set1
    }
    private fun setData2(values:  List<Entry>?) :LineDataSet{

        val set1: LineDataSet
        if (binding.mLineChart!!.data != null && binding.mLineChart!!.data.dataSetCount > 0) {
            set1 = binding.mLineChart!!.data.getDataSetByIndex(0) as LineDataSet
            set1.values = values
            binding.mLineChart!!.data.notifyDataChanged()
            binding.mLineChart!!.notifyDataSetChanged()
        } else {
            // create a dataset and give it a type
            set1 = LineDataSet(values, "DataSet 2")
            set1.mode = LineDataSet.Mode.LINEAR
            set1.cubicIntensity = 0.2f
            set1.setDrawFilled(false)
            set1.lineWidth = 2.5f
            set1.setDrawCircleHole(false)
            set1.setDrawCircles(true)
            set1.circleRadius =1.5f
            set1.highLightColor =
                ContextCompat.getColor(requireContext(), R.color.col_e0b)  //设置点后高亮颜色
            set1.enableDashedHighlightLine(10f, 5f, 0f)
            set1.setCircleColor(
                ContextCompat.getColor(
                    requireContext(),
                    R.color.col_9BD
                )
            )    //#41C4AF
            set1.color = ContextCompat.getColor(requireContext(), R.color.col_9BD) //xian de yanse
            //set1.setFillColor(Color.WHITE);
//            set1.fillAlpha = 100
            set1.setDrawHorizontalHighlightIndicator(false)
            set1.fillFormatter =
                IFillFormatter { _, _ -> binding.mLineChart.axisLeft.axisMinimum }

            set1.setValueFormatter { value, entry, dataSetIndex, viewPortHandler ->
                "$value"
            }
            // create a data object with the data sets
            val data = LineData( )
            //data.setValueTypeface(tfLight)
            data.setValueTextSize(9f)
            data.setDrawValues(false)

            // set data
            binding.mLineChart!!.data = data

        }
        return set1
    }

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

    }
    private fun getDateAdd(days: Int): Date? {
        val c = Calendar.getInstance()
        c.add(Calendar.DAY_OF_MONTH, -days)
        return c.time
    }

    fun getXDate(): ArrayList<String> {
        val dateArr = ArrayList<String>()
        var time = 1688400000000.toDouble() // [XPHelper timeSwitchTimestamp:@"00:00" andFormatter:@"hh:mm"]
//        Log.d("time", time.toString())
        for (i in 0 until 144) {
            val timeStr = RxTimeTool.milliseconds2String(time.toLong(), SimpleDateFormat("HH:mm"))
            dateArr.add(0, timeStr)
            time += 10 * 60 * 1000
        }
        return dateArr
    }
//    fun getDayValueXDate(xDate: List<String>, valueArr: List<BreathCompareBean.Model>): List<BreathCompareBean.Model?> {
//        val arr = ArrayList<BreathCompareBean.Model?>()
//        for (i in xDate.indices) {
//            val dateStr = "${RxTimeTool.getCurTimeString(SimpleDateFormat("yyyy-MM-dd"))} ${xDate[i]}"
//            val dateTime =  timeSwitchTimestamp(dateStr, "yyyy-MM-dd HH:mm")
//            arr.add(null)
//            for (value in valueArr) {
//                val valueTime =  timeSwitchTimestamp("${RxTimeTool.getCurTimeString(SimpleDateFormat("yyyy-MM-dd"))} ${RxTimeTool.milliseconds2String(value.time.toLong(), SimpleDateFormat("HH:mm"))}", "yyyy-MM-dd HH:mm")
//                if (valueTime > dateTime - 5 * 60 * 1000 && valueTime <= dateTime + 4 * 60 * 1000) {
//                    arr[i] = value
//                }
//            }
//        }
//        return arr
//    }
@SuppressLint("SimpleDateFormat")
fun getDayValueXDate(xDate: List<String>, valueArr: List<BreathCompareBean.Model>): MutableList<BreathCompareBean.Model?> {
        val arr: MutableList<BreathCompareBean.Model?> = ArrayList()
        for (i in xDate.indices) {
            LogUtils.d("--------------date ;"+xDate[i])
            val dateStr = "${RxTimeTool.getCurTimeString(SimpleDateFormat("yyyy-MM-dd"))} ${xDate[i]}"
            val dateTime =  timeSwitchTimestamp(dateStr, "yyyy-MM-dd HH:mm")
            LogUtils.d("--------------dateTime:$dateTime")
            var hasValue = false
            for (value in valueArr) {
                val d  ="${RxTimeTool.getCurTimeString(SimpleDateFormat("yyyy-MM-dd"))} "
                val b = "${RxTimeTool.milliseconds2String(value.time.toLong(), SimpleDateFormat("HH:mm"))}"
                LogUtils.d("--------------CurTimeString:$d")
                LogUtils.d("--------------value:$value")
                LogUtils.d("--------------milliseconds2String$b")

                val valueTime =  timeSwitchTimestamp(d +
                        b , "yyyy-MM-dd HH:mm")

                if (valueTime > dateTime - 5 * 60 * 1000 && valueTime <= dateTime + 4 * 60 * 1000) {
                    arr.add(value )
                    hasValue = true
                    break
                }
            }
            if (!hasValue) {
                arr.add(null) // 或者可以使用其他占位符值
            }
        }
        return arr
    }
    fun timeSwitchTimestamp(dateStr: String, format: String): Long {
        val dateFormat = SimpleDateFormat(format, Locale.getDefault())
        val date = dateFormat.parse(dateStr)
        return date?.time ?: 0L
    }

}