package com.zj365.health.act.datamanage

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.R
import com.zj365.health.databinding.ActTzhongDataManageBinding
import com.zj365.health.vm.DataManageVm
import com.zj365.health.weight.AddDataDialog
import com.zj365.health.weight.CustomXAxisRenderer
import com.zj365.health.weight.ICompareMarkLineView
import com.zj365.health.weight.ICompareMarkView
import com.xty.network.model.DataManageChartBean
import com.xty.network.model.DataManageTendencyBean
import com.xty.network.model.HealthDataBean
import com.xty.network.model.RecentlyHealthBean
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

@Route(path = ARouterUrl.TZHONG_DATA_MANAGE_ACT)
class TZhongDataManageAct : BaseListAct<DataManageVm>() {

    val binding by lazy { ActTzhongDataManageBinding.inflate(layoutInflater) }

    var id: String = ""

    private val imageIds by lazy {
        arrayOf(
            R.mipmap.xiangt,
            R.mipmap.shangsheng,
            R.mipmap.xiajiang
        )
    }

    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
    }

    //日，周，月，年----集合
    private val mTabEntities: ArrayList<CustomTabEntity> = ArrayList()
    private val mTitles = arrayOf(
        "日", "周", "月", "年"
    )

    private var lineList = arrayListOf<Entry>()  //体重曲线数据
    private var bmiLineList = arrayListOf<Entry>()  //BMI曲线数据
    var lineValue = arrayListOf<Entry>()  //曲线数据
    private var lineValueCompare = arrayListOf<Entry>()  //曲线数据
    var barValue = arrayListOf<BarEntry>()  //柱形数据
    private var barValueCompare = arrayListOf<BarEntry>()  //柱形数据

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

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

    //设置时间
    private var week: Int = 1//默认点击时间是选择时间还是对比时间 1，选择， 2 对比
    var type = 1
    private var pageType = ""
    private val timeSelect by lazy { TimeSelectCompare() }
    private var weekWheelView: WheelView? = null
    private val bottomSheetDialog by lazy { BottomSheetDialog(this) }
    private val timeMonthSelect by lazy { TimeSelectCompare() }
    private val timeYearSelect by lazy { TimeSelectCompare() }
    private val timeYearSelectCompare by lazy { TimeSelectCompare() }
    private val timeSelectCompare by lazy { TimeSelectCompare() }
    private val timeMonthSelectCompare by lazy { TimeSelectCompare() }
    var dayDate = ""
    var weekDate = ""
    var mouthDate = ""
    var yearDate = ""
    private var titleStr = ""
    private var heightStr = ""

    //列表
    val adapter by lazy { if (pageType.toInt() != 3) DataManageShowAdapter() else TZhongDataManageListAdapter() }

    //添加数据弹窗
    val tipDialog by lazy {
        AddDataDialog(
            this,
            pageType,
            { id, date, dataVlue, tcStr, tgStr, hdlStr, ldlStr, height ->
                heightStr = 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 ->
                heightStr = height
            }
        )
    }

    @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.tvTendencySelectDate.text.toString(),
                        comDateTime = binding.tvTendencyComparisonDate.text.toString()
                    )

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

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

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

    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
        binding.tvCompareName.text = when (pageType) {
            "1" -> {
                "血糖值"
            }

            "4" -> {
                "尿酸值"
            }

            else -> {
                "体重值"
            }
        }
    }

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

        val currentDay = Date()
        dayDate = TimeUtils.date2String(currentDay, "yyyy-MM-dd")
        mouthDate = TimeUtils.date2String(currentDay, "yyyy-MM")
        yearDate = TimeUtils.date2String(currentDay, "yyyy")

        binding.mLineChart.setNoDataText(getString(R.string.line_chart_not_data))
        binding.mLineChart.setNoDataTextColor(
            ContextCompat.getColor(
                this,
                R.color.col_455
            )
        )
        binding.mBarChart.setNoDataText(getString(R.string.line_chart_not_data))
        binding.mBarChart.setNoDataTextColor(
            ContextCompat.getColor(
                this,
                R.color.col_455
            )
        )
        binding.mLineChartList.setNoDataText(getString(R.string.line_chart_not_data))
        binding.mLineChartList.setNoDataTextColor(
            ContextCompat.getColor(
                this,
                R.color.col_455
            )
        )
        binding.mBMILineChartList.setNoDataText(getString(R.string.line_chart_not_data))
        binding.mBMILineChartList.setNoDataTextColor(
            ContextCompat.getColor(
                this,
                R.color.col_455
            )
        )

        mTabEntities.clear()
        mTitles.forEach {
            mTabEntities.add(
                TabEntity(
                    it,
                    android.R.drawable.ic_delete,
                    android.R.drawable.ic_delete
                )
            )
        }
        binding.tendencyCommonTabLayout.setTabData(mTabEntities)
        binding.tendencyCommonTabLayout.setOnTabSelectListener(object : OnTabSelectListener {
            @SuppressLint("SetTextI18n", "SimpleDateFormat")
            override fun onTabSelect(position: Int) {
                binding.tendencyCommonTabLayout.currentTab = position
                when (position) {
                    0 -> {
                        type = 1
                        binding.showTitle.text = "选择日期"
                        binding.hideTitle.text = "对比日期"
                        binding.tvTendencyComparisonTitle.text = "对比日期"
                        binding.tvTendencySelectTitle.text = "选择日期"
                        binding.tvTendencySelectDate.text =
                            SimpleDateFormat("yyyy-MM-dd").format(getdateMunise(-1))
                        binding.tvTendencyComparisonDate.text =
                            SimpleDateFormat("yyyy-MM-dd").format(getdateMunise(-2))
                        binding.tvShowDate.text =
                            SimpleDateFormat("yyyy-MM-dd").format(getdateMunise(-1))
                        binding.tvHideDate.text =
                            SimpleDateFormat("yyyy-MM-dd").format(getdateMunise(-2))

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

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

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

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

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

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

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

                        binding.mLineChart.visibility = View.GONE
                        binding.mBarChart.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.tvTendencySelectDate.text = yearDate
                        binding.tvTendencyComparisonDate.text = lastYear
                        binding.tvShowDate.text = yearDate
                        binding.tvHideDate.text = lastYear
                        type = 4

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

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

            override fun onTabReselect(position: Int) {
            }

        })

        //时间对比/选择时间
        setTimeSelect()
        timeSelectOrComparison()
        initBottomDialog()

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

                else -> {
                    RouteManager.goAct(ARouterUrl.DATAMANAGE_TYPE_ACT, bundle)
                }
            }
        }

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

    //时间对比/选择时间
    private fun timeSelectOrComparison() {
        //点击选择日期
        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.tvTendencyComparisonDate.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.tvTendencySelectDate.text.toString(),
                            comDateTime = binding.tvTendencyComparisonDate.text.toString()
                        )

                    }
                    timeSelectCompare.selectTime(it, "yyyy-MM-dd")
                }

                2 -> {
                    week = 2
                    val selectedDateStr = binding.tvTendencySelectDate.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()
                }

                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.tvTendencyComparisonDate.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.tvTendencySelectDate.text.toString(),
                            comDateTime = binding.tvTendencyComparisonDate.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.tvTendencyComparisonDate.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.tvTendencySelectDate.text.toString(),
                            comDateTime = binding.tvTendencyComparisonDate.text.toString()
                        )

                    }

                    timeYearSelectCompare.selectTimeWithYear(
                        it,
                        "yyyy"
                    )
                }
            }
        }
    }

    /**
     * 初始化时间选择器
     */
    @SuppressLint("SimpleDateFormat")
    private fun setTimeSelect() {
        var calendar = Calendar.getInstance()
        calendar.time = getdateMunise(-1)
        binding.tvTendencySelectDate.text = SimpleDateFormat("yyyy-MM-dd").format(calendar.time)
        binding.tvTendencyComparisonDate.text =
            SimpleDateFormat("yyyy-MM-dd").format(getdateMunise(-2))
        binding.tvShowDate.text = SimpleDateFormat("yyyy-MM-dd").format(calendar.time)
        binding.tvHideDate.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

            mViewModel.interceptingDate(
                id = id,
                type = type,
                dataType = pageType,
                dateTime = binding.tvTendencySelectDate.text.toString(),
                comDateTime = binding.tvTendencyComparisonDate.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.tvTendencyComparisonDate.text.toString()

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

            timeMonthSelect.selectTimeWithYearMonth(binding.tvTendencySelectDate, "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.tvTendencyComparisonDate.text.toString()

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

            timeYearSelect.selectTimeWithYearMonth(binding.tvTendencySelectDate, "yyyy")
        }

        timeYearSelect.startDate.set(Calendar.YEAR, 1922)
        timeYearSelect.endDate = calendaryear
        //年 的对比时间器
        calendaryear.add(Calendar.YEAR, -1)
        timeYearSelectCompare.createPvTime(this, calendaryear, 4) {
            // 在选择时间后执行的逻辑
            type = 4

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

        }
        timeYearSelectCompare.startDate.set(Calendar.YEAR, 1922)
        timeYearSelectCompare.endDate = calendaryear
    }

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

        adapter.setOnItemClickListener { adapter, view, position ->
            val weight = adapter.data[position] as HealthDataBean
            if (weight.upType == 3) {  //物联网上传
                bundle.clear()
                bundle.putString("pbfId", weight.pbfId)
            } else {
                bundle.clear()
                bundle.putSerializable("manageInfo", weight)
            }
            RouteManager.goAct(ARouterUrl.BODY_FAT_DETAIL, bundle)
        }

    }

    @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) {
        if (!TextUtils.isEmpty(event.height)) {
            heightStr = event.height
        }
        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()
//            chartLineListCompare.clear()
            if (it.data.model.size == 0 && it.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(
                                        DataManageChartBean(
                                            dateMinute.format(Date(time.toLong() * 1000)),
                                            model.dataValue,
                                            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(
                                        DataManageChartBean(
                                            dateMinute.format(Date(time.toLong() * 1000)),
                                            0f,
                                            model.dataValue,
                                            dayMinute.format(Date(time.toLong() * 1000)),
                                            dateMinute.format(Date(time.toLong() * 1000))
                                                .replace(":", ".").toDouble()
                                        )
                                    )
                                }
                            }
                        }

                        2 -> {//周
                            var split = binding.tvTendencySelectDate.text.toString().split("至")
                            var start = split[0]
                            var end = split[1]
                            it.data.model = it.data.fillMissingData(it.data.model, start, end)
                            split = binding.tvTendencyComparisonDate.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.tvTendencySelectDate.text.toString()
                            )
                            it.data.modelCompare = it.data.fillMissingData(
                                it.data.modelCompare,
                                binding.tvTendencyComparisonDate.text.toString()
                            )
                        }

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

            setChartdata(it.data)

            //设置页面数据
            val valueCompare = it.data.valueCompare
            val value = it.data.value
            binding.tvContrastData.text = if (valueCompare.avg == 0f) {
                "--" + getUnit(pageType.toInt())
            } else {
                valueCompare.avg.toString() + getUnit(pageType.toInt())
            }
            binding.tvSelectData.text = if (value.avg == 0f) {
                "--" + getUnit(pageType.toInt())
            } else {
                value.avg.toString() + getUnit(pageType.toInt())
            }
            if (valueCompare.avg > value.avg) {
                binding.ivDataContrastImg.setImageResource(imageIds[2])
            } else if (valueCompare.avg < value.avg) {
                binding.ivDataContrastImg.setImageResource(imageIds[1])
            } else {
                binding.ivDataContrastImg.setImageResource(imageIds[0])
            }
            val comprehensiveContent = it.data.comprehensiveContent
            if (!TextUtils.isEmpty(comprehensiveContent)) {
                binding.tvCompareContent.text = comprehensiveContent
            }
        }

        //获取网络请求数据列表
        mViewModel.getDataListOb.observe(this) {
            adapter.setNewInstance(it.data.records)
            adapter.notifyDataSetChanged()
            if (pageType == "3") {
                val records = it.data.records
                if (records.size > 0) {
                    val height = records[0].height
                    if (!TextUtils.isEmpty(height) && TextUtils.isEmpty(heightStr)) {
                        heightStr = height
                    }
                }
            }
        }

        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")
                    val dateMonth = SimpleDateFormat("MM-dd")
                    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()
        bmiLineList.clear()

        for ((i, chartList) in lineListData.withIndex()) {
            val listTipG = mutableListOf<String>()
            listTipG.add(chartList.time)
            listTipG.add(chartList.date)
            listTipG.add(chartList.dataValue.toString())
            listTipG.add(chartList.bmi.toString())
            listTipG.add("0")
//            listTipG.add(listCompare[listCompare.size - 1 - i].dataValue.toString())

            lineList.add(
                Entry(
                    i.toFloat(),
                    chartList.dataValue,
                    listTipG
                )
            )

            bmiLineList.add(
                Entry(
                    i.toFloat(),
                    chartList.bmi,
                    listTipG
                )
            )
        }
        binding.mLineChartList.clear()
        binding.mBMILineChartList.clear()

        /**
         * 设置体重趋势图
         */
        val lineChartMax = if (data.max >= 0) data.max + 10 else data.max
        val lineChartMin = if (data.min - 10 < 0) 0f else data.min - 10
        initLineChartList(
            binding.mLineChartList,
            lineChartMax,
            lineChartMin,
            true
        )

        /**
         * 设置BMI趋势图
         */
        val bmiMax = if (data.maxBmi >= 0) data.maxBmi + 10 else data.maxBmi
        val bmiMin = if (data.minBmi - 10 < 0) 0f else data.minBmi - 10
        initLineChartList(
            binding.mBMILineChartList,
            bmiMax,
            bmiMin,
            false
        )
    }

    //设置趋势图
    private fun initLineChartList(
        mLineChart: LineChart,
        max: Float,
        min: Float,
        lineChartType: Boolean
    ) {
        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()
            if (lineListData.size > 10) {
                m.postScale(2.8f, 1f)
            } else {
                m.postScale(0.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.textSize = 9f
            x.textColor = ContextCompat.getColor(this, 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, _ ->
                val index = value.toInt()
                //Log.e("x轴", "$value")
                if (lineChartType) {
                    if (index < 0 || index >= lineList.size) {
                        ""
                    } else {
                        "${(lineList[value.toInt()].data as MutableList<String>)[0]}\n${(lineList[value.toInt()].data as MutableList<String>)[1]}"
                    }
                } else {
                    if (index < 0 || index >= bmiLineList.size) {
                        ""
                    } else {
                        "${(bmiLineList[value.toInt()].data as MutableList<String>)[0]}\n${(bmiLineList[value.toInt()].data as MutableList<String>)[1]}"
                    }
                }
            }
            //y轴
            val y = it.axisLeft
            y.setLabelCountAndMaxMinValue(6, false, min, max)
            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)

            val markerView = if (lineChartType) {
                val markType = if (pageType == "3") {
                    ICompareMarkLineView.MarkPage.WEIGHT
                } else {
                    ICompareMarkLineView.MarkPage.TShu
                }
                ICompareMarkLineView(
                    this,
                    R.layout.mark_view_compare_line,
                    getUnit(pageType.toInt()),
                    markType
                )
            } else {
                ICompareMarkLineView(
                    this,
                    R.layout.mark_view_compare_line,
                    "",
                    ICompareMarkLineView.MarkPage.Bmi
                )
            }
            it.marker = markerView
            markerView.chartView = it
            it.axisRight.isEnabled = false
            it.legend.isEnabled = false

            //   it.animateXY(2000, 2000)  //设置xy轴进入的动画
            it.invalidate()
            if (lineList.isNotEmpty() && bmiLineList.isNotEmpty()) {
                val barsetsNew: java.util.ArrayList<ILineDataSet> = java.util.ArrayList()
                val segments = splitDataIntoSegmentsLineList(lineListData)
                if (lineChartType) {
                    val dataSets = segments.mapNotNull { segment ->
                        if (segment.isEmpty()) return@mapNotNull null
                        val entries = segment.mapIndexed { index, model ->
                            Entry(
                                index.toFloat(),
                                model.dataValue,
                                lineList[index].data
                            )
                        }
                        return@mapNotNull setLineListData(entries, mLineChart)
                    }
                    barsetsNew.addAll(dataSets)
                } else {
                    val dataSets = segments.mapNotNull { segment ->
                        if (segment.isEmpty()) return@mapNotNull null
                        val entries = segment.mapIndexed { index, model ->
                            Entry(
                                index.toFloat(),
                                model.bmi,
                                bmiLineList[index].data
                            )
                        }
                        return@mapNotNull setLineListData(entries, mLineChart)
                    }
                    barsetsNew.addAll(dataSets)
                }
                val lineData = LineData(barsetsNew)
                lineData.setValueTextSize(9f)
                lineData.setDrawValues(false)
                it.data = lineData

                if (lineChartType) {
                    it.moveViewToX(lineList[lineList.size - 1].x)
                } else {
                    it.moveViewToX(bmiLineList[bmiLineList.size - 1].x)
                }
            }
        }
    }

    private fun setLineListData(values: List<Entry>?, mLineChart: LineChart): 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, 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, R.color.col_e0b)  //设置点后高亮颜色
            set1.enableDashedHighlightLine(10f, 5f, 0f)
            set1.setCircleColor(
                ContextCompat.getColor(
                    this,
                    R.color.col_41c
                )
            )    //#41C4AF
            set1.color = ContextCompat.getColor(this, 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, _, _, _ ->
                "$value"
            }

        }
        return set1
    }

    private fun setChartdata(data: DataManageTendencyBean) {
        list.clear()
        listCompare.clear()
        list.addAll(data.model)
        listCompare.addAll(data.modelCompare)
        lineValue.clear()
        lineValueCompare.clear()
        barValue.clear()
        barValueCompare.clear()
        if (type != 1) {
            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
                            )
                        )
                    }
                }
            }
            val rever: IntProgression = if (list.size < listCompare.size) {
                (listCompare.indices).reversed()
            } else {
                (list.indices).reversed()
            }
            for (i in rever) {
                //中间两端在x轴显示尺度 其他情况下不显示
                when (type) {
                    2 -> {
                        val listTipW = mutableListOf<String>()
                        listTipW.add(weeker[weeker.size - i - 1])
                        listTipW.add("0")
                        listTipW.add(list[list.size - 1 - i].dataValue.toString())
                        listTipW.add(listCompare[listCompare.size - 1 - i].dataValue.toString())
                        barValue.add(
                            BarEntry(
                                (list.size - 1 - i).toFloat(),
                                list[list.size - 1 - i].dataValue,
                                listTipW
                            )
                        )
                        barValueCompare.add(
                            BarEntry(
                                (listCompare.size - 1 - i).toFloat(),
                                listCompare[listCompare.size - 1 - i].dataValue,
                                listTipW
                            )
                        )
                    }

                    3 -> {
                        val listTipY = mutableListOf<String>()
                        listTipY.add(list[list.size - 1 - i].time)
                        listTipY.add("0")
                        listTipY.add(list[list.size - 1 - i].dataValue.toString())
                        listTipY.add(listCompare[listCompare.size - 1 - i].dataValue.toString())
                        barValue.add(
                            BarEntry(
                                (list.size - 1 - i).toFloat(),
                                list[list.size - 1 - i].dataValue,
                                listTipY
                            )
                        )
                        barValueCompare.add(
                            BarEntry(
                                (listCompare.size - 1 - i).toFloat(),
                                listCompare[listCompare.size - 1 - i].dataValue,
                                listTipY
                            )
                        )
                    }

                    else -> {
                        val listTipY = mutableListOf<String>()
                        listTipY.add(list[list.size - 1 - i].time)
                        listTipY.add("0")
                        listTipY.add(list[list.size - 1 - i].dataValue.toString())
                        listTipY.add(listCompare[listCompare.size - 1 - i].dataValue.toString())
                        barValue.add(
                            BarEntry(
                                (list.size - 1 - i).toFloat(),
                                list[list.size - 1 - i].dataValue,
                                listTipY
                            )
                        )
                        barValueCompare.add(
                            BarEntry(
                                (listCompare.size - 1 - i).toFloat(),
                                listCompare[listCompare.size - 1 - i].dataValue,
                                listTipY
                            )
                        )
                    }
                }
            }
        } else {
            chartLineList.sortWith { u1, u2 ->
                u1.sort.compareTo(u2.sort)
            }
            for ((index, dataManageChartBean) in chartLineList.withIndex()) {
                dataManageChartBean.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].dataValue.toString())
                listTipG.add(chartLineList[chartLineList.size - 1 - i].dataValueCompare.toString())

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

                lineValueCompare.add(
                    Entry(
                        (chartLineList.size - 1 - i).toFloat(),
                        chartLineList[chartLineList.size - 1 - i].dataValueCompare,
                        listTipG
                    )
                )
            }
        }

        binding.mLineChart.clear()
        binding.mBarChart.clear()
        var min: Float = if (data.value.min != 0f && data.valueCompare.min != 0f) {
            if (data.value.min < data.valueCompare.min) {
                data.value.min
            } else {
                data.valueCompare.min
            }
        } else if (data.value.min == 0f && data.valueCompare.min != 0f) {
            data.valueCompare.min
        } else if (data.valueCompare.min == 0f && data.value.min != 0f) {
            data.value.min
        } else {
            min(data.value.min, data.valueCompare.min)
        }

        var max: Float = if (data.value.max != 0f && data.valueCompare.max != 0f) {
            if (data.value.max > data.valueCompare.max) {
                data.value.max
            } else {
                data.valueCompare.max
            }
        } else if (data.value.max == 0f && data.valueCompare.max != 0f) {
            data.valueCompare.max
        } else if (data.valueCompare.max == 0f && data.value.max != 0f) {
            data.value.max
        } else {
            max(data.value.max, data.value.max)
        }
        min = if (min - 5 < 0) min else min - 5
        max = if (max > 0) max else max + 5
        initChart(min, max)
    }

    //设置趋势图
    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(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 ->
                    val 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, max)
                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, "kg",
                    ICompareMarkView.MarkPage.XTang
                )
                it.marker = markerView
                markerView.chartView = it
                it.axisRight.isEnabled = false
                it.legend.isEnabled = false

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

                    val segments = splitDataIntoSegmentsLine(chartLineList)
                    val dataSets = segments.mapNotNull { segment ->
                        if (segment.isEmpty()) return@mapNotNull null

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

                        return@mapNotNull setData(entries)
                    }
                    val segmentsCompare = splitDataIntoSegmentsLineCompare(chartLineList)
                    val dataSetsCompare = segmentsCompare.mapNotNull { segment ->
                        if (segment.isEmpty()) return@mapNotNull null

                        val entries = segment.mapIndexed { index, model ->
                            Entry(
                                model.index.toFloat(),
                                model.dataValueCompare,
                                lineValueCompare[model.index].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(this, 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）功能。
                setChartData(barValue.size, it)
                it.isScaleXEnabled = true  //支持x轴缩放
                it.isScaleYEnabled = false //支持Y轴缩放

                val x = it.xAxis
                x.granularity = 1f  //精准设置
                x.textColor = ContextCompat.getColor(this, R.color.col_92a)
                x.textSize = 9f
                x.axisMinimum = 0f

//                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 ->
                    val 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, true, min, max)
                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)
                y.xOffset = 5f
                val markerView = ICompareMarkView(
                    this,
                    R.layout.mark_view_compare,
                    getUnit(pageType.toInt()),
                    ICompareMarkView.MarkPage.Temp
                )
                it.marker = markerView
                markerView.chartView = it
                it.axisRight.isEnabled = false
                it.legend.isEnabled = false

//                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, R.color.col_9BDd)
                set1.highLightColor =
                    ContextCompat.getColor(this, R.color.col_C6B)  //设置点后高亮颜色
                set1.color =
                    ContextCompat.getColor(this, R.color.col_9BDd) //xian de yanse
                sets.add(set1)

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

                val set2 = BarDataSet(barValueCompare, "DataSet2")
                set2.setDrawValues(false) // 不显示值
                set2.valueTextColor = ContextCompat.getColor(this, R.color.col_8c6)
                set2.highLightColor =
                    ContextCompat.getColor(this, R.color.col_8c6)  //设置点后高亮颜色
                set2.color =
                    ContextCompat.getColor(this, R.color.col_9BD) //xian de yanse
//                val data2 = BarData(set2)
                sets.add(set2)
                val 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 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, 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, R.color.col_e0b)  //设置点后高亮颜色
            set1.enableDashedHighlightLine(10f, 5f, 0f)
            set1.setCircleColor(
                ContextCompat.getColor(
                    this,
                    R.color.col_41c
                )
            )    //#41C4AF
            set1.color = ContextCompat.getColor(this, 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, _, _, _ ->
                "$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.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, R.color.col_9BD) //xian de yanse
            set1.setDrawHorizontalHighlightIndicator(false)
            set1.fillFormatter =
                IFillFormatter { _, _ -> binding.mLineChart.axisLeft.axisMinimum }
            set1.setValueFormatter { value, _, _, _ ->
                "$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 splitDataIntoSegmentsLine(dataList: MutableList<DataManageChartBean>):
            MutableList<MutableList<DataManageChartBean>> {
        val segments = mutableListOf<MutableList<DataManageChartBean>>()
        var currentSegment = mutableListOf<DataManageChartBean>()

        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
    }

    private fun splitDataIntoSegmentsLineCompare(dataList: MutableList<DataManageChartBean>):
            MutableList<MutableList<DataManageChartBean>> {
        val segments = mutableListOf<MutableList<DataManageChartBean>>()
        var currentSegment = mutableListOf<DataManageChartBean>()

        for (model in dataList) {
            if (model.dataValueCompare.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.dataValue.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 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
    }

    private fun checkData(segmentsCompare: MutableList<MutableList<DataManageChartBean>>):
            MutableList<MutableList<DataManageChartBean>> {
        if (segmentsCompare[0][0].time != "00:00") {
            val d = mutableListOf<DataManageChartBean>()
            val b = DataManageChartBean(
                "00:00",
                0f,
                0f,
                "",
                0.0
            )
            d.add(b)
            segmentsCompare.add(d)
        }
        if (segmentsCompare[segmentsCompare.size - 1][segmentsCompare[segmentsCompare.size - 1].size - 1].time != "23:50") {
            val d = mutableListOf<DataManageChartBean>()
            val b = DataManageChartBean(
                "00:00",
                0f,
                0f,
                "",
                0.0
            )
            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

        // 计算对应的索引值
        return totalMinutes / 10
    }

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

    override fun setLayout() = binding.root

    @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
    }

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