package com.zj365.health.act.binddevice

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.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.TimeUtils
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.data.LineDataSet
import com.github.mikephil.charting.formatter.IFillFormatter
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet
import com.xty.base.act.BaseListAct
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.event.MeasureWeightEvent
import com.xty.common.event.TZhongDataManageEvent
import com.xty.common.util.CommonToastUtils
import com.xty.common.weight.tablayout.TabEntity
import com.xty.common.weight.tablayout.listener.CustomTabEntity
import com.zj365.health.R
import com.zj365.health.act.datamanage.DataManageTypeAct
import com.zj365.health.adapter.binddevice.BindDeviceHistoryAdapter
import com.zj365.health.adapter.binddevice.BodyFatBindDeviceHistoryAdapter
import com.zj365.health.databinding.ActDeviceChatBinding
import com.zj365.health.vm.DevicesChatVm
import com.zj365.health.weight.CustomXAxisRenderer
import com.zj365.health.weight.ICompareMarkLineView
import com.xty.network.model.BindDevHistoryBean
import com.xty.network.model.BodyFatHistoryBean
import com.xty.network.model.DataManageChartBean
import com.xty.network.model.DataManageTendencyBean
import com.xty.network.model.RecentlyHealthBean
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
import kotlin.math.max
import kotlin.math.min

@Route(path = ARouterUrl.BODY_FAT_BIND_CHAT)
class DevicesChatAct : BaseListAct<DevicesChatVm>() {

    val binding by lazy { ActDeviceChatBinding.inflate(layoutInflater) }
    var id: String = ""

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

            2 -> {
                showName = "mmol/L"
            }

            3 -> {
                showName = "kg"
            }
        }
        return showName
    }

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

    private var lineList = arrayListOf<Entry>()  //体重曲线数据
    private var bmiLineList = arrayListOf<Entry>()  //BMI曲线数据
    private var bodyFatList = arrayListOf<Entry>()  //体脂曲线数据


    var lineValue = arrayListOf<Entry>()  //曲线数据
    var barValue = arrayListOf<BarEntry>()  //柱形数据

    private lateinit var lineListData: MutableList<RecentlyHealthBean.ChartList>
    private var pbfLine: MutableList<RecentlyHealthBean.ChartList> = mutableListOf()

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


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

    var type = 1
    private var pageType = ""

    var dayDate = ""
    var weekDate = ""
    var mouthDate = ""
    var yearDate = ""
    private var titleStr = ""
    private var heightStr = ""

    //列表
    val mAdapter by lazy { BodyFatBindDeviceHistoryAdapter() }
    var mBloodSugarAdapter: BindDeviceHistoryAdapter? = null


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

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

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

        binding.mBodyFatLineChartList.setNoDataText(getString(R.string.line_chart_not_data))
        binding.mBodyFatLineChartList.setNoDataTextColor(
            ContextCompat.getColor(
                this,
                R.color.col_455
            )
        )
        mTabEntities.clear()
        mTitles.forEach {
            mTabEntities.add(
                TabEntity(
                    it,
                    android.R.drawable.ic_delete,
                    android.R.drawable.ic_delete
                )
            )
        }

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

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

        if (pageType == "2") {
            binding.lineName.text = "血糖数据趋势"
            binding.llBmiLayout.visibility = View.GONE
            binding.llPbfLayout.visibility = View.GONE
        }
    }


    override fun initAdapter() {
        binding.mRecycle.layoutManager = LinearLayoutManager(this)
        setRecycleRefresh(binding.mRecycle, binding.mRefresh, false)
        if (pageType == "3") {
            binding.mRecycle.adapter = mAdapter
            mAdapter.setOnItemClickListener { adapter, view, position ->
                val bodyData = adapter.data[position] as BodyFatHistoryBean
                bundle.clear()
                bundle.putSerializable("bodyData", bodyData)
                RouteManager.goAct(ARouterUrl.BODY_FAT_DETAIL, bundle)
            }
        } else {
            mBloodSugarAdapter = BindDeviceHistoryAdapter()
            binding.mRecycle.adapter = mBloodSugarAdapter
        }
    }

    @SuppressLint("SimpleDateFormat")
    override fun loadData() {
        //获取最近趋势图数据
        mViewModel.getChatData(
            id,
            pageType
        )

        if (pageType == "3") {
            mViewModel.getBodyFatHistory(id, null, null, page)
        } else {
            mViewModel.getDeviceHistory(
                id,
                BaseDeviceBindListAct.DeviceType.XUETANG.type,
                null,
                page
            )
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun tizhongHealthUpdate(event: TZhongDataManageEvent) {
        if (!TextUtils.isEmpty(event.height)) {
            heightStr = event.height
        }
        loadData()
    }

    @SuppressLint("SetTextI18n")
    override fun liveObserver() {

        mViewModel.bindOk.observe(this) {
            mBloodSugarAdapter?.let { adapter ->
                if (it.data.records.size > 2) {
                    val twoData = mutableListOf<BindDevHistoryBean>()
                    twoData.add(it.data.records[0])
                    twoData.add(it.data.records[1])
                    setDate(adapter, twoData)
                } else {
                    setDate(adapter, it.data.records)
                }
            }
        }

        mViewModel.bodyFatData.observe(this) {
            val twoData = mutableListOf<BodyFatHistoryBean>()
            if (it.data.records.size > 2) {
                twoData.add(it.data.records[0])
                twoData.add(it.data.records[1])
                setDate(mAdapter, twoData)
            } else {
                setDate(mAdapter, 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")
                    val dateMonth = SimpleDateFormat("MM-dd")
                    for (chartList in data.list) {
                        val time = chartList.time
                        chartList.date = dateTime.format(Date(time.toLong() * 1000))
                        chartList.time = dateMonth.format(Date(time.toLong() * 1000))
                    }
                    setRecentyHealthData(it.data)
                }
            }
        }
    }

    private fun setRecentyHealthData(data: RecentlyHealthBean) {
        lineListData = data.list
        lineList.clear()
        bmiLineList.clear()
        bodyFatList.clear()
        pbfLine.clear()

        for ((i, chartList) in lineListData.withIndex()) {
            val listTipG = mutableListOf<String>()
            listTipG.add(chartList.time)
            listTipG.add(chartList.date)
            listTipG.add(chartList.dataValue.toString())
            listTipG.add(chartList.bmi.toString())
            listTipG.add(chartList.pbf.toString())

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

            bmiLineList.add(
                Entry(
                    i.toFloat(),
                    chartList.bmi,
                    listTipG
                )
            )

            if (chartList.pbf != 0f) {
                pbfLine.add(chartList)
                bodyFatList.add(
                    Entry(
                        i.toFloat(),
                        chartList.pbf,
                        listTipG
                    )
                )
            }
        }

        binding.mLineChartList.clear()
        binding.mBMILineChartList.clear()
        binding.mBodyFatLineChartList.clear()

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

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

        /**
         * pbf趋势图
         */
        val pbfMax = if (data.maxPbf >= 0) data.maxPbf + 10 else data.maxPbf
        val pbfMin = if (data.minPbf - 10 < 0) 0f else data.minPbf - 5
        initLineChartList(
            binding.mBodyFatLineChartList,
            pbfMax,
            pbfMin,
            2
        )
    }

    //设置趋势图
    private fun initLineChartList(
        mLineChart: LineChart,
        max: Float,
        min: Float,
        type: Int
    ) {
        mLineChart.let {
            it.clear()
            it.setNoDataText(getString(R.string.line_chart_not_data))
            it.setNoDataTextColor(ContextCompat.getColor(this, R.color.col_455))
            it.setLayerType(View.LAYER_TYPE_SOFTWARE, null)

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

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

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

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

            it.isDragEnabled = true
            val m = Matrix()
            if (lineListData.size > 10) {
                m.postScale(2.8f, 1f)
            } else {
                m.postScale(0.5f, 1f)
            }
            it.viewPortHandler.refresh(m, it, false)
            it.isScaleXEnabled = true                 //支持x轴缩放
            it.isScaleYEnabled = false

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

            val x = it.xAxis
            x.granularity = 1f  //精准设置

//            x.textSize = 9f
            x.textColor = ContextCompat.getColor(this, R.color.col_92a)
            x.isEnabled = true
            x.setDrawGridLines(false)  //不绘制y
            x.setDrawAxisLine(false)
            x.position = XAxis.XAxisPosition.BOTTOM
            x.setAvoidFirstLastClipping(false)
            x.setValueFormatter { value, _ ->
                val index = value.toInt()
                //Log.e("x轴", "$value")

                when (type) {
                    0 -> {
                        if (index < 0 || index >= lineList.size) {
                            ""
                        } else {
                            "${(lineList[value.toInt()].data as MutableList<String>)[0]}\n${(lineList[value.toInt()].data as MutableList<String>)[1]}"
                        }
                    }

                    1 -> if (index < 0 || index >= bmiLineList.size) {
                        ""
                    } else {
                        "${(bmiLineList[value.toInt()].data as MutableList<String>)[0]}\n${(bmiLineList[value.toInt()].data as MutableList<String>)[1]}"
                    }

                    2 -> if (index < 0 || index >= bodyFatList.size) {
                        ""
                    } else {
                        "${(bodyFatList[value.toInt()].data as MutableList<String>)[0]}\n${(bodyFatList[value.toInt()].data as MutableList<String>)[1]}"
                    }

                    else -> {
                        ""
                    }
                }

            }
            //y轴
            val y = it.axisLeft
            y.setLabelCountAndMaxMinValue(6, false, min, max)
            y.textColor = ContextCompat.getColor(this, R.color.col_92a)
            y.setDrawAxisLine(false)
            y.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
            y.gridColor = ContextCompat.getColor(this, R.color.col_92a)
            y.setGridDashedLine(DashPathEffect(floatArrayOf(5f, 5f), 0f))
            y.setDrawGridLines(true)  //绘制横者的x轴
            y.setDrawZeroLine(true)


            val markerView = when (type) {
                0 -> {
                    val markType = if (pageType == "2") {
                        ICompareMarkLineView.MarkPage.TShu
                    } else {
                        ICompareMarkLineView.MarkPage.WEIGHT
                    }
                    ICompareMarkLineView(
                        this,
                        R.layout.mark_view_compare_line,
                        getUnit(pageType.toInt()),
                        markType
                    )
                }

                1 -> ICompareMarkLineView(
                    this,
                    R.layout.mark_view_compare_line,
                    "",
                    ICompareMarkLineView.MarkPage.Bmi
                )

                2 -> ICompareMarkLineView(
                    this,
                    R.layout.mark_view_compare_line,
                    "%",
                    ICompareMarkLineView.MarkPage.PBF
                )

                else -> ICompareMarkLineView(
                    this,
                    R.layout.mark_view_compare_line,
                    getUnit(pageType.toInt()),
                    ICompareMarkLineView.MarkPage.TShu
                )
            }

            it.marker = markerView
            markerView.chartView = it
            it.axisRight.isEnabled = false
            it.legend.isEnabled = false

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

                            }
                            return@mapNotNull setLineListData(entries, mLineChart)
                        }
                        barsetsNew.addAll(dataSets)
                    }
                }
                val lineData = LineData(barsetsNew)
                lineData.setValueTextSize(9f)
                lineData.setDrawValues(false)
                it.data = lineData

                when (type) {
                    0 -> {
                        it.moveViewToX(lineList[lineList.size - 1].x)
                    }

                    1 -> {
                        it.moveViewToX(bmiLineList[bmiLineList.size - 1].x)
                    }

                    else -> {
                        if (bodyFatList.isNotEmpty()) {
                            it.moveViewToX(bodyFatList[bodyFatList.size - 1].x)
                        }
                    }
                }
            }
        }
    }

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

        }
        return set1
    }

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

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

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

        return segments
    }

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

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

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

        return segments
    }

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

        return segmentsCompare
    }

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

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

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

    private fun setChartData(count: Int, mChart: BarChart) {
        val m = Matrix()
        m.postScale(scaleNum(count), 1f) //两个参数分别是x,y轴的缩放比例。例如：将x轴的数据放大为之前的1.5倍
        mChart.viewPortHandler.refresh(m, mChart, false) //将图表动画显示之前进行缩放
    }

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

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

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

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

    override fun setLayout() = binding.root

    @SuppressLint("SimpleDateFormat")
    private fun buildWeekLower26(shouldEnd: Date?): MutableList<String> {
        val startDate = Calendar.getInstance()
        startDate.firstDayOfWeek = Calendar.MONDAY
        startDate.add(Calendar.YEAR, -1)
        val endDate = Calendar.getInstance()
        if (shouldEnd != null) {
            endDate.time = shouldEnd
        }
        val dateRanges: MutableList<String> = ArrayList()
        val currentMonday = startDate.clone() as Calendar
        currentMonday.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY)

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

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

            currentMonday.add(Calendar.WEEK_OF_YEAR, 1)
        }

        dateRanges.reverse()
        return dateRanges
    }

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

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

        val currentDate = calendar.time

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

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

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

        return startDate + "至$endDate"
    }

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

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

        return dateFormat.format(calendar.time)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun reveiveMsg(event: MeasureWeightEvent) {
        CommonToastUtils.showSucceedToast("测量成功")
        loadData()
    }
}