package com.zj365.health.act.datamanage

import com.zj365.health.R
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.alibaba.android.arouter.facade.annotation.Route
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.charts.LineChart
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.xty.base.act.BaseListAct
import com.xty.common.TimeSelectCompare
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.event.TZhongDataManageEvent
import com.xty.common.recycleUtils.RecycleItem
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.databinding.ActXyDataManageBinding
import com.zj365.health.vm.DataManageVm
import com.zj365.health.weight.AddDataDialog
import com.zj365.health.weight.CustomXAxisRenderer
import com.zj365.health.weight.ICompareMarkView
import com.xty.network.model.DataManageTendencyBean
import com.xty.network.model.RecentlyHealthBean
import com.xty.network.model.XYaDataManageChartBean
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
import kotlin.math.max
import kotlin.math.min

/**
 * 血压数据管理
 */
@SuppressLint("SimpleDateFormat")
@Route(path = ARouterUrl.DATAMANAGE_XY_ACT)
open class XYDataManageAct: BaseListAct<DataManageVm>() {

    val binding by lazy { ActXyDataManageBinding.inflate(layoutInflater) }
    override fun setLayout() = binding.root

    private var titleStr = ""
    var pageType = ""

    private var dayDate = ""
    private var weekDate = ""
    private var mouthDate = ""
    private var yearDate = ""
    private var type = 1
    private var week: Int = 1//默认点击时间是选择时间还是对比时间 1，选择， 2 对比
    var id: String = ""

    private val mTabEntities: ArrayList<CustomTabEntity> = ArrayList()
    private val mTitles by lazy {
        arrayOf(
            "日", "周", "月", "年"
        )
    }
    private val imageIds by lazy {
        arrayOf(
            com.zj365.health.R.mipmap.xiangt,
            com.zj365.health.R.mipmap.shangsheng,
            com.zj365.health.R.mipmap.xiajiang
        )
    }

    private val timeSelect by lazy { TimeSelectCompare() }
    private val timeMonthSelect by lazy { TimeSelectCompare() }
    private val timeYearSelect by lazy { TimeSelectCompare() }
    private val timeSelectCompare by lazy { TimeSelectCompare() }
    private val timeMonthSelectCompare by lazy { TimeSelectCompare() }
    private val timeYearSelectCompare by lazy { TimeSelectCompare() }
    private var weekWheelView: WheelView? = null
    private val bottomSheetDialog by lazy { BottomSheetDialog(this) }

    //列表
    val adapter by lazy { DataManageShowAdapter() }

    //趋势图
    private val weeker by lazy { arrayOf("周一", "周二", "周三", "周四", "周五", "周六", "周日") }
    private var list: MutableList<DataManageTendencyBean.Model> = mutableListOf()
    private var listCompare: MutableList<DataManageTendencyBean.Model> = mutableListOf()
    private var chartLineList: MutableList<XYaDataManageChartBean> = mutableListOf()//（日）趋势图数据集合

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

    private var lineValue = arrayListOf<Entry>()  //曲线数据
    private var lineValueCompare = arrayListOf<Entry>()  //曲线数据
    private var lineValueLow = arrayListOf<Entry>()  //曲线数据
    private var lineValueCompareLow = arrayListOf<Entry>()  //曲线数据

    private var barValue = arrayListOf<BarEntry>()  //柱形数据
    private var barValueCompare = arrayListOf<BarEntry>()  //柱形数据
    private var barValueLow = arrayListOf<BarEntry>()  //柱形数据
    private var barValueCompareLow = arrayListOf<BarEntry>()  //柱形数据

    private var lineList = arrayListOf<Entry>()  //曲线数据
    private var lineListCompare = arrayListOf<Entry>()  //曲线数据
    private lateinit var lineListData: MutableList<RecentlyHealthBean.ChartList>

    //添加数据弹窗
    private val tipDialog by lazy {
        AddDataDialog(
            this,
            pageType,
            { id, date, dataVlue, tcStr, tgStr, hdlStr, ldlStr, height ->
                if (id.isNotEmpty()) {
                    mViewModel.editData(
                        id,
                        pageType,
                        date,
                        dataVlue,
                        tcStr,
                        tgStr,
                        hdlStr,
                        ldlStr,
                        height
                    )
                } else {
                    mViewModel.addData(
                        this.id,
                        pageType,
                        date,
                        dataVlue,
                        tcStr,
                        tgStr,
                        hdlStr,
                        ldlStr,
                        height
                    )
                }

                //刷新数据
                dataRefresh()
            },
            { height -> }
        )
    }

    override fun initData() {
        super.initData()
        titleStr = intent.getStringExtra(DataManageTypeAct.exceptionKey).toString()
        pageType = intent.getStringExtra(DataManageTypeAct.dataType).toString()
        id = intent.getStringExtra("userId").toString()
        binding.title.mTvTitle.text = titleStr
    }

    override fun initView() {
        super.initView()
        //设置状态栏
        statusBar(binding.title.mView)
        binding.title.mIvBack.apply {
            this.setOnClickListener {
                finish()
            }
        }

        //初始化没数据显示的图表
        initChartNoData()

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

        //初始化tab
        initTab()

        //初始化控件点击事件
        initOnClick()

        //初始化时间选择器
        setTimeSelect()

        initBottomDialog()
    }

    /**
     * 初始化没数据显示的图表
     */
    private fun initChartNoData() {
        binding.mLineChart.setNoDataText(getString(com.zj365.health.R.string.line_chart_not_data))
        binding.mLineChart.setNoDataTextColor(
            ContextCompat.getColor(
                this,
                com.zj365.health.R.color.col_455
            )
        )
        binding.mBarChart.setNoDataText(getString(com.zj365.health.R.string.line_chart_not_data))
        binding.mBarChart.setNoDataTextColor(
            ContextCompat.getColor(
                this,
                com.zj365.health.R.color.col_455
            )
        )
        binding.mLineChartList.setNoDataText(getString(com.zj365.health.R.string.line_chart_not_data))
        binding.mLineChartList.setNoDataTextColor(
            ContextCompat.getColor(
                this,
                com.zj365.health.R.color.col_455
            )
        )
        binding.mLineChartTwo.setNoDataText(getString(com.zj365.health.R.string.line_chart_not_data))
        binding.mLineChartTwo.setNoDataTextColor(
            ContextCompat.getColor(
                this,
                com.zj365.health.R.color.col_455
            )
        )
        binding.mBarChartTwo.setNoDataText(getString(com.zj365.health.R.string.line_chart_not_data))
        binding.mBarChartTwo.setNoDataTextColor(
            ContextCompat.getColor(
                this,
                com.zj365.health.R.color.col_455
            )
        )
    }

    /**
     * 初始化tab
     */
    private fun initTab() {
        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", "SimpleDateFormat")
            override fun onTabSelect(position: Int) {
                binding.commonTabLayout.currentTab = position

                when (position) {
                    0 -> {
                        type = 1
                        binding.showTitle.text = "选择日期"
                        binding.hideTitle.text = "对比日期"
                        binding.tvTendencyComparisonTitle.text = "对比日期"
                        binding.tvTendencySelectTitle.text = "选择日期"
                        binding.tvShowDate.text =
                            SimpleDateFormat("yyyy-MM-dd").format(getdateMunise(-1))
                        binding.tvHideDate.text =
                            SimpleDateFormat("yyyy-MM-dd").format(getdateMunise(-2))
                        binding.tvTendencySelectDate.text =
                            SimpleDateFormat("yyyy-MM-dd").format(getdateMunise(-1))
                        binding.tvTendencyComparisonDate.text =
                            SimpleDateFormat("yyyy-MM-dd").format(getdateMunise(-2))

                        mViewModel.interceptingDate(
                            id = id,
                            type = type,
                            dataType = pageType,
                            dateTime = binding.tvShowDate.text.toString(),
                            comDateTime = binding.tvHideDate.text.toString()
                        )

                        binding.mLineChart.visibility = View.VISIBLE
                        binding.mBarChart.visibility = View.GONE
                        binding.mLineChartTwo.visibility = View.VISIBLE
                        binding.mBarChartTwo.visibility = View.GONE

                    }

                    1 -> {
                        binding.tvShowDate.text = weekDate
                        binding.tvTendencySelectDate.text = weekDate
                        type = 2
                        binding.showTitle.text = "选择周"
                        binding.hideTitle.text = "对比周"
                        binding.tvTendencyComparisonTitle.text = "对比周"
                        binding.tvTendencySelectTitle.text = "选择周"
                        binding.tvShowDate.text = getPreviousWeekDateRange(1)
                        binding.tvHideDate.text = getPreviousWeekDateRange(2)
                        binding.tvTendencySelectDate.text = getPreviousWeekDateRange(1)
                        binding.tvTendencyComparisonDate.text = getPreviousWeekDateRange(2)

                        mViewModel.interceptingDate(
                            id = id,
                            type = type,
                            dataType = pageType,
                            dateTime = binding.tvShowDate.text.toString(),
                            comDateTime = binding.tvHideDate.text.toString()
                        )

                        binding.mLineChart.visibility = View.GONE
                        binding.mBarChart.visibility = View.VISIBLE
                        binding.mLineChartTwo.visibility = View.GONE
                        binding.mBarChartTwo.visibility = View.VISIBLE
                    }

                    2 -> {
                        binding.showTitle.text = "选择月"
                        binding.hideTitle.text = "对比月"
                        binding.tvTendencyComparisonTitle.text = "对比月"
                        binding.tvTendencySelectTitle.text = "选择月"
                        binding.tvShowDate.text = getPreviousMonthDateRange(1)
                        binding.tvHideDate.text = getPreviousMonthDateRange(2)
                        binding.tvTendencySelectDate.text = getPreviousMonthDateRange(1)
                        binding.tvTendencyComparisonDate.text = getPreviousMonthDateRange(2)
                        type = 3

                        mViewModel.interceptingDate(
                            id = id,
                            type = type,
                            dataType = pageType,
                            dateTime = binding.tvShowDate.text.toString(),
                            comDateTime = binding.tvHideDate.text.toString()
                        )

                        binding.mLineChart.visibility = View.GONE
                        binding.mBarChart.visibility = View.VISIBLE
                        binding.mLineChartTwo.visibility = View.GONE
                        binding.mBarChartTwo.visibility = View.VISIBLE

                    }

                    3 -> {
                        binding.showTitle.text = "选择年"
                        binding.hideTitle.text = "对比年"
                        binding.tvTendencyComparisonTitle.text = "对比年"
                        binding.tvTendencySelectTitle.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
                        binding.tvTendencySelectDate.text = yearDate
                        binding.tvTendencyComparisonDate.text = lastYear
                        type = 4

                        mViewModel.interceptingDate(
                            id = id,
                            type = type,
                            dataType = pageType,
                            dateTime = binding.tvShowDate.text.toString(),
                            comDateTime = binding.tvHideDate.text.toString()
                        )

                        binding.mLineChart.visibility = View.GONE
                        binding.mBarChart.visibility = View.VISIBLE
                        binding.mLineChartTwo.visibility = View.GONE
                        binding.mBarChartTwo.visibility = View.VISIBLE
                    }
                }
            }

            override fun onTabReselect(position: Int) {}
        })

    }

    /**
     * 初始化控件点击事件
     */
    @SuppressLint("SimpleDateFormat")
    private fun initOnClick() {
        //选择时间按钮
        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 -> {
                    val 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(this, calendar, 1) {
                        // 在选择时间后执行的逻辑
                        type = 1
                        val compareTime = binding.tvHideDate.text.toString()
                        binding.tvTendencyComparisonDate.text = compareTime

                        mViewModel.interceptingDate(
                            id = id,
                            type = type,
                            dataType = pageType,
                            dateTime = binding.tvShowDate.text.toString(),
                            comDateTime = binding.tvHideDate.text.toString()
                        )
                    }
                    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 -> {
                    val 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(this, calendar, 3) {
                        // 在选择时间后执行的逻辑
                        type = 3
                        val compareTime = binding.tvHideDate.text.toString()
                        binding.tvTendencyComparisonDate.text = compareTime

                        mViewModel.interceptingDate(
                            id = id,
                            type = type,
                            dataType = pageType,
                            dateTime = binding.tvShowDate.text.toString(),
                            comDateTime = binding.tvHideDate.text.toString()
                        )
                    }

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

                4 -> {
                    val 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(this, calendar, 4) {
                        // 在选择时间后执行的逻辑
                        type = 4
                        val compareTime = binding.tvHideDate.text.toString()
                        binding.tvTendencyComparisonDate.text = compareTime

                        mViewModel.interceptingDate(
                            id = id,
                            type = type,
                            dataType = pageType,
                            dateTime = binding.tvShowDate.text.toString(),
                            comDateTime = binding.tvHideDate.text.toString()
                        )
                    }
                    timeYearSelectCompare.selectTimeWithYear(it, "yyyy")
                }
            }
        }

        //点击跳转更多页面
        binding.tvDataContrastList.setOnClickListener {
            bundle.clear()
            bundle.putString(DataManageTypeAct.dataType, pageType)
            bundle.putString(DataManageTypeAct.exceptionKey, titleStr)
            bundle.putString("userId", id)
            //根据类型字段跳转不同数据页面。
            RouteManager.goAct(ARouterUrl.DATAMANAGE_TYPE_ACT, bundle)
        }

        //点击手动添加数据
        binding.mAddData.setOnClickListener {
            tipDialog.clear(pageType.toInt())
            tipDialog.show()
        }
    }

    /**
     * 初始化时间选择器
     */
    @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))
        binding.tvTendencySelectDate.text = SimpleDateFormat("yyyy-MM-dd").format(calendar.time)
        binding.tvTendencyComparisonDate.text =
            SimpleDateFormat("yyyy-MM-dd").format(getdateMunise(-2))
        //日 的选择时间器
        timeSelect.createPvTime(this, calendar, 1) {
            // 在选择时间后执行的逻辑
            type = 1
            val selectTime = binding.tvShowDate.text.toString()
            binding.tvTendencySelectDate.text = selectTime
            dayDate = selectTime
//            dayDate = binding.tvShowDate.text.toString()

            mViewModel.interceptingDate(
                id = id,
                type = type,
                dataType = pageType,
                dateTime = binding.tvShowDate.text.toString(),
                comDateTime = binding.tvHideDate.text.toString()
            )
        }
        timeSelect.startDate.set(1922, 1, 1)
        timeSelect.endDate = calendar

//-------------------------------------------------月
        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.createPvTime(this, calendar, 3) {
            // 在选择时间后执行的逻辑
            type = 3
            val selectTime = binding.tvShowDate.text.toString()
            binding.tvTendencySelectDate.text = selectTime
            mouthDate = selectTime
//            mouthDate = binding.tvHideDate.text.toString()

            mViewModel.interceptingDate(
                id = id,
                type = type,
                dataType = pageType,
                dateTime = binding.tvShowDate.text.toString(),
                comDateTime = binding.tvHideDate.text.toString()
            )
            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.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.createPvTime(this, calendaryear, 4) {
            // 在选择时间后执行的逻辑
            type = 4
            val selectTime = binding.tvShowDate.text.toString()
            binding.tvTendencySelectDate.text = selectTime
            mouthDate = selectTime
//            mouthDate = binding.tvHideDate.text.toString()

            mViewModel.interceptingDate(
                id = id,
                type = type,
                dataType = pageType,
                dateTime = binding.tvShowDate.text.toString(),
                comDateTime = binding.tvHideDate.text.toString()
            )
            timeYearSelect.selectTimeWithYearMonth(binding.tvShowDate, "yyyy")
        }

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

    @SuppressLint("SuspiciousIndentation", "InflateParams")
    fun initBottomDialog() {
        bottomSheetDialog.let { dialog ->
            val view = LayoutInflater.from(this).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.tvTendencySelectDate.text = item.toString()
                    binding.tvShowDate.text = item.toString()
                    weekDate = binding.tvTendencySelectDate.text.toString()

                    mViewModel.interceptingDate(
                        id = id,
                        type = type,
                        dataType = pageType,
                        dateTime = binding.tvShowDate.text.toString(),
                        comDateTime = binding.tvHideDate.text.toString()
                    )

                } else {
                    binding.tvTendencyComparisonDate.text = item.toString()
                    binding.tvHideDate.text = item.toString()

                    mViewModel.interceptingDate(
                        id = id,
                        type = type,
                        dataType = pageType,
                        dateTime = binding.tvShowDate.text.toString(),
                        comDateTime = binding.tvHideDate.text.toString()
                    )

                }
                // 点击确定按钮的操作
                dialog.dismiss()
            }
        }
    }

    override fun initAdapter() {
        binding.mRecycle.addItemDecoration(RecycleItem(this, 30))
        binding.mRecycle.layoutManager = LinearLayoutManager(this)
        binding.mRecycle.adapter = adapter

        adapter.addChildClickViewIds(
            com.zj365.health.R.id.root,
        )
    }

    @SuppressLint("SimpleDateFormat")
    override fun loadData() {
        //数据网络请求
        mViewModel.interceptingDate(
            id = id,
            type = type,
            dataType = pageType,
            dateTime = SimpleDateFormat("yyyy-MM-dd").format(getdateMunise(-1)),
            comDateTime = SimpleDateFormat("yyyy-MM-dd").format(getdateMunise(-2))
        )

        //数据列表网络请求
        mViewModel.getDataList(
            id,
            pageType,
            "1",
            page,
            "",
            "",
            pageSize = 2
        )

        //获取最近趋势图数据
        mViewModel.getRecentlyHealthData(
            id,
            pageType
        )
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun tizhongHealthUpdate(event: TZhongDataManageEvent) {
        dataRefresh()
    }

    private fun dataRefresh() {
        //对比数据网络请求
        mViewModel.interceptingDate(
            id = id,
            type = type,
            dataType = pageType,
            dateTime = binding.tvTendencySelectDate.text.toString(),
            comDateTime = binding.tvTendencyComparisonDate.text.toString()
        )

        //数据列表网络请求
        mViewModel.getDataList(
            id,
            pageType,
            "1",
            page,
            "",
            "",
            pageSize = 2
        )
    }

    @SuppressLint("SetTextI18n")
    override fun liveObserver() {
        mViewModel.getTendencyReturnData.observe(this) {
            chartLineList.clear()
            val data = it.data
            if (data.model.size == 0 && data.modelCompare.size == 0) {

            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    when (type) {
                        1 -> {//日
                            val dateMinute = SimpleDateFormat("HH:mm", Locale.getDefault())
                            val dayMinute = SimpleDateFormat("MM-dd", Locale.getDefault())
                            if (it.data.model.size > 0) {
                                for (model in it.data.model) {
                                    val time = model.time
                                    chartLineList.add(
                                        XYaDataManageChartBean(
                                            dateMinute.format(Date(time.toLong() * 1000)),
                                            model.high,
                                            model.low,
                                            0f,
                                            0f,
                                            dayMinute.format(Date(time.toLong() * 1000)),
                                            dateMinute.format(Date(time.toLong() * 1000))
                                                .replace(":", ".").toDouble()
                                        )
                                    )
                                }
                            }
                            if (it.data.modelCompare.size > 0) {
                                for (model in it.data.modelCompare) {
                                    val time = model.time
                                    chartLineList.add(
                                        XYaDataManageChartBean(
                                            dateMinute.format(Date(time.toLong() * 1000)),
                                            0f,
                                            0f,
                                            model.high,
                                            model.low,
                                            dayMinute.format(Date(time.toLong() * 1000)),
                                            dateMinute.format(Date(time.toLong() * 1000))
                                                .replace(":", ".").toDouble()
                                        )
                                    )
                                }
                            }
                        }

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

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

                        4 -> {//年
                            data.model = data.fillMissingData(data.model)
                            data.modelCompare = data.fillMissingData(data.modelCompare)
                        }
                    }
                }
            }

            setChartdata(data)

            //设置页面数据
            //----------------收缩压------------------
            val valueCompare = data.valueCompare
            val value = data.value
            binding.tvContrastAvgShrinkageData.text = if (valueCompare.avgHigh == 0f) {
                "-- mmHg"
            } else {
                "${valueCompare.avgHigh} mmHg"
            }
            binding.tvSelectAvgShrinkageData.text = if (value.avgHigh == 0f) {
                "-- mmHg"
            } else {
                "${value.avgHigh} mmHg"
            }
            if (valueCompare.avgHigh > value.avgHigh) {
                binding.ivDataContrastAvgShrinkageImg.setImageResource(imageIds[2])
            } else if (valueCompare.avgHigh < value.avgHigh) {
                binding.ivDataContrastAvgShrinkageImg.setImageResource(imageIds[1])
            } else {
                binding.ivDataContrastAvgShrinkageImg.setImageResource(imageIds[0])
            }
            //----------------舒张压------------------
            binding.tvContrastAvgDiastoleData.text = if (valueCompare.avgLow == 0f) {
                "-- mmHg"
            } else {
                "${valueCompare.avgLow} mmHg"
            }
            binding.tvSelectAvgDiastoleData.text = if (value.avgLow == 0f) {
                "-- mmHg"
            } else {
                "${value.avgLow} mmHg"
            }
            if (valueCompare.avgLow > value.avgLow) {
                binding.ivDataContrastAvgDiastoleImg.setImageResource(imageIds[2])
            } else if (valueCompare.avgLow < value.avgLow) {
                binding.ivDataContrastAvgDiastoleImg.setImageResource(imageIds[1])
            } else {
                binding.ivDataContrastAvgDiastoleImg.setImageResource(imageIds[0])
            }
            val comprehensiveContent = data.comprehensiveContent
            if (!TextUtils.isEmpty(comprehensiveContent)) {
                binding.tvCompareContent.text = comprehensiveContent
            }
        }

        //获取网络请求数据列表
        mViewModel.getDataListOb.observe(this) {
            adapter.setNewInstance(it.data.records)
        }

        mViewModel.getRecentyHealthReturnData.observe(this) {
            val data = it.data
            if (data.list.size == 0) {

            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    val dateTime = SimpleDateFormat("HH:mm", Locale.getDefault())
                    val dateMonth = SimpleDateFormat("MM-dd", Locale.getDefault())
                    for (chartList in data.list) {
                        val time = chartList.time
                        chartList.date = dateTime.format(Date(time.toLong() * 1000))
                        chartList.time = dateMonth.format(Date(time.toLong() * 1000))
                    }

                    setRecentyHealthData(it.data)
                }
            }
        }
    }

    private fun setRecentyHealthData(data: RecentlyHealthBean) {
        lineListData = data.list
        lineList.clear()
        lineListCompare.clear()

        for ((i, chartList) in lineListData.withIndex()) {
            val listTipG = mutableListOf<String>()
            listTipG.add(chartList.time)
            listTipG.add(chartList.date)
            listTipG.add(chartList.high.toString())
            listTipG.add(chartList.low.toString())
            lineList.add(
                Entry(
                    i.toFloat(),
                    chartList.high,
                    listTipG
                )
            )
            lineListCompare.add(
                Entry(
                    i.toFloat(),
                    chartList.low,
                    listTipG
                )
            )
        }
//        val rever: IntProgression = (lineListData.indices).reversed()
//        for (i in rever) {
//            val listTipG = mutableListOf<String>()
//            listTipG.add(lineListData[i].time)
//            listTipG.add(lineListData[i].date)
//            listTipG.add(lineListData[lineListData.size - 1 - i].high.toString())
//            listTipG.add(lineListData[lineListData.size - 1 - i].low.toString())
//
//            lineList.add(
//                Entry(
//                    (lineListData.size - 1 - i).toFloat(),
//                    lineListData[lineListData.size - 1 - i].high,
//                    listTipG
//                )
//            )
//            lineListCompare.add(
//                Entry(
//                    (lineListData.size - 1 - i).toFloat(),
//                    lineListData[lineListData.size - 1 - i].low,
//                    listTipG
//                )
//            )
//        }
        binding.mLineChartList.clear()

        var max = if (data.maxHigh > data.maxLow) data.maxHigh else data.maxLow
        var min = if (data.minHigh < data.minLow) data.minHigh else data.minLow
        max = if (max >= 0) max + 10 else max
        min = if (min - 10 < 0) min else min - 10
        //设置趋势图
        initLineChartList(
            max,
            min
        )
    }

    //设置趋势图
    private fun initLineChartList(max: Float, min: Float) {
        binding.mLineChartList.let {
            it.clear()
            it.setNoDataText(getString(com.zj365.health.R.string.line_chart_not_data))
            it.setNoDataTextColor(ContextCompat.getColor(this, com.zj365.health.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(1.5f, 1f)
            it.viewPortHandler.refresh(m, it, false)
            it.isScaleXEnabled = true                 //支持x轴缩放
            it.isScaleYEnabled = false

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

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

            val markerView = ICompareMarkView(
                this,
                R.layout.mark_view_compare,
                getUnit(pageType.toInt()),
                ICompareMarkView.MarkPage.TShu
            )
            it.marker = markerView
            markerView.chartView = it
            it.axisRight.isEnabled = false
            it.legend.isEnabled = false

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

                var segments = splitDataIntoSegmentsLineList(lineListData)
                val dataSets = segments.mapNotNull { segment ->
                    if (segment.isEmpty()) return@mapNotNull null

                    val entries = segment.mapIndexed { index, model ->
                        Entry(
                            index.toFloat(),
                            model.high,
                            lineList[index].data
                        )
                    }

                    return@mapNotNull setLineListData(entries)
                }
                var segmentsCompare = splitDataIntoSegmentsLineList(lineListData)
                val dataSetsCompare = segmentsCompare.mapNotNull { segment ->
                    if (segment.isEmpty()) return@mapNotNull null

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

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

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

        }
        return set1
    }

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

        }
        return set1
    }

    private fun setChartdata(data: DataManageTendencyBean) {
        list.clear()
        listCompare.clear()
        list.addAll(data.model)
        listCompare.addAll(data.modelCompare)
        lineValue.clear()
        lineValueCompare.clear()
        lineValueLow.clear()
        lineValueCompareLow.clear()
        barValue.clear()
        barValueCompare.clear()
        barValueLow.clear()
        barValueCompareLow.clear()
        if (type != 1) {
            val 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,
                            DataManageTendencyBean.Model(
                                listCompare[list.size].time,
                                0f,
                                0f,
                                0f
                            )
                        )
                    }
                } else if (compare < 0) {
                    compare = 0 - compare
                    for (Int in 1..compare) {
                        listCompare.add(
                            listCompare.size,
                            DataManageTendencyBean.Model(
                                list[listCompare.size].time,
                                0f,
                                0f,
                                0f
                            )
                        )
                    }
                }
            }
            for (i in rever) {
                //中间两端在x轴显示尺度 其他情况下不显示
                when (type) {
                    1 -> {
                        val listTipG = mutableListOf<String>()
                        listTipG.add(list[list.size - 1 - i].time)
                        listTipG.add("0")
                        listTipG.add(list[list.size - 1 - i].high.toString())
                        listTipG.add(listCompare[listCompare.size - 1 - i].high.toString())
                        if (list[list.size - 1 - i].high == 0f && list[list.size - 1 - i].low == 0f) {
                            list[list.size - 1 - i].high = Float.NaN
                            list[list.size - 1 - i].low = Float.NaN
                        } else {
                            list[list.size - 1 - i].high
                            list[list.size - 1 - i].low
                        }
                        lineValue.add(
                            Entry(
                                (list.size - 1 - i).toFloat(),
                                list[list.size - 1 - i].high,
                                listTipG
                            )
                        )
                        //                }
                        if (listCompare[listCompare.size - 1 - i].high == 0f &&
                            listCompare[listCompare.size - 1 - i].low == 0f
                        ) {
                            listCompare[listCompare.size - 1 - i].high = Float.NaN
                            listCompare[listCompare.size - 1 - i].low = Float.NaN
                        } else {
                            listCompare[listCompare.size - 1 - i].high
                            listCompare[listCompare.size - 1 - i].low
                        }
                        lineValueCompare.add(
                            Entry(
                                (listCompare.size - 1 - i).toFloat(),
                                listCompare[listCompare.size - 1 - i].high,
                                listTipG
                            )
                        )

                        var listTipGl = mutableListOf<String>()
                        listTipGl.add(list[list.size - 1 - i].time)
                        listTipGl.add("1")
                        listTipGl.add(list[list.size - 1 - i].low.toString())
                        listTipGl.add(listCompare[listCompare.size - 1 - i].low.toString())


                        lineValueLow.add(
                            Entry(
                                (list.size - 1 - i).toFloat(),
                                list[list.size - 1 - i].low,
                                listTipGl
                            )
                        )
                        lineValueCompareLow.add(
                            Entry(
                                (listCompare.size - 1 - i).toFloat(),
                                listCompare[listCompare.size - 1 - i].low,
                                listTipGl
                            )
                        )
                    }

                    2 -> {
                        val listTipW = mutableListOf<String>()
                        listTipW.add(weeker[weeker.size - i - 1])
                        listTipW.add("0")
                        listTipW.add(list[list.size - 1 - i].high.toString())
                        listTipW.add(listCompare[listCompare.size - 1 - i].high.toString())
                        barValue.add(
                            BarEntry(
                                (list.size - 1 - i).toFloat(),
                                list[list.size - 1 - i].high,
                                listTipW

                            )
                        )
                        barValueCompare.add(
                            BarEntry(
                                (listCompare.size - 1 - i).toFloat(),
                                listCompare[listCompare.size - 1 - i].high,
                                listTipW
                            )
                        )

                        var listTipW1 = mutableListOf<String>()
                        listTipW1.add(weeker[weeker.size - i - 1])
                        listTipW1.add("1")
                        listTipW1.add(list[list.size - 1 - i].low.toString())
                        listTipW1.add(listCompare[listCompare.size - 1 - i].low.toString())
                        barValueLow.add(
                            BarEntry(
                                (list.size - 1 - i).toFloat(),
                                list[list.size - 1 - i].low,
                                listTipW1

                            )
                        )
                        barValueCompareLow.add(
                            BarEntry(
                                (listCompare.size - 1 - i).toFloat(),
                                listCompare[listCompare.size - 1 - i].low,
                                listTipW1
                            )
                        )
                    }

                    3 -> {

                        var listTipY = mutableListOf<String>()
                        listTipY.add(list[list.size - 1 - i].time)
                        listTipY.add("0")
                        listTipY.add(list[list.size - 1 - i].high.toString())
                        listTipY.add(listCompare[listCompare.size - 1 - i].high.toString())
                        barValue.add(
                            BarEntry(
                                (list.size - 1 - i).toFloat(),
                                list[list.size - 1 - i].high.toFloat(),
                                listTipY
                            )
                        )
                        barValueCompare.add(
                            BarEntry(
                                (listCompare.size - 1 - i).toFloat(),
                                listCompare[listCompare.size - 1 - i].high,
                                listTipY
                            )
                        )

                        var listTipY1 = mutableListOf<String>()
                        listTipY1.add(list[list.size - 1 - i].time)
                        listTipY1.add("1")
                        listTipY1.add(list[list.size - 1 - i].low.toString())
                        listTipY1.add(listCompare[listCompare.size - 1 - i].low.toString())
                        barValueLow.add(
                            BarEntry(
                                (list.size - 1 - i).toFloat(),
                                list[list.size - 1 - i].low,
                                listTipY1
                            )
                        )
                        barValueCompareLow.add(
                            BarEntry(
                                (listCompare.size - 1 - i).toFloat(),
                                listCompare[listCompare.size - 1 - i].low,
                                listTipY1
                            )
                        )
                    }

                    else -> {
                        var listTipY = mutableListOf<String>()
                        listTipY.add(list[list.size - 1 - i].time)
                        listTipY.add("0")
                        listTipY.add(list[list.size - 1 - i].high.toString())
                        listTipY.add(listCompare[listCompare.size - 1 - i].high.toString())
                        barValue.add(
                            BarEntry(
                                (list.size - 1 - i).toFloat(),
                                list[list.size - 1 - i].high,
                                listTipY
                            )
                        )
                        barValueCompare.add(
                            BarEntry(
                                (listCompare.size - 1 - i).toFloat(),
                                listCompare[listCompare.size - 1 - i].high,
                                listTipY
                            )
                        )
                        var listTipY1 = mutableListOf<String>()
                        listTipY1.add(list[list.size - 1 - i].time)
                        listTipY1.add("1")
                        listTipY1.add(list[list.size - 1 - i].low.toString())
                        listTipY1.add(listCompare[listCompare.size - 1 - i].low.toString())
                        barValueLow.add(
                            BarEntry(
                                (list.size - 1 - i).toFloat(),
                                list[list.size - 1 - i].low,
                                listTipY1
                            )
                        )
                        barValueCompareLow.add(
                            BarEntry(
                                (listCompare.size - 1 - i).toFloat(),
                                listCompare[listCompare.size - 1 - i].low,
                                listTipY1
                            )
                        )
                    }
                }
            }
        } else {
            chartLineList.sortWith { u1, u2 ->
                u1.sort.compareTo(u2.sort)
            }
            for ((index, xYaDataManageChartBean) in chartLineList.withIndex()) {
                xYaDataManageChartBean.index = index
            }
            val reversed = chartLineList.indices.reversed()
            for (i in reversed) {
                val listTipG = mutableListOf<String>()
                listTipG.add(chartLineList[chartLineList.size - 1 - i].time)
                listTipG.add("0")
                listTipG.add(chartLineList[chartLineList.size - 1 - i].high.toString())
                listTipG.add(chartLineList[chartLineList.size - 1 - i].highCompare.toString())

                if (chartLineList[chartLineList.size - 1 - i].high == 0f) {
                    chartLineList[chartLineList.size - 1 - i].high = Float.NaN
                } else {
                    chartLineList[chartLineList.size - 1 - i].high
                }
                if (chartLineList[chartLineList.size - 1 - i].highCompare == 0f) {
                    chartLineList[chartLineList.size - 1 - i].highCompare = Float.NaN
                } else {
                    chartLineList[chartLineList.size - 1 - i].highCompare
                }
                lineValue.add(
                    Entry(
                        (chartLineList.size - 1 - i).toFloat(),
                        chartLineList[chartLineList.size - 1 - i].high,
                        listTipG
                    )
                )
                lineValueCompare.add(
                    Entry(
                        (chartLineList.size - 1 - i).toFloat(),
                        chartLineList[chartLineList.size - 1 - i].highCompare,
                        listTipG
                    )
                )

                val listTipGl = mutableListOf<String>()
                listTipGl.add(chartLineList[chartLineList.size - 1 - i].time)
                listTipGl.add("1")
                listTipGl.add(chartLineList[chartLineList.size - 1 - i].low.toString())
                listTipGl.add(chartLineList[chartLineList.size - 1 - i].lowCompare.toString())

                if (chartLineList[chartLineList.size - 1 - i].low == 0f) {
                    chartLineList[chartLineList.size - 1 - i].low = Float.NaN
                } else {
                    chartLineList[chartLineList.size - 1 - i].low
                }
                if (chartLineList[chartLineList.size - 1 - i].lowCompare == 0f) {
                    chartLineList[chartLineList.size - 1 - i].lowCompare = Float.NaN
                } else {
                    chartLineList[chartLineList.size - 1 - i].lowCompare
                }
                lineValueLow.add(
                    Entry(
                        (chartLineList.size - 1 - i).toFloat(),
                        chartLineList[chartLineList.size - 1 - i].low,
                        listTipGl
                    )
                )
                lineValueCompareLow.add(
                    Entry(
                        (chartLineList.size - 1 - i).toFloat(),
                        chartLineList[chartLineList.size - 1 - i].lowCompare,
                        listTipGl
                    )
                )
            }
        }

        binding.mLineChart.clear()
        binding.mBarChart.clear()
        binding.mLineChartTwo.clear()
        binding.mBarChartTwo.clear()
        //收缩压 最大值 最小值
        val min: Float = if (data.value.minHigh != 0f && data.valueCompare.minHigh != 0f) {
            if (data.value.minHigh < data.valueCompare.minHigh) {
                data.value.minHigh
            } else {
                data.valueCompare.minHigh
            }
        } else if (data.value.minHigh == 0f && data.valueCompare.minHigh != 0f) {
            data.valueCompare.minHigh
        } else if (data.valueCompare.minHigh == 0f && data.value.minHigh != 0f) {
            data.value.minHigh
        } else {
            min(data.value.minHigh, data.valueCompare.minHigh)
        }

        val max: Float = if (data.value.maxHigh != 0f && data.valueCompare.maxHigh != 0f) {
            if (data.value.maxHigh > data.valueCompare.maxHigh) {
                data.value.maxHigh
            } else {
                data.valueCompare.maxHigh
            }
        } else if (data.value.maxHigh == 0f && data.valueCompare.maxHigh != 0f) {
            data.valueCompare.maxHigh
        } else if (data.valueCompare.maxHigh == 0f && data.value.maxHigh != 0f) {
            data.value.maxHigh
        } else {
            max(data.value.maxHigh, data.valueCompare.maxHigh)
        }

        //舒张压 最大值 最小值
        val lowMin: Float = if (data.value.minLow != 0f && data.valueCompare.minLow != 0f) {
            if (data.value.minLow < data.valueCompare.minLow) {
                data.value.minLow
            } else {
                data.valueCompare.minLow
            }
        } else if (data.value.minLow == 0f && data.valueCompare.minLow != 0f) {
            data.valueCompare.minLow
        } else if (data.valueCompare.minLow == 0f && data.value.minLow != 0f) {
            data.value.minLow
        } else {
            min(data.value.minLow, data.valueCompare.minLow)
        }

        val lowMax: Float = if (data.value.maxLow != 0f && data.valueCompare.maxLow != 0f) {
            if (data.value.maxLow > data.valueCompare.maxLow) {
                data.value.maxLow
            } else {
                data.valueCompare.maxLow
            }
        } else if (data.value.maxLow == 0f && data.valueCompare.maxLow != 0f) {
            data.valueCompare.maxLow
        } else if (data.valueCompare.maxLow == 0f && data.value.maxLow != 0f) {
            data.value.maxLow
        } else {
            max(data.value.maxLow, data.valueCompare.maxLow)
        }

        //收缩压
        initChart(
            true,
            lineValue,
            lineValueCompare,
            barValue,
            barValueCompare,
            binding.mLineChart,
            binding.mBarChart,
            min,
            max
        )
        //舒张压
        initChart(
            false,
            lineValueLow,
            lineValueCompareLow,
            barValueLow,
            barValueCompareLow,
            binding.mLineChartTwo,
            binding.mBarChartTwo,
            lowMin,
            lowMax
        )
    }

    private fun initChart(
        isHigh: Boolean,
        lineValue: ArrayList<Entry>,
        lineValueCompare: ArrayList<Entry>,
        barValue: ArrayList<BarEntry>,
        barValueCompare: ArrayList<BarEntry>,
        mLineChart: LineChart,
        mBarChart: BarChart,
        min: Float,
        max: Float
    ) {
        if (type == 1) {
            mLineChart.let {
                it.clear()
                it.setNoDataText(getString(R.string.line_chart_not_data))
                it.setNoDataTextColor(ContextCompat.getColor(this, R.color.col_455))
                it.setLayerType(View.LAYER_TYPE_SOFTWARE, null)

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

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

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

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

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

                val x = it.xAxis
                x.granularity = 1f  //精准设置
                x.textColor = ContextCompat.getColor(this, 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]}"
                    }
                }
                val y = it.axisLeft
//            y.axisMaximum=max
//            y.axisMinimum=min
                y.setLabelCountAndMaxMinValue(6, false, min - 0.4f, max + 0.3f)
                y.textColor = ContextCompat.getColor(this, R.color.col_92a)
                y.setDrawAxisLine(false)
                y.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
                y.gridColor = ContextCompat.getColor(this, R.color.col_92a)
                y.setGridDashedLine(DashPathEffect(floatArrayOf(5f, 5f), 0f))
                y.setDrawGridLines(true)  //绘制横者的x轴
                y.setDrawZeroLine(true)

                var markerView = ICompareMarkView(
                    this,
                    R.layout.mark_view_compare,
                    getUnit(pageType.toInt()),
                    ICompareMarkView.MarkPage.XYa
                )
                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 = splitDataIntoSegmentsLine(chartLineList, isHigh)
                    val dataSets = segments.mapNotNull { segment ->
                        if (segment.isEmpty()) return@mapNotNull null

                        val entries = segment.mapIndexed { index, model ->
                            Entry(
                                model.index.toFloat(),
                                if (isHigh) model.high else model.low,
                                lineValue[model.index].data
                            )
                        }
                        return@mapNotNull setData(it, entries)
                    }
                    var segmentsCompare = splitDataIntoSegmentsLineCompare(chartLineList, isHigh)
                    val dataSetsCompare = segmentsCompare.mapNotNull { segment ->
                        if (segment.isEmpty()) return@mapNotNull null

                        val entries = segment.mapIndexed { index, model ->
                            Entry(
                                model.index.toFloat(),
                                if (isHigh) model.highCompare else model.lowCompare,
                                lineValueCompare[model.index].data
                            )
                        }
                        return@mapNotNull setData2(it, 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 {
            mBarChart.let {
                it.clear()
                it.setNoDataText(getString(com.zj365.health.R.string.line_chart_not_data))
                it.setNoDataTextColor(
                    ContextCompat.getColor(
                        this,
                        com.zj365.health.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(this, com.zj365.health.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]}"
                    }
                }
                //y轴
                val y = it.axisLeft
                y.setLabelCountAndMaxMinValue(6, false, min, max)
                y.textColor =
                    ContextCompat.getColor(this, com.zj365.health.R.color.col_92a)
                y.setDrawAxisLine(false)
                y.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
                y.gridColor =
                    ContextCompat.getColor(this, com.zj365.health.R.color.col_92a)
                y.setGridDashedLine(DashPathEffect(floatArrayOf(5f, 5f), 0f))
                y.setDrawGridLines(true)  //绘制横者的x轴
                y.setDrawZeroLine(true)
                y.xOffset = 5f
                var markerView = ICompareMarkView(
                    this,
                    R.layout.mark_view_compare,
                    getUnit(pageType.toInt()),
                    ICompareMarkView.MarkPage.XYa
                )
                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(this, com.zj365.health.R.color.col_9BDd)
                set1.highLightColor =
                    ContextCompat.getColor(
                        this,
                        com.zj365.health.R.color.col_C6B
                    )  //设置点后高亮颜色
                set1.color = ContextCompat.getColor(
                    this,
                    com.zj365.health.R.color.col_9BDd
                ) //xian de yanse
                sets.add(set1)

                val set2 = BarDataSet(barValueCompare, "DataSet2")
                set2.valueTextColor =
                    ContextCompat.getColor(this, com.zj365.health.R.color.col_8c6)
                set2.highLightColor =
                    ContextCompat.getColor(
                        this,
                        com.zj365.health.R.color.col_8c6
                    )  //设置点后高亮颜色
                set2.color = ContextCompat.getColor(
                    this,
                    com.zj365.health.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)

                mBarChart.data = d
                mBarChart.invalidate()

            }
        }
    }

    private fun setData(mLineChart: LineChart, values: List<Entry>?): LineDataSet {
        val set1: LineDataSet
        if (mLineChart.data != null && mLineChart.data.dataSetCount > 0) {
            set1 = mLineChart.data.getDataSetByIndex(0) as LineDataSet
            set1.values = values
            mLineChart.data.notifyDataChanged()
            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 = 3.5f
            set1.highLightColor =
                ContextCompat.getColor(this, com.zj365.health.R.color.col_e0b)  //设置点后高亮颜色
            set1.enableDashedHighlightLine(10f, 5f, 0f)
            set1.setCircleColor(
                ContextCompat.getColor(
                    this,
                    com.zj365.health.R.color.col_41c
                )
            )    //#41C4AF
            set1.color =
                ContextCompat.getColor(this, com.zj365.health.R.color.col_9BDd) //xian de yanse
            //set1.setFillColor(Color.WHITE);
//            set1.fillAlpha = 100
            set1.setDrawHorizontalHighlightIndicator(false)
            set1.fillFormatter =
                IFillFormatter { _, _ -> 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)
        }
        return set1
    }

    private fun setData2(mLineChart: LineChart, values: List<Entry>?): LineDataSet {
        val set1: LineDataSet
        if (mLineChart.data != null && mLineChart.data.dataSetCount > 0) {
            set1 = mLineChart.data.getDataSetByIndex(0) as LineDataSet
            set1.values = values
            mLineChart.data.notifyDataChanged()
            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 = 3.5f
            set1.highLightColor =
                ContextCompat.getColor(this, R.color.col_e0b)  //设置点后高亮颜色
            set1.enableDashedHighlightLine(10f, 5f, 0f)
            set1.setCircleColor(
                ContextCompat.getColor(
                    this,
                    R.color.col_9BD
                )
            )    //#41C4AF
            set1.color =
                ContextCompat.getColor(this, com.zj365.health.R.color.col_9BD) //xian de yanse
            //set1.setFillColor(Color.WHITE);
//            set1.fillAlpha = 100
            set1.setDrawHorizontalHighlightIndicator(false)
            set1.fillFormatter =
                IFillFormatter { _, _ -> 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)
        }
        return set1
    }

    private fun splitDataIntoSegmentsLine(
        dataList: MutableList<XYaDataManageChartBean>,
        isHigh: Boolean
    ):
            MutableList<MutableList<XYaDataManageChartBean>> {
        val segments = mutableListOf<MutableList<XYaDataManageChartBean>>()
        var currentSegment = mutableListOf<XYaDataManageChartBean>()

        for (model in dataList) {
            if (isHigh) {
                if (model.high.isNaN()) {
                    // 遇到 Float.NaN，如果当前线段不为空，则添加到结果中，并开始新的线段
                    if (currentSegment.isNotEmpty()) {
                        segments.add(currentSegment)
                        currentSegment = mutableListOf()
                    }
                } else {
                    // 遇到有效数据，将其添加到当前线段中
                    currentSegment.add(model)
                }
            } else {
                if (model.low.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 splitDataIntoSegmentsLineCompare(
        dataList: MutableList<XYaDataManageChartBean>,
        isHigh: Boolean
    ):
            MutableList<MutableList<XYaDataManageChartBean>> {
        val segments = mutableListOf<MutableList<XYaDataManageChartBean>>()
        var currentSegment = mutableListOf<XYaDataManageChartBean>()

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

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

        return segments
    }

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

        for (model in dataList) {
            if (model.high.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<DataManageTendencyBean.Model>>):
            MutableList<MutableList<DataManageTendencyBean.Model>> {
        if (segmentsCompare[0][0].time != "00:00") {
            val d = mutableListOf<DataManageTendencyBean.Model>()
            val b = DataManageTendencyBean.Model(
                "00:00",
                0f,
                0f,
                0f
            )
            d.add(b)
            segmentsCompare.add(d)
        }
        if (segmentsCompare[segmentsCompare.size - 1][segmentsCompare[segmentsCompare.size - 1].size - 1].time != "23:50") {
            val d = mutableListOf<DataManageTendencyBean.Model>()
            val b = DataManageTendencyBean.Model(
                "23:50",
                0f,
                0f,
                0f
            )
            d.add(b)
            segmentsCompare.add(d)
        }

        return segmentsCompare
    }

    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
    }

    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) //将图表动画显示之前进行缩放
    }

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

    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 getDateAdd(days: Int): Date? {
        val c = Calendar.getInstance()
        c.add(Calendar.DAY_OF_MONTH, -days)
        return c.time
    }

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

    /**
     * 获取上周的礼拜 周数
     */
    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"
    }

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

        val dateFormat = SimpleDateFormat("yyyy-MM", Locale.getDefault())

        return dateFormat.format(calendar.time)
    }

    private fun splitDataIntoSegmentsLineList(dataList: MutableList<RecentlyHealthBean.ChartList>):
            MutableList<MutableList<RecentlyHealthBean.ChartList>> {
        val segments = mutableListOf<MutableList<RecentlyHealthBean.ChartList>>()
        var currentSegment = mutableListOf<RecentlyHealthBean.ChartList>()

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

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

        return segments
    }

    @SuppressLint("SimpleDateFormat")
    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()
        val 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
    }

    fun getUnit(dataType: Int): String {
        var showName = ""
        when (dataType) {
            1 -> {
                showName = "mmol/L"
            }

            2 -> {
                showName = "mmHg"
            }

            3 -> {
                showName = "kg"
            }

            4 -> {
                showName = "μmol/L"
            }

            5 -> {
                showName = "mmol/l"
            }
        }
        return showName
    }
}