package com.zj365.health.act.datamanage

//noinspection SuspiciousImport
import android.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.BarEntry
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
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.ActXzhiDataManageBinding
import com.zj365.health.fragment.bloodlipid.BaseChartInitUtils
import com.zj365.health.fragment.bloodlipid.BloodLipidGetMinMaxChart
import com.zj365.health.model.XZhiCompareDataBean
import com.zj365.health.util.HealthDateAndTimeUtils
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.BloodLipidDataBean
import com.xty.network.model.RecentlyHealthBean
import com.xty.network.model.XZhiDataManageChartBean
import com.xty.network.model.XZhiRecentlyChartBean
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.DATAMANAGE_XZHI_ACT)
class XZhiDataManageAct : BaseListAct<DataManageVm>() {

    private val binding by lazy { ActXzhiDataManageBinding.inflate(layoutInflater) }
    override fun setLayout(): View = binding.root

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

    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 { XZhiDataManageListAdapter() }

    val compareAdapter by lazy { XZhiCompareDataListAdapter() }

    /**
     * 趋势图
     */
    private val weeker by lazy { arrayOf("周一", "周二", "周三", "周四", "周五", "周六", "周日") }


    private var zdgcLineList = arrayListOf<Entry>()  //总胆固醇曲线数据
    private var gyszLineList = arrayListOf<Entry>()  //甘油三酯曲线数据
    private var gmdzdbLineList = arrayListOf<Entry>()  //高密度脂蛋白曲线数据
    private var dmdzdbLineList = arrayListOf<Entry>()  //低密度脂蛋白曲线数据
    private var lineListData: MutableList<XZhiRecentlyChartBean> = mutableListOf()

    private var titleStr = ""
    private 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 对比
    private var id: String = ""

    private var chartLineList: MutableList<XZhiDataManageChartBean> = mutableListOf()//（日）趋势图数据集合

    //添加数据弹窗
    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 -> }
        )
    }

    @SuppressLint("SuspiciousIndentation", "InflateParams")
    fun initBottomDialog() {
        bottomSheetDialog.let { dialog ->
            val view =
                LayoutInflater.from(this).inflate(com.zj365.health.R.layout.bottom_sheet_layout, null)
            dialog.setContentView(view)
            weekWheelView = view.findViewById<WheelView>(com.zj365.health.R.id.wheelView)
            weekWheelView?.setCyclic(false)
            val list = HealthDateAndTimeUtils.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>(com.zj365.health.R.id.cancel_button)
            val confirmButton = view.findViewById<TextView>(com.zj365.health.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.lineBarChart.tvShowDate.text = item.toString()
                    weekDate = binding.tvTendencySelectDate.text.toString()

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

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

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

    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(HealthDateAndTimeUtils.getDateAdd(6), "yyyy-MM-dd")}至$dayDate"
        mouthDate = TimeUtils.date2String(currentDay, "yyyy-MM")
        yearDate = TimeUtils.date2String(currentDay, "yyyy")

        //初始化tab
        initTab()

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

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

        initBottomDialog()
    }

    /**
     * 初始化tab
     */
    private fun initTab() {
        mTabEntities.clear()
        mTitles.forEach {
            mTabEntities.add(
                TabEntity(
                    it, R.drawable.ic_delete, R.drawable.ic_delete
                )
            )
        }
        binding.lineBarChart.commonTabLayout.setTabData(mTabEntities)
        binding.lineBarChart.commonTabLayout.setOnTabSelectListener(object : OnTabSelectListener {
            @SuppressLint("SetTextI18n", "SimpleDateFormat")
            override fun onTabSelect(position: Int) {
                binding.lineBarChart.commonTabLayout.currentTab = position

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

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

                        //总胆固醇
                        binding.lineBarChart.dgcCompareLineChart.visibility = View.VISIBLE
                        binding.lineBarChart.dgcCompareBarChart.visibility = View.GONE
                        //甘油三酯
                        binding.lineBarChart.gyszCompareLineChart.visibility = View.VISIBLE
                        binding.lineBarChart.gyszCompareBarChart.visibility = View.GONE
                        //高密度脂蛋白
                        binding.lineBarChart.gmdzdbCompareLineChart.visibility = View.VISIBLE
                        binding.lineBarChart.gmdzdbCompareBarChart.visibility = View.GONE
                        //低密度脂蛋白
                        binding.lineBarChart.dmdzdbCompareLineChart.visibility = View.VISIBLE
                        binding.lineBarChart.dmdzdbCompareBarChart.visibility = View.GONE

                    }

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

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

                        //总胆固醇
                        binding.lineBarChart.dgcCompareLineChart.visibility = View.GONE
                        binding.lineBarChart.dgcCompareBarChart.visibility = View.VISIBLE
                        //甘油三酯
                        binding.lineBarChart.gyszCompareLineChart.visibility = View.GONE
                        binding.lineBarChart.gyszCompareBarChart.visibility = View.VISIBLE
                        //高密度脂蛋白
                        binding.lineBarChart.gmdzdbCompareLineChart.visibility = View.GONE
                        binding.lineBarChart.gmdzdbCompareBarChart.visibility = View.VISIBLE
                        //低密度脂蛋白
                        binding.lineBarChart.dmdzdbCompareLineChart.visibility = View.GONE
                        binding.lineBarChart.dmdzdbCompareBarChart.visibility = View.VISIBLE
                    }

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

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

                        //总胆固醇
                        binding.lineBarChart.dgcCompareLineChart.visibility = View.GONE
                        binding.lineBarChart.dgcCompareBarChart.visibility = View.VISIBLE
                        //甘油三酯
                        binding.lineBarChart.gyszCompareLineChart.visibility = View.GONE
                        binding.lineBarChart.gyszCompareBarChart.visibility = View.VISIBLE
                        //高密度脂蛋白
                        binding.lineBarChart.gmdzdbCompareLineChart.visibility = View.GONE
                        binding.lineBarChart.gmdzdbCompareBarChart.visibility = View.VISIBLE
                        //低密度脂蛋白
                        binding.lineBarChart.dmdzdbCompareLineChart.visibility = View.GONE
                        binding.lineBarChart.dmdzdbCompareBarChart.visibility = View.VISIBLE
                    }

                    3 -> {
                        binding.lineBarChart.showTitle.text = "选择年"
                        binding.lineBarChart.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.lineBarChart.tvShowDate.text = yearDate
                        binding.lineBarChart.tvHideDate.text = lastYear
                        binding.tvTendencySelectDate.text = yearDate
                        binding.tvTendencyComparisonDate.text = lastYear
                        type = 4

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

                        //总胆固醇
                        binding.lineBarChart.dgcCompareLineChart.visibility = View.GONE
                        binding.lineBarChart.dgcCompareBarChart.visibility = View.VISIBLE
                        //甘油三酯
                        binding.lineBarChart.gyszCompareLineChart.visibility = View.GONE
                        binding.lineBarChart.gyszCompareBarChart.visibility = View.VISIBLE
                        //高密度脂蛋白
                        binding.lineBarChart.gmdzdbCompareLineChart.visibility = View.GONE
                        binding.lineBarChart.gmdzdbCompareBarChart.visibility = View.VISIBLE
                        //低密度脂蛋白
                        binding.lineBarChart.dmdzdbCompareLineChart.visibility = View.GONE
                        binding.lineBarChart.dmdzdbCompareBarChart.visibility = View.VISIBLE
                    }
                }
            }

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

    /**
     * 初始化控件点击事件
     */
    @SuppressLint("SimpleDateFormat")
    private fun initOnClick() {
        //选择时间按钮
        binding.lineBarChart.tvShowDate.setOnClickListener {
            when (type) {
                1 -> {
                    timeSelect.selectTime(it, "yyyy-MM-dd")
                }

                2 -> {
                    week = 1
                    val list = HealthDateAndTimeUtils.buildWeekLower26(null)
                    weekWheelView?.adapter = ArrayWheelAdapter(list)
                    bottomSheetDialog.show()
                }

                3 -> {
                    timeMonthSelect.selectTimeWithYearMonth(it, "yyyy-MM")
                }

                4 -> {
                    timeYearSelect.selectTimeWithYear(it, "yyyy")
                }
            }
        }

        //对比时间按钮
        binding.lineBarChart.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.lineBarChart.tvHideDate.text.toString())
                        if (date != null) {
                            calendar.time = date
                        }
                    }
                    timeSelectCompare.createPvTime(this, calendar, 1) {
                        // 在选择时间后执行的逻辑
                        type = 1
                        val compareTime = binding.lineBarChart.tvHideDate.text.toString()
                        binding.tvTendencyComparisonDate.text = compareTime

                        mViewModel.interceptingDate(
                            id = id,
                            type = type,
                            dataType = pageType,
                            dateTime = binding.lineBarChart.tvShowDate.text.toString(),
                            comDateTime = binding.lineBarChart.tvHideDate.text.toString()
                        )
                    }
                    timeSelectCompare.selectTime(it, "yyyy-MM-dd")
                }

                2 -> {
                    val selectedDateStr = binding.lineBarChart.tvShowDate.text
                    if (selectedDateStr != null) {
                        val selectedDateSpit = selectedDateStr.split("至")
                        selectedDateSpit.let { split ->
                            if (split.size >= 2) {
                                val selectedStartStr = split[0]
                                val list = HealthDateAndTimeUtils.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.lineBarChart.tvHideDate.text.toString())
                        if (date != null) {
                            calendar.time = date
                        }
                    }

                    timeMonthSelectCompare.createPvTime(this, calendar, 3) {
                        // 在选择时间后执行的逻辑
                        type = 3
                        val compareTime = binding.lineBarChart.tvHideDate.text.toString()
                        binding.tvTendencyComparisonDate.text = compareTime

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

                        mViewModel.interceptingDate(
                            id = id,
                            type = type,
                            dataType = pageType,
                            dateTime = binding.lineBarChart.tvShowDate.text.toString(),
                            comDateTime = binding.lineBarChart.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_XZHI_TYPE_ACT, bundle)
        }

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

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

        //日 的选择时间器
        timeSelect.createPvTime(this, calendar, 1) {
            // 在选择时间后执行的逻辑
            type = 1
            val selectTime = binding.lineBarChart.tvShowDate.text.toString()
            binding.tvTendencySelectDate.text = selectTime
            dayDate = selectTime
//            dayDate = binding.lineBarChart.tvShowDate.text.toString()

            mViewModel.interceptingDate(
                id = id,
                type = type,
                dataType = pageType,
                dateTime = binding.lineBarChart.tvShowDate.text.toString(),
                comDateTime = binding.lineBarChart.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.lineBarChart.tvShowDate.text.toString()
            binding.tvTendencySelectDate.text = selectTime
            mouthDate = selectTime
//            mouthDate = binding.lineBarChart.tvHideDate.text.toString()

            mViewModel.interceptingDate(
                id = id,
                type = type,
                dataType = pageType,
                dateTime = binding.lineBarChart.tvShowDate.text.toString(),
                comDateTime = binding.lineBarChart.tvHideDate.text.toString()
            )
            timeMonthSelect.selectTimeWithYearMonth(binding.lineBarChart.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.lineBarChart.tvShowDate.text.toString()
            binding.tvTendencySelectDate.text = selectTime
            mouthDate = selectTime
//            mouthDate = binding.lineBarChart.tvHideDate.text.toString()

            mViewModel.interceptingDate(
                id = id,
                type = type,
                dataType = pageType,
                dateTime = binding.lineBarChart.tvShowDate.text.toString(),
                comDateTime = binding.lineBarChart.tvHideDate.text.toString()
            )
            timeYearSelect.selectTimeWithYearMonth(binding.lineBarChart.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.lineBarChart.tvShowDate.text.toString(),
                comDateTime = binding.lineBarChart.tvHideDate.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.addChildClickViewIds(
            com.zj365.health.R.id.root,
        )

        binding.rvCompareConclusionList.layoutManager = LinearLayoutManager(this)
        binding.rvCompareConclusionList.adapter = compareAdapter
    }

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

    /**
     * 数据刷新
     */
    private fun dataRefresh() {
        //数据列表网络请求
        mViewModel.getDataList(
            id,
            pageType,
            "1",
            page,
            "",
            "",
            pageSize = 2
        )

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

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

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

        var calendar = Calendar.getInstance()
        calendar.time = HealthDateAndTimeUtils.getdateMunise(-1)
        var startTime  =""
        var endTime = ""

        if (TextUtils.isEmpty(binding.lineBarChart.tvShowDate.text.toString())){
            startTime   = SimpleDateFormat("yyyy-MM-dd").format(calendar.time)

        }else{
            startTime = binding.lineBarChart.tvShowDate.text.toString()
        }

        if (TextUtils.isEmpty(binding.lineBarChart.tvHideDate.text.toString())){
            endTime =  SimpleDateFormat("yyyy-MM-dd").format(HealthDateAndTimeUtils.getdateMunise(-2))
        }else{
            endTime  = binding.lineBarChart.tvHideDate.text.toString()
        }
        mViewModel.interceptingDate(
            id = id,
            type = type,
            dataType = pageType,
            dateTime = startTime,
            comDateTime = endTime
        )
    }

    @SuppressLint("SetTextI18n")
    override fun liveObserver() {
        mViewModel.getBloodLipidReturnData.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())
                            val dayAndData =  SimpleDateFormat("MM-dd HH:mm", Locale.getDefault())

                            if (it.data.model.size > 0) {
                                for (model in it.data.model) {
                                    val time = model.time
                                    chartLineList.add(
                                        XZhiDataManageChartBean(
                                            dateMinute.format(Date(time.toLong() * 1000)),
                                            model.tc,
                                            model.tg,
                                            model.hdl,
                                            model.ldl,
                                            0f,
                                            0f,
                                            0f,
                                            0f,
                                            dayMinute.format(Date(time.toLong() * 1000)),
                                            dateMinute.format(Date(time.toLong() * 1000))
                                                .replace(":", ".").toDouble(),
                                            dayMinute.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(
                                        XZhiDataManageChartBean(
                                            dateMinute.format(Date(time.toLong() * 1000)),
                                            0f,
                                            0f,
                                            0f,
                                            0f,
                                            model.tc,
                                            model.tg,
                                            model.hdl,
                                            model.ldl,
                                            dayMinute.format(Date(time.toLong() * 1000)),
                                            dateMinute.format(Date(time.toLong() * 1000))
                                                .replace(":", ".").toDouble(),
                                            dayMinute.format(Date(time.toLong() * 1000)) .replace("-", ".").toDouble()
                                        )
                                    )
                                }
                            }
                        }

                        2 -> {//周

                            var split = binding.lineBarChart.tvShowDate.text.toString().split("至")
                            var start = split[0]
                            var end = split[1]
                            data.model = data.fillMissingData(data.model, start, end)
                            split = binding.lineBarChart.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.lineBarChart.tvShowDate.text.toString()
                            )
                            data.modelCompare = data.fillMissingData(
                                data.modelCompare,
                                binding.lineBarChart.tvHideDate.text.toString()
                            )
                        }

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

                        }
                    }
                }
            }

            setTCChartData(data)
            setTGChartData(data)
            setHDLChartData(data)
            setLDLChartData(data)

            var compareDataList = ArrayList<XZhiCompareDataBean>()
            var tcCompareData = XZhiCompareDataBean("总胆固醇",data.valueCompare.avgTc,data.value.avgTc)
            var tgCompareData = XZhiCompareDataBean("甘油三酯",data.valueCompare.avgTg,data.value.avgTg)
            var hdlCompareData = XZhiCompareDataBean("高密度脂蛋白",data.valueCompare.avgHdl,data.value.avgHdl)
            var ldlCompareData = XZhiCompareDataBean("低密度脂蛋白",data.valueCompare.avgLdl,data.value.avgLdl)
            compareDataList.add(tcCompareData)
            compareDataList.add(tgCompareData)

            compareDataList.add(hdlCompareData)

            compareDataList.add(ldlCompareData)
            compareAdapter.setNewInstance(compareDataList)



            //设置页面数据
            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.clear()
        zdgcLineList.clear()
        gyszLineList.clear()
        gmdzdbLineList.clear()
        dmdzdbLineList.clear()
        data.list.forEach {
            lineListData.add(
                XZhiRecentlyChartBean(
                    time = it.time,
                    hdl = it.hdl,
                    ldl = it.ldl,
                    tc = it.tc,
                    tg = it.tg,
                    date = it.date
                )
            )
        }

        for ((i, chartList) in lineListData.withIndex()) {
            val listTipG = mutableListOf<String>()
            listTipG.add(chartList.time)
            listTipG.add(chartList.date)
            listTipG.add(chartList.hdl.toString())
            listTipG.add(chartList.ldl.toString())
            listTipG.add(chartList.tc.toString())
            listTipG.add(chartList.tg.toString())
            zdgcLineList.add(
                Entry(
                    i.toFloat(),
                    chartList.tc,
                    listTipG
                )
            )
            gyszLineList.add(
                Entry(
                    i.toFloat(),
                    chartList.tg,
                    listTipG
                )
            )
            gmdzdbLineList.add(
                Entry(
                    i.toFloat(),
                    chartList.hdl,
                    listTipG
                )
            )
            dmdzdbLineList.add(
                Entry(
                    i.toFloat(),
                    chartList.ldl,
                    listTipG
                )
            )
        }
        binding.lineChart.dgcLineChartList.clear()
        binding.lineChart.gyszLineChartList.clear()
        binding.lineChart.gmdzdbLineChartList.clear()
        binding.lineChart.dmdzdbLineChartList.clear()
        //总胆固醇
        var tcMax = data.maxTc
        var tcmin = data.minTc
        tcMax = if (tcMax >= 0) tcMax + 1 else tcMax
        tcmin = if (tcmin - 1 < 0) tcmin else tcmin - 1
        //甘油三酯
        var tgMax = data.maxTg
        var tgmin = data.minTg
        tgMax = if (tgMax >= 0) tgMax + 1 else tgMax
        tgmin = if (tgmin - 1 < 0) tgmin else tgmin - 1
        //高密度蛋白
        var hdlMax = data.maxHdl
        var hdlmin = data.minHdl
        hdlMax = if (hdlMax >= 0) hdlMax + 1 else hdlMax
        hdlmin = if (hdlmin - 1 < 0) hdlmin else hdlmin - 1
        //低密度蛋白
        var ldlMax = data.maxLdl
        var ldlmin = data.minLdl
        ldlMax = if (ldlMax >= 0) ldlMax + 1 else ldlMax
        ldlmin = if (ldlmin - 1 < 0) ldlmin else ldlmin - 1
        //设置总胆固醇线性趋势图
        initLineChartList(
            1,
            tcMax,
            tcmin,
            zdgcLineList,
            binding.lineChart.dgcLineChartList
        )
        //设置甘油三酯线性趋势图
        initLineChartList(
            2,
            tgMax,
            tgmin,
            gyszLineList,
            binding.lineChart.gyszLineChartList
        )
        //设置高密度蛋白线性趋势图
        initLineChartList(
            3,
            hdlMax,
            hdlmin,
            gmdzdbLineList,
            binding.lineChart.gmdzdbLineChartList
        )
        //设置低密度蛋白线性趋势图
        initLineChartList(
            4,
            ldlMax,
            ldlmin,
            dmdzdbLineList,
            binding.lineChart.dmdzdbLineChartList
        )
    }

    lateinit var ldlList: MutableList<BloodLipidDataBean.ModelBean>
    private lateinit var ldlListCompare: MutableList<BloodLipidDataBean.ModelBean>


    var ldlLineValue = arrayListOf<Entry>()  //线形数据
    var ldlLineValueCompare = arrayListOf<Entry>()  //线形数据

    var ldlBarValue = arrayListOf<BarEntry>()  //柱形数据
    var ldlBarValueCompare = arrayListOf<BarEntry>()  //柱形数据
    private fun setLDLChartData(data: BloodLipidDataBean) {
        ldlList = data.model
        ldlListCompare = data.modelCompare
        ldlBarValue.clear()
        ldlBarValueCompare.clear()
        ldlLineValue.clear()
        ldlLineValueCompare.clear()
        if(type != 1){
            var rever: IntProgression
            if (ldlList.size < ldlListCompare.size) {
                rever = (ldlListCompare.indices).reversed()
            } else {
                rever = (ldlList.indices).reversed()
            }
            if (type == 3) {
                var compare = ldlListCompare.size - ldlList.size
                if (compare > 0) {
                    for (Int in 1..compare) {
                        ldlList.add(ldlList.size,
                            BloodLipidDataBean.ModelBean(0f,0f,0f,0f,ldlListCompare[ldlList.size].time))
                    }
                } else if (compare < 0) {
                    compare = 0 - compare
                    for (Int in 1..compare) {
                        ldlListCompare.add(
                            ldlListCompare.size,
                            BloodLipidDataBean.ModelBean(0f,0f,0f,0f,ldlList[ldlListCompare.size].time)
                        )
                    }
                }
            }
            for (i in rever) {
                //中间两端在x轴显示尺度 其他情况下不显示
                if (type == 1) {
                    var listTipG = mutableListOf<String>()
                    listTipG.add(ldlList[ldlList.size - 1 - i].time)
                    listTipG.add("0")
                    listTipG.add(ldlList[ldlList.size - 1 - i].ldl.toString())
                    listTipG.add(ldlListCompare[ldlListCompare.size - 1 - i].ldl.toString())

                    if (ldlList[ldlList.size - 1 - i].ldl == 0f) {
                        ldlList[ldlList.size - 1 - i].ldl = Float.NaN
                    } else {
                        ldlList[ldlList.size - 1 - i].ldl
                    }
                    ldlLineValue.add(
                        Entry(
                            (ldlList.size - 1 - i).toFloat(),
                            ldlList[ldlList.size - 1 - i].ldl,
                            listTipG
                        )
                    )



                    if (ldlListCompare[ldlListCompare.size - 1 - i].ldl == 0f)
                        ldlListCompare[ldlListCompare.size - 1 - i].ldl = Float.NaN
                    else
                        ldlListCompare[ldlListCompare.size - 1 - i].ldl

                    ldlLineValueCompare.add(
                        Entry(
                            (ldlListCompare.size - 1 - i).toFloat(),
                            ldlListCompare[ldlListCompare.size - 1 - i].ldl,
                            listTipG
                        )
                    )



                } else if (type == 2) {
                    var listTipW = mutableListOf<String>()
                    listTipW.add(weeker[weeker.size - i - 1])
                    listTipW.add("0")
                    listTipW.add(ldlList[ldlList.size - 1 - i].ldl.toString())
                    listTipW.add(ldlListCompare[ldlListCompare.size - 1 - i].ldl.toString())
                    ldlBarValue.add(
                        BarEntry(
                            (ldlList.size - 1 - i).toFloat(),
                            ldlList[ldlList.size - 1 - i].ldl,
                            listTipW

                        )
                    )
                    ldlBarValueCompare.add(
                        BarEntry(
                            (ldlListCompare.size - 1 - i).toFloat(),
                            ldlListCompare[ldlListCompare.size - 1 - i].ldl,
                            listTipW
                        )
                    )
                } else if (type == 3) {

                    var listTipY = mutableListOf<String>()
                    listTipY.add(ldlList[ldlList.size - 1 - i].time)
                    listTipY.add("0")
                    listTipY.add(ldlList[ldlList.size - 1 - i].ldl.toString())
                    listTipY.add(ldlListCompare[ldlListCompare.size - 1 - i].ldl.toString())
                    ldlBarValue.add(
                        BarEntry(
                            (ldlList.size - 1 - i).toFloat(),
                            ldlList[ldlList.size - 1 - i].ldl,
                            listTipY
                        )
                    )
                    ldlBarValueCompare.add(
                        BarEntry(
                            (ldlListCompare.size - 1 - i).toFloat(),
                            ldlListCompare[ldlListCompare.size - 1 - i].ldl,
                            listTipY
                        )
                    )
                } else {
                    var listTipY = mutableListOf<String>()
                    listTipY.add(ldlList[ldlList.size - 1 - i].time)
                    listTipY.add("0")
                    listTipY.add(ldlList[ldlList.size - 1 - i].ldl.toString())
                    listTipY.add(ldlListCompare[ldlListCompare.size - 1 - i].ldl.toString())
                    ldlBarValue.add(
                        BarEntry(
                            (ldlList.size - 1 - i).toFloat(),
                            ldlList[ldlList.size - 1 - i].ldl,
                            listTipY
                        )
                    )
                    ldlBarValueCompare.add(
                        BarEntry(
                            (ldlListCompare.size - 1 - i).toFloat(),
                            ldlListCompare[ldlListCompare.size - 1 - i].ldl,
                            listTipY
                        )
                    )
                }
            }
        }else{
            chartLineList.sortWith { u1, u2 ->
                //       u1.sortDate.compareTo(u2.sortDate)
                if(u1.sortDate != u2.sortDate){
                    u1.sortDate.compareTo(u2.sortDate)
                }else{
                    u1.sort.compareTo(u2.sort)

                }
            }
            for ((index, xXZhiDataManageChartBean) in chartLineList.withIndex()) {
                xXZhiDataManageChartBean.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].ldl.toString())
                listTipG.add(chartLineList[chartLineList.size - 1 - i].ldlCompare.toString())

                if (chartLineList[chartLineList.size - 1 - i].ldl == 0f) {
                    chartLineList[chartLineList.size - 1 - i].ldl = Float.NaN
                } else {
                    chartLineList[chartLineList.size - 1 - i].ldl
                }
                if (chartLineList[chartLineList.size - 1 - i].ldlCompare == 0f) {
                    chartLineList[chartLineList.size - 1 - i].ldlCompare = Float.NaN
                } else {
                    chartLineList[chartLineList.size - 1 - i].ldlCompare
                }
                ldlLineValue.add(
                    Entry(
                        (chartLineList.size - 1 - i).toFloat(),
                        chartLineList[chartLineList.size - 1 - i].ldl,
                        listTipG
                    )
                )
                ldlLineValueCompare.add(
                    Entry(
                        (chartLineList.size - 1 - i).toFloat(),
                        chartLineList[chartLineList.size - 1 - i].ldlCompare,
                        listTipG
                    )
                )
            }
        }

        binding.lineBarChart.dmdzdbCompareLineChart.clear()
        binding.lineBarChart.dmdzdbCompareBarChart.clear()

        val min = BloodLipidGetMinMaxChart.getBloodLipidMix(data.value.minLdl,data.valueCompare.minLdl)

        val max = BloodLipidGetMinMaxChart.getBloodLipidMax(data.value.maxLdl,data.valueCompare.maxLdl)
        if(type == 1){
            initChart(min, max,binding.lineBarChart.dmdzdbCompareLineChart,ldlLineValue,ldlLineValueCompare,ldlList,4)
        }else{
            BaseChartInitUtils.initBarChartTwo(this,binding.lineBarChart.dmdzdbCompareBarChart,
                min,max,ldlBarValue,ldlBarValueCompare,
                ICompareMarkView.MarkPage.BloodFilip,"mmol/L",type,1f)
//            initBarChart(min, max,binding.lineBarChart.dmdzdbCompareBarChart,ldlBarValue,ldlBarValueCompare)
        }
    }

    lateinit var hdlList: MutableList<BloodLipidDataBean.ModelBean>
    private lateinit var hdlListCompare: MutableList<BloodLipidDataBean.ModelBean>


    var hdlLineValue = arrayListOf<Entry>()  //线形数据
    var hdlLineValueCompare = arrayListOf<Entry>()  //线形数据

    var hdlBarValue = arrayListOf<BarEntry>()  //柱形数据
    var hdlBarValueCompare = arrayListOf<BarEntry>()  //柱形数据
    private fun setHDLChartData(data: BloodLipidDataBean) {
        hdlList = data.model
        hdlListCompare = data.modelCompare
        /*  lineValue.clear()
          lineValueCompare.clear()*/
        hdlBarValue.clear()
        hdlBarValueCompare.clear()
        hdlLineValue.clear()
        hdlLineValueCompare.clear()
        if(type != 1){
            var rever: IntProgression
            if (hdlList.size < hdlListCompare.size) {
                rever = (hdlListCompare.indices).reversed()
            } else {
                rever = (hdlList.indices).reversed()
            }
            if (type == 3) {
                var compare = hdlListCompare.size - hdlList.size
                if (compare > 0) {
                    for (Int in 1..compare) {
                        hdlList.add(hdlList.size,
                            BloodLipidDataBean.ModelBean(0f,0f,0f,0f,hdlListCompare[hdlList.size].time))
                    }
                } else if (compare < 0) {
                    compare = 0 - compare
                    for (Int in 1..compare) {
                        hdlListCompare.add(
                            hdlListCompare.size,
                            BloodLipidDataBean.ModelBean(0f,0f,0f,0f,hdlList[hdlListCompare.size].time)
                        )
                    }
                }
            }
            for (i in rever) {
                //中间两端在x轴显示尺度 其他情况下不显示
                if (type == 1) {
                    var listTipG = mutableListOf<String>()
                    listTipG.add(hdlList[hdlList.size - 1 - i].time)
                    listTipG.add("0")
                    listTipG.add(hdlList[hdlList.size - 1 - i].hdl.toString())
                    listTipG.add(hdlListCompare[hdlListCompare.size - 1 - i].hdl.toString())

                    if (hdlList[hdlList.size - 1 - i].hdl == 0f) {
                        hdlList[hdlList.size - 1 - i].hdl = Float.NaN
                    } else {
                        hdlList[hdlList.size - 1 - i].hdl
                    }
                    hdlLineValue.add(
                        Entry(
                            (hdlList.size - 1 - i).toFloat(),
                            hdlList[hdlList.size - 1 - i].hdl,
                            listTipG
                        )
                    )



                    if (hdlListCompare[hdlListCompare.size - 1 - i].hdl == 0f)
                        hdlListCompare[hdlListCompare.size - 1 - i].hdl = Float.NaN
                    else
                        hdlListCompare[hdlListCompare.size - 1 - i].hdl

                    hdlLineValueCompare.add(
                        Entry(
                            (hdlListCompare.size - 1 - i).toFloat(),
                            hdlListCompare[hdlListCompare.size - 1 - i].hdl,
                            listTipG
                        )
                    )



                } else if (type == 2) {
                    var listTipW = mutableListOf<String>()
                    listTipW.add(weeker[weeker.size - i - 1])
                    listTipW.add("0")
                    listTipW.add(hdlList[hdlList.size - 1 - i].hdl.toString())
                    listTipW.add(hdlListCompare[hdlListCompare.size - 1 - i].hdl.toString())
                    hdlBarValue.add(
                        BarEntry(
                            (hdlList.size - 1 - i).toFloat(),
                            hdlList[hdlList.size - 1 - i].hdl,
                            listTipW

                        )
                    )
                    hdlBarValueCompare.add(
                        BarEntry(
                            (hdlListCompare.size - 1 - i).toFloat(),
                            hdlListCompare[hdlListCompare.size - 1 - i].hdl,
                            listTipW
                        )
                    )
                } else if (type == 3) {

                    var listTipY = mutableListOf<String>()
                    listTipY.add(hdlList[hdlList.size - 1 - i].time)
                    listTipY.add("0")
                    listTipY.add(hdlList[hdlList.size - 1 - i].hdl.toString())
                    listTipY.add(hdlListCompare[hdlListCompare.size - 1 - i].hdl.toString())
                    hdlBarValue.add(
                        BarEntry(
                            (hdlList.size - 1 - i).toFloat(),
                            hdlList[hdlList.size - 1 - i].hdl,
                            listTipY
                        )
                    )
                    hdlBarValueCompare.add(
                        BarEntry(
                            (hdlListCompare.size - 1 - i).toFloat(),
                            hdlListCompare[hdlListCompare.size - 1 - i].hdl,
                            listTipY
                        )
                    )
                } else {
                    var listTipY = mutableListOf<String>()
                    listTipY.add(hdlList[hdlList.size - 1 - i].time)
                    listTipY.add("0")
                    listTipY.add(hdlList[hdlList.size - 1 - i].hdl.toString())
                    listTipY.add(hdlListCompare[hdlListCompare.size - 1 - i].hdl.toString())
                    hdlBarValue.add(
                        BarEntry(
                            (hdlList.size - 1 - i).toFloat(),
                            hdlList[hdlList.size - 1 - i].hdl,
                            listTipY
                        )
                    )
                    hdlBarValueCompare.add(
                        BarEntry(
                            (hdlListCompare.size - 1 - i).toFloat(),
                            hdlListCompare[hdlListCompare.size - 1 - i].hdl,
                            listTipY
                        )
                    )
                }
            }
        }else{
            chartLineList.sortWith { u1, u2 ->
                //       u1.sortDate.compareTo(u2.sortDate)
                if(u1.sortDate != u2.sortDate){
                    u1.sortDate.compareTo(u2.sortDate)
                }else{
                    u1.sort.compareTo(u2.sort)

                }
            }
            for ((index, xXZhiDataManageChartBean) in chartLineList.withIndex()) {
                xXZhiDataManageChartBean.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].hdl.toString())
                listTipG.add(chartLineList[chartLineList.size - 1 - i].hdlCompare.toString())

                if (chartLineList[chartLineList.size - 1 - i].hdl == 0f) {
                    chartLineList[chartLineList.size - 1 - i].hdl = Float.NaN
                } else {
                    chartLineList[chartLineList.size - 1 - i].hdl
                }
                if (chartLineList[chartLineList.size - 1 - i].hdlCompare == 0f) {
                    chartLineList[chartLineList.size - 1 - i].hdlCompare = Float.NaN
                } else {
                    chartLineList[chartLineList.size - 1 - i].hdlCompare
                }
                hdlLineValue.add(
                    Entry(
                        (chartLineList.size - 1 - i).toFloat(),
                        chartLineList[chartLineList.size - 1 - i].hdl,
                        listTipG
                    )
                )
                hdlLineValueCompare.add(
                    Entry(
                        (chartLineList.size - 1 - i).toFloat(),
                        chartLineList[chartLineList.size - 1 - i].hdl,
                        listTipG
                    )
                )
            }
        }

        binding.lineBarChart.gmdzdbCompareLineChart.clear()
        binding.lineBarChart.gmdzdbCompareBarChart.clear()

        val min = BloodLipidGetMinMaxChart.getBloodLipidMix(data.value.minHdl,data.valueCompare.minHdl)

        val max = BloodLipidGetMinMaxChart.getBloodLipidMax(data.value.maxHdl,data.valueCompare.maxHdl)
        if(type == 1){
            initChart(min, max,binding.lineBarChart.gmdzdbCompareLineChart,hdlLineValue,hdlLineValueCompare,hdlList,3)
        }else{
            BaseChartInitUtils.initBarChartTwo(this,binding.lineBarChart.gmdzdbCompareBarChart,
                min,max,hdlBarValue,hdlBarValueCompare,
                ICompareMarkView.MarkPage.BloodFilip,"mmol/L",type,1f)
      //      initBarChart(min, max,binding.lineBarChart.gmdzdbCompareBarChart,hdlBarValue,hdlBarValueCompare)
        }
    }


    lateinit var tgList: MutableList<BloodLipidDataBean.ModelBean>
    private lateinit var tgListCompare: MutableList<BloodLipidDataBean.ModelBean>


    var tgLineValue = arrayListOf<Entry>()  //线形数据
    var tgLineValueCompare = arrayListOf<Entry>()  //线形数据

    var tgBarValue = arrayListOf<BarEntry>()  //柱形数据
    var tgBarValueCompare = arrayListOf<BarEntry>()  //柱形数据
    private fun setTGChartData(data: BloodLipidDataBean) {
        tgList = data.model
        tgListCompare = data.modelCompare
        /*  lineValue.clear()
          lineValueCompare.clear()*/
        tgLineValue.clear()
        tgLineValueCompare.clear()
        tgBarValue.clear()
        tgBarValueCompare.clear()
        if(type != 1){
            var rever: IntProgression
            if (tgList.size < tgListCompare.size) {
                rever = (tgListCompare.indices).reversed()
            } else {
                rever = (tgList.indices).reversed()
            }
            if (type == 3) {
                var compare = tgListCompare.size - tgList.size
                if (compare > 0) {
                    for (Int in 1..compare) {
                        tgList.add(tgList.size,
                            BloodLipidDataBean.ModelBean(0f,0f,0f,0f,tgListCompare[tgList.size].time))
                    }
                } else if (compare < 0) {
                    compare = 0 - compare
                    for (Int in 1..compare) {
                        tgListCompare.add(
                            tgListCompare.size,
                            BloodLipidDataBean.ModelBean(0f,0f,0f,0f,tgList[tgListCompare.size].time)
                        )
                    }
                }
            }
            for (i in rever) {
                //中间两端在x轴显示尺度 其他情况下不显示
                if (type == 1) {
                    var listTipG = mutableListOf<String>()
                    listTipG.add(tgList[tgList.size - 1 - i].time)
                    listTipG.add("0")
                    listTipG.add(tgList[tgList.size - 1 - i].tg.toString())
                    listTipG.add(tgListCompare[tgListCompare.size - 1 - i].tg.toString())

                    if (tgList[tgList.size - 1 - i].tg == 0f) {
                        tgList[tgList.size - 1 - i].tg = Float.NaN
                    } else {
                        tgList[tgList.size - 1 - i].tg
                    }
                    tgLineValue.add(
                        Entry(
                            (tgList.size - 1 - i).toFloat(),
                            tgList[tgList.size - 1 - i].tg,
                            listTipG
                        )
                    )



                    if (tgListCompare[tgListCompare.size - 1 - i].tg == 0f)
                        tgListCompare[tgListCompare.size - 1 - i].tg = Float.NaN
                    else
                        tgListCompare[tgListCompare.size - 1 - i].tg

                    tgLineValueCompare.add(
                        Entry(
                            (tgListCompare.size - 1 - i).toFloat(),
                            tgListCompare[tgListCompare.size - 1 - i].tg,
                            listTipG
                        )
                    )



                } else if (type == 2) {
                    var listTipW = mutableListOf<String>()
                    listTipW.add(weeker[weeker.size - i - 1])
                    listTipW.add("0")
                    listTipW.add(tgList[tgList.size - 1 - i].tg.toString())
                    listTipW.add(tgListCompare[tgListCompare.size - 1 - i].tg.toString())
                    tgBarValue.add(
                        BarEntry(
                            (tgList.size - 1 - i).toFloat(),
                            tgList[tgList.size - 1 - i].tg,
                            listTipW

                        )
                    )
                    tgBarValueCompare.add(
                        BarEntry(
                            (tgListCompare.size - 1 - i).toFloat(),
                            tgListCompare[tgListCompare.size - 1 - i].tg,
                            listTipW
                        )
                    )
                } else if (type == 3) {

                    var listTipY = mutableListOf<String>()
                    listTipY.add(tgList[tgList.size - 1 - i].time)
                    listTipY.add("0")
                    listTipY.add(tgList[tgList.size - 1 - i].tg.toString())
                    listTipY.add(tgListCompare[tgListCompare.size - 1 - i].tg.toString())
                    tgBarValue.add(
                        BarEntry(
                            (tgList.size - 1 - i).toFloat(),
                            tgList[tgList.size - 1 - i].tg,
                            listTipY
                        )
                    )
                    tgBarValueCompare.add(
                        BarEntry(
                            (tgListCompare.size - 1 - i).toFloat(),
                            tgListCompare[tgListCompare.size - 1 - i].tg,
                            listTipY
                        )
                    )
                } else {
                    var listTipY = mutableListOf<String>()
                    listTipY.add(tgList[tgList.size - 1 - i].time)
                    listTipY.add("0")
                    listTipY.add(tgList[tgList.size - 1 - i].tg.toString())
                    listTipY.add(tgListCompare[tgListCompare.size - 1 - i].tg.toString())
                    tgBarValue.add(
                        BarEntry(
                            (tgList.size - 1 - i).toFloat(),
                            tgList[tgList.size - 1 - i].tg,
                            listTipY
                        )
                    )
                    tgBarValueCompare.add(
                        BarEntry(
                            (tgListCompare.size - 1 - i).toFloat(),
                            tgListCompare[tgListCompare.size - 1 - i].tg,
                            listTipY
                        )
                    )
                }
            }
        }else{
            chartLineList.sortWith { u1, u2 ->
                //       u1.sortDate.compareTo(u2.sortDate)
                if(u1.sortDate != u2.sortDate){
                    u1.sortDate.compareTo(u2.sortDate)
                }else{
                    u1.sort.compareTo(u2.sort)

                }
            }
            for ((index, xXZhiDataManageChartBean) in chartLineList.withIndex()) {
                xXZhiDataManageChartBean.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].tg.toString())
                listTipG.add(chartLineList[chartLineList.size - 1 - i].tgCompare.toString())

                if (chartLineList[chartLineList.size - 1 - i].tg == 0f) {
                    chartLineList[chartLineList.size - 1 - i].tg = Float.NaN
                } else {
                    chartLineList[chartLineList.size - 1 - i].tg
                }
                if (chartLineList[chartLineList.size - 1 - i].tgCompare == 0f) {
                    chartLineList[chartLineList.size - 1 - i].tgCompare = Float.NaN
                } else {
                    chartLineList[chartLineList.size - 1 - i].tgCompare
                }
                tgLineValue.add(
                    Entry(
                        (chartLineList.size - 1 - i).toFloat(),
                        chartLineList[chartLineList.size - 1 - i].tg,
                        listTipG
                    )
                )
                tgLineValueCompare.add(
                    Entry(
                        (chartLineList.size - 1 - i).toFloat(),
                        chartLineList[chartLineList.size - 1 - i].tgCompare,
                        listTipG
                    )
                )
            }
        }

        binding.lineBarChart.gyszCompareLineChart.clear()
        binding.lineBarChart.gyszCompareBarChart.clear()

        val min = BloodLipidGetMinMaxChart.getBloodLipidMix(data.value.minTg,data.valueCompare.minTg)

        val max = BloodLipidGetMinMaxChart.getBloodLipidMax(data.value.maxTg,data.valueCompare.maxTg)
        if(type == 1){
            initChart(min, max,binding.lineBarChart.gyszCompareLineChart,tgLineValue,tgLineValueCompare,tgList,2)
        }else{
            BaseChartInitUtils.initBarChartTwo(this,binding.lineBarChart.gyszCompareBarChart,
                min,max,tgBarValue,tgBarValueCompare,
                ICompareMarkView.MarkPage.BloodFilip,"mmol/L",type,1f)
//            initBarChart(min, max,binding.lineBarChart.gyszCompareBarChart,tgBarValue,tgBarValueCompare)
        }
    }

    lateinit var tcList: MutableList<BloodLipidDataBean.ModelBean>
    private lateinit var tcListCompare: MutableList<BloodLipidDataBean.ModelBean>

    var tcLineValue = arrayListOf<Entry>()  //线形数据
    var tcLineValueCompare = arrayListOf<Entry>()  //线形数据

    var tcBarValue = arrayListOf<BarEntry>()  //柱形数据
    var tcBarValueCompare = arrayListOf<BarEntry>()  //柱形数据

    private fun setTCChartData(data: BloodLipidDataBean) {
        tcList = data.model
        tcListCompare = data.modelCompare
        tcBarValue.clear()
        tcBarValueCompare.clear()
        tcLineValue.clear()
        tcLineValueCompare.clear()
        if(type !=1){
            var rever: IntProgression
            if (tcList.size < tcListCompare.size) {
                rever = (tcListCompare.indices).reversed()
            } else {
                rever = (tcList.indices).reversed()
            }
            if (type == 3) {
                var compare = tcListCompare.size - tcList.size
                if (compare > 0) {
                    for (Int in 1..compare) {
                        tcList.add(tcList.size,
                            BloodLipidDataBean.ModelBean(0f,0f,0f,0f,tcListCompare[tcList.size].time))
                    }
                } else if (compare < 0) {
                    compare = 0 - compare
                    for (Int in 1..compare) {
                        tcListCompare.add(
                            tcListCompare.size,
                            BloodLipidDataBean.ModelBean(0f,0f,0f,0f,tcList[tcListCompare.size].time)
                        )
                    }
                }
            }
            for (i in rever) {
                //中间两端在x轴显示尺度 其他情况下不显示
                if (type == 1) {
                    var listTipG = mutableListOf<String>()
                    listTipG.add(tcList[tcList.size - 1 - i].time)
                    listTipG.add("0")
                    listTipG.add(tcList[tcList.size - 1 - i].tc.toString())
                    listTipG.add(tcListCompare[tcListCompare.size - 1 - i].tc.toString())

                    if (tcList[tcList.size - 1 - i].tc == 0f) {
                        tcList[tcList.size - 1 - i].tc = Float.NaN
                    } else {
                        tcList[tcList.size - 1 - i].tc
                    }
                    tcLineValue.add(
                        Entry(
                            (tcList.size - 1 - i).toFloat(),
                            tcList[tcList.size - 1 - i].tc,
                            listTipG
                        )
                    )



                    if (tcListCompare[tcListCompare.size - 1 - i].tc == 0f)
                        tcListCompare[tcListCompare.size - 1 - i].tc = Float.NaN
                    else
                        tcListCompare[tcListCompare.size - 1 - i].tc

                    tcLineValueCompare.add(
                        Entry(
                            (tcListCompare.size - 1 - i).toFloat(),
                            tcListCompare[tcListCompare.size - 1 - i].tc,
                            listTipG
                        )
                    )



                } else if (type == 2) {
                    var listTipW = mutableListOf<String>()
                    listTipW.add(weeker[weeker.size - i - 1])
                    listTipW.add("0")
                    listTipW.add(tcList[tcList.size - 1 - i].tc.toString())
                    listTipW.add(tcListCompare[tcListCompare.size - 1 - i].tc.toString())
                    tcBarValue.add(
                        BarEntry(
                            (tcList.size - 1 - i).toFloat(),
                            tcList[tcList.size - 1 - i].tc,
                            listTipW

                        )
                    )
                    tcBarValueCompare.add(
                        BarEntry(
                            (tcListCompare.size - 1 - i).toFloat(),
                            tcListCompare[tcListCompare.size - 1 - i].tc,
                            listTipW
                        )
                    )
                } else if (type == 3) {

                    var listTipY = mutableListOf<String>()
                    listTipY.add(tcList[tcList.size - 1 - i].time)
                    listTipY.add("0")
                    listTipY.add(tcList[tcList.size - 1 - i].tc.toString())
                    listTipY.add(tcListCompare[tcListCompare.size - 1 - i].tc.toString())
                    tcBarValue.add(
                        BarEntry(
                            (tcList.size - 1 - i).toFloat(),
                            tcList[tcList.size - 1 - i].tc,
                            listTipY
                        )
                    )
                    tcBarValueCompare.add(
                        BarEntry(
                            (tcListCompare.size - 1 - i).toFloat(),
                            tcListCompare[tcListCompare.size - 1 - i].tc,
                            listTipY
                        )
                    )
                } else {
                    var listTipY = mutableListOf<String>()
                    listTipY.add(tcList[tcList.size - 1 - i].time)
                    listTipY.add("0")
                    listTipY.add(tcList[tcList.size - 1 - i].tc.toString())
                    listTipY.add(tcListCompare[tcListCompare.size - 1 - i].tc.toString())
                    tcBarValue.add(
                        BarEntry(
                            (tcList.size - 1 - i).toFloat(),
                            tcList[tcList.size - 1 - i].tc,
                            listTipY
                        )
                    )
                    tcBarValueCompare.add(
                        BarEntry(
                            (tcListCompare.size - 1 - i).toFloat(),
                            tcListCompare[tcListCompare.size - 1 - i].tc,
                            listTipY
                        )
                    )
                }
            }
        }else{

            chartLineList.sortWith { u1, u2 ->
                if(u1.sortDate != u2.sortDate){
                    u1.sortDate.compareTo(u2.sortDate)
                }else{
                    u1.sort.compareTo(u2.sort)

                }
            }
            for ((index, xXZhiDataManageChartBean) in chartLineList.withIndex()) {
                xXZhiDataManageChartBean.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].tc.toString())
                listTipG.add(chartLineList[chartLineList.size - 1 - i].tcCompare.toString())

                if (chartLineList[chartLineList.size - 1 - i].tc == 0f) {
                    chartLineList[chartLineList.size - 1 - i].tc = Float.NaN
                } else {
                    chartLineList[chartLineList.size - 1 - i].tc
                }
                if (chartLineList[chartLineList.size - 1 - i].tcCompare == 0f) {
                    chartLineList[chartLineList.size - 1 - i].tcCompare = Float.NaN
                } else {
                    chartLineList[chartLineList.size - 1 - i].tcCompare
                }
                tcLineValue.add(
                    Entry(
                        (chartLineList.size - 1 - i).toFloat(),
                        chartLineList[chartLineList.size - 1 - i].tc,
                        listTipG
                    )
                )
                tcLineValueCompare.add(
                    Entry(
                        (chartLineList.size - 1 - i).toFloat(),
                        chartLineList[chartLineList.size - 1 - i].tcCompare,
                        listTipG
                    )
                )
            }
        }

        binding.lineBarChart.dgcCompareLineChart.clear()
        binding.lineBarChart.dgcCompareBarChart.clear()

        val min = BloodLipidGetMinMaxChart.getBloodLipidMix(data.value.minTc,data.valueCompare.minTc)

        val max = BloodLipidGetMinMaxChart.getBloodLipidMax(data.value.maxTc,data.valueCompare.maxTc)
        if(type == 1){
            initChart(min, max,binding.lineBarChart.dgcCompareLineChart,tcLineValue,tcLineValueCompare,tcList,1)
        }else{
            BaseChartInitUtils.initBarChartTwo(this,binding.lineBarChart.dgcCompareBarChart,
                min,max,tcBarValue,tcBarValueCompare,
                ICompareMarkView.MarkPage.BloodFilip,"mmol/L",type,1f)
        }
    }

    /**
     * 设置趋势图
     * @param chartType 趋势图类型（1：总胆固醇，2：甘油三酯，3：高密度蛋白，4：低密度蛋白）
     */
    private fun initLineChartList(
        chartType: Int,
        max: Float,
        min: Float,
        lineList: ArrayList<Entry>,
        lineChartList: LineChart
    ) {
        lineChartList.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(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)
                )
            )
//            x.labelCount = lineList.size
//            x.textSize = 9f

            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 {
//                    val day = (lineList[value.toInt()].data as MutableList<String>)[0]
                    "${(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, 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)

            val markerView = ICompareMarkLineView(
                this,
                com.zj365.health.R.layout.mark_view_compare_line,
                getUnit(pageType.toInt()),
                ICompareMarkLineView.MarkPage.XZhi,
                xzhiType = chartType
            )
            it.marker = markerView
            markerView.chartView = it
            it.axisRight.isEnabled = false
            it.legend.isEnabled = false

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

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

                val entries = segment.mapIndexed { index, model ->
                    val value = when (chartType) {
                        1 -> {
                            model.tc
                        }

                        2 -> {
                            model.tg
                        }

                        3 -> {
                            model.hdl
                        }

                        else -> {
                            model.ldl
                        }
                    }
                    Entry(
                        index.toFloat(),
                        value,
                        lineList[index].data
                    )
                }

                return@mapNotNull BaseChartInitUtils.setLineDataStyleOne(this,entries,it,2.5f,3.5f,false)
            }
            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>?, lineChartList: LineChart): LineDataSet {
        val set1: LineDataSet
        if (lineChartList.data != null && lineChartList.data.dataSetCount > 0) {
            set1 = lineChartList.data.getDataSetByIndex(0) as LineDataSet
            set1.values = values
            lineChartList.data.notifyDataChanged()
            lineChartList.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 { _, _ -> lineChartList.axisLeft.axisMinimum }
            set1.setValueFormatter { value, _, _, _ ->
                "$value"
            }
        }
        return set1
    }*/

    /**
     *初始化数据对比折线图
     */
    @SuppressLint("SuspiciousIndentation")
    private fun initChart(min: Float, max: Float, chart: LineChart, lineValue:ArrayList<Entry>,
                          lineValueCompare:ArrayList<Entry>,dataList: MutableList<BloodLipidDataBean.ModelBean>,chartType:Int) {
        chart.let {

            val markerView= ICompareMarkView(
                this,com.zj365.health.R.layout.mark_view_compare,
                getUnit(pageType.toInt()),
                ICompareMarkView.MarkPage.BloodFilip)
            BaseChartInitUtils.initLineChartWithCompare(this,min,max,it,lineValue,lineValueCompare,markerView)


            val barsetsNew: java.util.ArrayList<ILineDataSet> = java.util.ArrayList()

            if (!lineValue.isNullOrEmpty()){
                var segments = splitDataIntoSegmentsLineListForType(chartLineList, chartType)
                val dataSets = segments.mapNotNull { segment ->
                    if (segment.isEmpty()) return@mapNotNull null

                    val entries = segment.mapIndexed { index, model ->

                        val value = when (chartType) {
                            1 -> {
                                model.tc
                            }

                            2 -> {
                                model.tg
                            }

                            3 -> {
                                model.hdl
                            }

                            else -> {
                                model.ldl
                            }
                        }

                        Entry(
                            index.toFloat(),
                            value,
                            lineValue[index].data
                        )
                    }
                    return@mapNotNull BaseChartInitUtils.setLineDataStyleOne(this,entries,it,2.5f,3.5f,false)
                }
                var segmentsCompare = splitDataIntoSegmentsLineListForTypeCompare(chartLineList,chartType)
                val dataSetsCompare = segmentsCompare.mapNotNull { segment ->
                    if (segment.isEmpty()) return@mapNotNull null

                    val entries = segment.mapIndexed { index, model ->

                        val value = when (chartType) {
                            1 -> {
                                model.tcCompare
                            }

                            2 -> {
                                model.tgCompare
                            }

                            3 -> {
                                model.hdlCompare
                            }

                            else -> {
                                model.ldlCompare
                            }
                        }
                        Entry(
                            index.toFloat(),
                            value,
                            lineValueCompare[index].data
                        )
                    }
                    return@mapNotNull BaseChartInitUtils.setLineDataStyleTwo(this, entries,it)
                }
                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)
            }


        }

    }

    /*private fun setLineListData1(values: List<Entry>?,lineChartList: LineChart): LineDataSet {
        val set1: LineDataSet
        if (lineChartList.data != null && lineChartList.data.dataSetCount > 0) {
            set1 = lineChartList.data.getDataSetByIndex(0) as LineDataSet
            set1.values = values
            lineChartList.data.notifyDataChanged()
            lineChartList.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 { _, _ ->lineChartList.axisLeft.axisMinimum }
            set1.setValueFormatter { value, _, _, _ ->
                "$value"
            }

        }
        return set1
    }

    private fun setLineListData2(values: List<Entry>?,lineChartList: LineChart): LineDataSet {
        val set1: LineDataSet
        if (lineChartList.data != null && lineChartList.data.dataSetCount > 0) {
            set1 = lineChartList.data.getDataSetByIndex(0) as LineDataSet
            set1.values = values
            lineChartList.data.notifyDataChanged()
            lineChartList.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 { _, _ -> lineChartList.axisLeft.axisMinimum }
            set1.setValueFormatter { value, _, _, _ ->
                "$value"
            }

        }
        return set1
    }
*/
    fun splitDataIntoSegmentsLineListForType(dataList: MutableList<XZhiDataManageChartBean>,chartType: Int):MutableList<MutableList<XZhiDataManageChartBean>>{
        val segments = mutableListOf<MutableList<XZhiDataManageChartBean>>()
        var currentSegment = mutableListOf<XZhiDataManageChartBean>()
        for (model in dataList) {
            when(chartType){
                1->{
                    if (model.tc.isNaN()) {
                        // 遇到 Float.NaN，如果当前线段不为空，则添加到结果中，并开始新的线段
                        if (currentSegment.isNotEmpty()) {
                            segments.add(currentSegment)
                            currentSegment = mutableListOf()
                        }
                    } else {
                        // 遇到有效数据，将其添加到当前线段中
                        currentSegment.add(model)
                    }
                }
                2->{
                    if (model.tg.isNaN()) {
                        // 遇到 Float.NaN，如果当前线段不为空，则添加到结果中，并开始新的线段
                        if (currentSegment.isNotEmpty()) {
                            segments.add(currentSegment)
                            currentSegment = mutableListOf()
                        }
                    } else {
                        // 遇到有效数据，将其添加到当前线段中
                        currentSegment.add(model)
                    }
                }

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

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

        }

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

        return segments
    }

    fun splitDataIntoSegmentsLineListForTypeCompare(dataList: MutableList<XZhiDataManageChartBean>,chartType: Int):MutableList<MutableList<XZhiDataManageChartBean>>{
        val segments = mutableListOf<MutableList<XZhiDataManageChartBean>>()
        var currentSegment = mutableListOf<XZhiDataManageChartBean>()

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

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

                else->{
                    if (model.ldlCompare.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<XZhiRecentlyChartBean>,chartType: Int):
            MutableList<MutableList<XZhiRecentlyChartBean>> {
        val segments = mutableListOf<MutableList<XZhiRecentlyChartBean>>()
        var currentSegment = mutableListOf<XZhiRecentlyChartBean>()

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

                3->{
                    if (model.hdl.isNaN()) {
                        // 遇到 Float.NaN，如果当前线段不为空，则添加到结果中，并开始新的线段
                        if (currentSegment.isNotEmpty()) {
                            segments.add(currentSegment)
                            currentSegment = mutableListOf()
                        }
                    } else {
                        // 遇到有效数据，将其添加到当前线段中
                        currentSegment.add(model)
                    }
                }
                else ->{
                    if (model.ldl.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 initChartNoData() {
        //设置趋势图默认没数据显示(显示最近趋势数据)
        binding.lineChart.dgcLineChartList.setNoDataText("暂无数据")
        binding.lineChart.dgcLineChartList.setNoDataTextColor(
            ContextCompat.getColor(
                this,
                com.zj365.health.R.color.col_455
            )
        )
        binding.lineChart.gyszLineChartList.setNoDataText("暂无数据")
        binding.lineChart.gyszLineChartList.setNoDataTextColor(
            ContextCompat.getColor(
                this,
                com.zj365.health.R.color.col_455
            )
        )
        binding.lineChart.gmdzdbLineChartList.setNoDataText("暂无数据")
        binding.lineChart.gmdzdbLineChartList.setNoDataTextColor(
            ContextCompat.getColor(
                this,
                com.zj365.health.R.color.col_455
            )
        )
        binding.lineChart.dmdzdbLineChartList.setNoDataText("暂无数据")
        binding.lineChart.dmdzdbLineChartList.setNoDataTextColor(
            ContextCompat.getColor(
                this,
                com.zj365.health.R.color.col_455
            )
        )
        //显示比对数据趋势图表
        binding.lineBarChart.dgcCompareLineChart.setNoDataText("暂无数据")
        binding.lineBarChart.dgcCompareLineChart.setNoDataTextColor(
            ContextCompat.getColor(
                this,
                com.zj365.health.R.color.col_455
            )
        )
        binding.lineBarChart.dgcCompareBarChart.setNoDataText("暂无数据")
        binding.lineBarChart.dgcCompareBarChart.setNoDataTextColor(
            ContextCompat.getColor(
                this,
                com.zj365.health.R.color.col_455
            )
        )
        binding.lineBarChart.gyszCompareLineChart.setNoDataText("暂无数据")
        binding.lineBarChart.gyszCompareLineChart.setNoDataTextColor(
            ContextCompat.getColor(
                this,
                com.zj365.health.R.color.col_455
            )
        )
        binding.lineBarChart.gyszCompareBarChart.setNoDataText("暂无数据")
        binding.lineBarChart.gyszCompareBarChart.setNoDataTextColor(
            ContextCompat.getColor(
                this,
                com.zj365.health.R.color.col_455
            )
        )
        binding.lineBarChart.gmdzdbCompareLineChart.setNoDataText("暂无数据")
        binding.lineBarChart.gmdzdbCompareLineChart.setNoDataTextColor(
            ContextCompat.getColor(
                this,
                com.zj365.health.R.color.col_455
            )
        )
        binding.lineBarChart.gmdzdbCompareBarChart.setNoDataText("暂无数据")
        binding.lineBarChart.gmdzdbCompareBarChart.setNoDataTextColor(
            ContextCompat.getColor(
                this,
                com.zj365.health.R.color.col_455
            )
        )
        binding.lineBarChart.dmdzdbCompareLineChart.setNoDataText("暂无数据")
        binding.lineBarChart.dmdzdbCompareLineChart.setNoDataTextColor(
            ContextCompat.getColor(
                this,
                com.zj365.health.R.color.col_455
            )
        )
        binding.lineBarChart.dmdzdbCompareBarChart.setNoDataText("暂无数据")
        binding.lineBarChart.dmdzdbCompareBarChart.setNoDataTextColor(
            ContextCompat.getColor(
                this,
                com.zj365.health.R.color.col_455
            )
        )
    }

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

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

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