package com.zj365.health.fragment

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.DashPathEffect
import android.graphics.Matrix
import android.os.Build
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.bigkoo.pickerview.adapter.ArrayWheelAdapter
import com.blankj.utilcode.util.TimeUtils
import com.contrarywind.view.WheelView
import com.github.mikephil.charting.charts.BarChart
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.BarData
import com.github.mikephil.charting.data.BarDataSet
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.xty.base.fragment.BaseVmFrag
import com.xty.common.TimeSelectCompare
import com.xty.common.weight.tablayout.TabEntity
import com.xty.common.weight.tablayout.listener.CustomTabEntity
import com.xty.common.weight.tablayout.listener.OnTabSelectListener
import com.zj365.health.R
import com.zj365.health.adapter.CompareAdapter
import com.zj365.health.databinding.FragUricAcidCompareDataBinding
import com.zj365.health.vm.UricAcidCompareVm
import com.zj365.health.weight.ICompareMarkView
import com.xty.network.model.ModelCompare
import com.xty.network.model.ValueMap
import com.xty.network.model.UricAcidBean
import com.xty.network.model.Value
import com.xty.network.model.fillMissingData
import com.xty.network.model.mapDataToTime
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
import kotlin.math.max
import kotlin.math.min


/**
 *  尿酸数据对比
 */
@Suppress("NAME_SHADOWING")
class UricAcidCompareDataFrag : BaseVmFrag<UricAcidCompareVm>() {

    private var week: Int = 1//默认点击时间是选择时间还是对比时间 1，选择， 2 对比
    val binding by lazy { FragUricAcidCompareDataBinding.inflate(layoutInflater) }
    val adapter by lazy { CompareAdapter() }

    val fomartStr by lazy { arrayOf("HH:mm", "HH:mm", "MM-dd", "MM-dd", "yy-MM") }
    val contentStr by lazy {
        arrayOf(
            "日期",
            "正常次数",
            "高尿酸"
        )
    }

    private val otherContentStr by lazy {
        arrayOf(
            "日期",
            "累计次数",
            "平均尿酸",
            "最高尿酸",
            "最低尿酸",
            "正常次数",
            "高尿酸"
        )
    }
    val weeker by lazy { arrayOf("周一", "周二", "周三", "周四", "周五", "周六", "周日") }

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

    var barValue = arrayListOf<BarEntry>()  //柱形数据
    var barValueCompare = arrayListOf<BarEntry>()  //柱形数据
    var id: String = ""
    var type = 1

    var dayDate = ""
    var weekDate = ""
    var mouthDate = ""
    var yearDate = ""
    private var timeSelect: TimeSelectCompare? = null
    private var timeSelectCompare: TimeSelectCompare? = null

    private var timeMonthSelect: TimeSelectCompare? = null

    private var timeMonthSelectCompare: TimeSelectCompare? = null

    var timeYearSelect: TimeSelectCompare? = null

    var timeYearSelectCompare: TimeSelectCompare? = null

    private var bottomSheetDialog: BottomSheetDialog? = null
    private var weekWheelView: WheelView? = null

    @SuppressLint("SuspiciousIndentation")
    fun initBottomDialog() {
        if (bottomSheetDialog == null) {
            bottomSheetDialog = BottomSheetDialog(this.requireContext())
            bottomSheetDialog?.let { dialog ->
                val view = LayoutInflater.from(context).inflate(R.layout.bottom_sheet_layout, null)
                dialog.setContentView(view)
                weekWheelView = view.findViewById<WheelView>(R.id.wheelView)
                weekWheelView?.setCyclic(false)
                val list = buildWeekLower26(null)
                list.removeAt(0)
                weekWheelView?.adapter = ArrayWheelAdapter(list)
                val windowHeight = (resources.displayMetrics.heightPixels * 0.6).toInt()
                dialog.behavior.peekHeight = windowHeight

                dialog.behavior.isHideable = false
                dialog.behavior.state = BottomSheetBehavior.STATE_EXPANDED

                val cancelButton = view.findViewById<TextView>(R.id.cancel_button)
                val confirmButton = view.findViewById<TextView>(R.id.confirm_button)

                cancelButton.setOnClickListener {
                    // 点击取消按钮的操作
                    dialog.dismiss()
                }

                confirmButton.setOnClickListener {
                    if (weekWheelView == null) {
                        return@setOnClickListener
                    }
                    // 点击确定按钮的操作
                    val item = weekWheelView!!.adapter.getItem(weekWheelView!!.currentItem)
                    if (week == 1) {
                        binding.tvShowDate.text = item.toString()
                        weekDate = binding.tvShowDate.text.toString()
                        mViewModel.getUricAcidData(
                            type,
                            binding.tvShowDate.text.toString(),
                            binding.tvHideDate.text.toString(), id
                        )
                    } else {
                        binding.tvHideDate.text = item.toString()
                        mViewModel.getUricAcidData(
                            type,
                            binding.tvShowDate.text.toString(),
                            binding.tvHideDate.text.toString(), id
                        )
                    }
                    // 点击确定按钮的操作
                    dialog.dismiss()
                }
            }
        }
    }

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

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

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

            currentMonday.add(Calendar.WEEK_OF_YEAR, 1)
        }

        dateRanges.reverse()
        return dateRanges
    }

    override fun setLayout() = binding.root
    override fun initData() {
        super.initData()
        id = arguments?.getString("id").toString()
    }

    @SuppressLint("SimpleDateFormat")
    override fun initView() {
        super.initView()
        initTab()
//        binding.mLineChart.setNoDataText(getString(R.string.line_chart_not_data))
//        binding.mLineChart.setNoDataTextColor(
//            ContextCompat.getColor(
//                requireContext(),
//                R.color.col_455
//            )
//        )
        binding.mBarChart.setNoDataText(getString(R.string.line_chart_not_data))
        binding.mBarChart.setNoDataTextColor(
            ContextCompat.getColor(
                requireContext(),
                R.color.col_455
            )
        )
        initRecycle()
        setTimeSelect()
        binding.tvShowDate.setOnClickListener {
            when (type) {
                1 -> {
                    timeSelect!!.selectTime(it, "yyyy-MM-dd")
                }

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

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

                4 -> {
                    timeYearSelect?.selectTimeWithYear(it, "yyyy")
                }
            }
        }
//        timeSelect!!.setHide().setOnDismissListener{
//            binding.nestedScrollView.scrollTo(0,0)
//        }
//        timeSelectCompare!!.setHide().setOnDismissListener{
//            binding.nestedScrollView.scrollTo(0,0)
//
//        }
//        timeMonthSelect.setHide().setOnDismissListener{
//            binding.nestedScrollView.scrollTo(0,0)
//        }
//        timeMonthSelectCompare.setHide().setOnDismissListener{
//            binding.nestedScrollView.scrollTo(0,0)
//        }
//        timeYearSelect.setHide().setOnDismissListener{
//            binding.nestedScrollView.scrollTo(0,0)
//        }
//        timeYearSelectCompare.setHide().setOnDismissListener{
//            binding.nestedScrollView.scrollTo(0,0)
//        }
        binding.tvHideDate.setOnClickListener {
            when (type) {
                1 -> {
                    var calendar = Calendar.getInstance()
                    if (!TextUtils.isEmpty(timeSelect!!.selectTime)) {
                        val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
                        val date = dateFormat.parse(timeSelect!!.selectTime)
                        if (date != null) {
                            calendar.time = date
                        }
                        calendar.add(Calendar.DAY_OF_YEAR, -1)

                    } else {
                        val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
                        val date = dateFormat.parse(binding.tvHideDate.text.toString())
                        if (date != null) {
                            calendar.time = date
                        }
                    }
                    timeSelectCompare!!.createPvTime(requireContext(), calendar, 1) {
                        // 在选择时间后执行的逻辑
                        type = 1
//            dayDate = binding.tvHideDate.text.toString()
                        mViewModel.getUricAcidData(
                            type,
                            binding.tvShowDate.text.toString(),
                            binding.tvHideDate.text.toString(), id
                        )
                    }
                    timeSelectCompare!!.selectTime(it, "yyyy-MM-dd")
                }

                2 -> {
                    val selectedDateStr = binding.tvShowDate.text
                    if (selectedDateStr != null) {
                        val selectedDateSpit = selectedDateStr.split("至")
                        selectedDateSpit.let { split ->
                            if (split.size >= 2) {
                                val selectedStartStr = split[0]
                                val list = buildWeekLower26(
                                    SimpleDateFormat("yyyy-MM-dd").parse(selectedStartStr)
                                )
                                weekWheelView?.adapter = ArrayWheelAdapter(list)
                            }
                        }
                    }
                    bottomSheetDialog?.show()
                    week = 2
                }

                3 -> {
                    var calendar = Calendar.getInstance()

                    timeMonthSelect!!.selectTime
                    if (!TextUtils.isEmpty(timeMonthSelect!!.selectTime)) {
                        val dateFormat = SimpleDateFormat("yyyy-MM", Locale.getDefault())
                        val date = dateFormat.parse(timeMonthSelect!!.selectTime)
                        if (date != null) {
                            calendar.time = date
                        }
                        if (calendar!!.get(Calendar.MONTH) == Calendar.JANUARY) {
                            calendar.add(Calendar.YEAR, -1)
                            calendar.set(Calendar.MONTH, Calendar.DECEMBER)
                        } else {
                            calendar.add(Calendar.MONTH, -1)
                        }
                    } else {
                        val dateFormat = SimpleDateFormat("yyyy-MM", Locale.getDefault())
                        val date = dateFormat.parse(binding.tvHideDate.text.toString())
                        if (date != null) {
                            calendar.time = date
                        }
                    }


                    timeMonthSelectCompare!!.createPvTime(requireContext(), calendar, 3) {
                        // 在选择时间后执行的逻辑
                        type = 3
//                        mouthDate = binding.tvHideDate.text.toString()
                        mViewModel.getUricAcidData(
                            type,
                            binding.tvShowDate.text.toString(),
                            binding.tvHideDate.text.toString(), id
                        )
                    }

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

                    // 如果当前月份是一月，将年份减一，并将月份设置为十二月
                }

                4 -> {
                    var calendar = Calendar.getInstance()

                    if (!TextUtils.isEmpty(timeYearSelect!!.selectTime)) {
                        val dateFormat = SimpleDateFormat("yyyy", Locale.getDefault())
                        val date = dateFormat.parse(timeYearSelect!!.selectTime)
                        if (date != null) {
                            calendar.time = date
                        }
                        calendar.add(Calendar.YEAR, -1)
                    } else {
                        val dateFormat = SimpleDateFormat("yyyy", Locale.getDefault())
                        val date = dateFormat.parse(binding.tvHideDate.text.toString())
                        if (date != null) {
                            calendar.time = date
                        }
                    }
                    timeYearSelectCompare!!.createPvTime(requireContext(), calendar, 4) {
                        // 在选择时间后执行的逻辑
                        type = 4
//                        mouthDate = binding.tvHideDate.text.toString()
                        mViewModel.getUricAcidData(
                            type,
                            binding.tvShowDate.text.toString(),
                            binding.tvHideDate.text.toString(), id
                        )
                    }
                    timeYearSelectCompare!!.selectTimeWithYear(it, "yyyy")
                }
            }
        }
        initBottomDialog()
        mViewModel.getUricAcidData(
            type,
            /* RxTimeTool.getCurTimeString(SimpleDateFormat("yyyy-MM-dd"))*/
            SimpleDateFormat("yyyy-MM-dd").format(getdateMunise(-1)),
            SimpleDateFormat("yyyy-MM-dd").format(getdateMunise(-2)), id
        )//TODO
    }

    /**
     * 初始化时间选择器
     */
    @SuppressLint("SimpleDateFormat")
    private fun setTimeSelect() {

        var calendar = Calendar.getInstance()
        calendar.time = getdateMunise(-1)
        binding.tvShowDate.text = SimpleDateFormat("yyyy-MM-dd").format(calendar.time)
        binding.tvHideDate.text = SimpleDateFormat("yyyy-MM-dd").format(getdateMunise(-2))
        //日 的选择时间器
        timeSelect = TimeSelectCompare()
        timeSelect!!.createPvTime(requireContext(), calendar, 1) {
            // 在选择时间后执行的逻辑
            type = 1
            dayDate = binding.tvShowDate.text.toString()
            mViewModel.getUricAcidData(
                type,
                dayDate,
                binding.tvHideDate.text.toString(), id
            )
        }
        timeSelect!!.startDate.set(1922, 1, 1)
        timeSelect!!.endDate = calendar
        //日 的对比时间器
        timeSelectCompare = TimeSelectCompare()

//-------------------------------------------------月
        calendar = Calendar.getInstance()
        val dateFormat = SimpleDateFormat("yyyy-MM", Locale.getDefault())
        dateFormat.format(calendar.time)
        if (calendar.get(Calendar.MONTH) == Calendar.JANUARY) {
            calendar.add(Calendar.YEAR, -1)
            calendar.set(Calendar.MONTH, Calendar.DECEMBER)
        } else {
            calendar.add(Calendar.MONTH, -1)
        }
        timeMonthSelect = TimeSelectCompare()
        timeMonthSelect!!.createPvTime(requireContext(), calendar, 3) {
            // 在选择时间后执行的逻辑
            type = 3
            mouthDate = binding.tvHideDate.text.toString()
            mViewModel.getUricAcidData(
                type,
                binding.tvShowDate.text.toString(),
                binding.tvHideDate.text.toString(), id
            )
            timeMonthSelect?.selectTimeWithYearMonth(binding.tvShowDate, "yyyy-MM")
        }
        timeMonthSelect!!.startDate.set(Calendar.YEAR, 1922)
        timeMonthSelect!!.startDate.set(Calendar.MONTH, 1)
        timeMonthSelect!!.endDate = calendar


        calendar.add(Calendar.MONTH, -1)
        //月 的对比时间器
        timeMonthSelectCompare = TimeSelectCompare()
        timeMonthSelectCompare!!.startDate.set(Calendar.YEAR, 1922)
        timeMonthSelectCompare!!.startDate.set(Calendar.MONTH, 1)
        timeMonthSelectCompare!!.endDate = calendar
//-------------------------------------------------年
        val calendaryear = Calendar.getInstance()
        val lastYear = SimpleDateFormat("yyyy", Locale.getDefault()).format(calendaryear.time)
        val date = lastYear.format(calendaryear.time)
        timeYearSelect = TimeSelectCompare()
        timeYearSelect!!.createPvTime(requireContext(), calendaryear, 4) {
            // 在选择时间后执行的逻辑
            type = 4
            mouthDate = binding.tvHideDate.text.toString()
            mViewModel.getUricAcidData(
                type,
                binding.tvShowDate.text.toString(),
                binding.tvHideDate.text.toString(), id
            )
            timeYearSelect?.selectTimeWithYearMonth(binding.tvShowDate, "yyyy")
        }

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

    }

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

    override fun setViewModel() = UricAcidCompareVm()

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

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

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

        return index
    }


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

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

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

        return segments
    }

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

        return segmentsCompare
    }

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

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

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

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

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

    private fun initTab() {

        val currentDay = Date()
        dayDate = TimeUtils.date2String(currentDay, "yyyy-MM-dd")
//        weekDate = "${TimeUtils.date2String(getDateAdd(6), "yyyy-MM-dd")}至$dayDate"
        mouthDate = TimeUtils.date2String(currentDay, "yyyy-MM")
        yearDate = TimeUtils.date2String(currentDay, "yyyy")
        mTabEntities.clear()
        mTitles.forEach {
            mTabEntities.add(
                TabEntity(
                    it, android.R.drawable.ic_delete, android.R.drawable.ic_delete
                )
            )
        }
        binding.commonTabLayout.setTabData(mTabEntities)
        binding.commonTabLayout.setOnTabSelectListener(object : OnTabSelectListener {
            @SuppressLint("SetTextI18n")
            override fun onTabSelect(position: Int) {
                binding.commonTabLayout.currentTab = position

                when (position) {
                    0 -> {
                        type = 1
                        binding.showTitle.text = "选择日期"
                        binding.hideTitle.text = "对比日期"
                        binding.tvShowDate.text =
                            SimpleDateFormat("yyyy-MM-dd").format(getdateMunise(-1))
                        binding.tvHideDate.text =
                            SimpleDateFormat("yyyy-MM-dd").format(getdateMunise(-2))
                        mViewModel.getUricAcidData(
                            type,
                            /* RxTimeTool.getCurTimeString(SimpleDateFormat("yyyy-MM-dd"))*/
                            binding.tvShowDate.text.toString(),
                            binding.tvHideDate.text.toString(), id
                        )
//                        binding.mLineChart.visibility = View.VISIBLE
//                        binding.mBarChart.visibility = View.GONE

                    }

                    1 -> {
                        type = 2
                        binding.showTitle.text = "选择周"
                        binding.hideTitle.text = "对比周"
                        binding.tvShowDate.text = getPreviousWeekDateRange(1)
                        binding.tvHideDate.text = getPreviousWeekDateRange(2)
                        mViewModel.getUricAcidData(
                            type,
                            /* RxTimeTool.getCurTimeString(SimpleDateFormat("yyyy-MM-dd"))*/
                            binding.tvShowDate.text.toString(),
                            binding.tvHideDate.text.toString(), id
                        )
//                        binding.mLineChart.visibility = View.GONE
//                        binding.mBarChart.visibility = View.VISIBLE
                    }

                    2 -> {
                        binding.showTitle.text = "选择月"
                        binding.hideTitle.text = "对比月"
                        binding.tvShowDate.text = getPreviousMonthDateRange(1)
                        binding.tvHideDate.text = getPreviousMonthDateRange(2)
                        type = 3
                        mViewModel.getUricAcidData(
                            type,
                            /* RxTimeTool.getCurTimeString(SimpleDateFormat("yyyy-MM-dd"))*/
                            binding.tvShowDate.text.toString(),
                            binding.tvHideDate.text.toString(), id
                        )
//                        binding.mLineChart.visibility = View.GONE
//                        binding.mBarChart.visibility = View.VISIBLE

                    }

                    3 -> {
                        val calendar = Calendar.getInstance()
                        calendar.add(Calendar.YEAR, -1)
                        val lastYear =
                            SimpleDateFormat("yyyy", Locale.getDefault()).format(calendar.time)
                        binding.tvShowDate.text = yearDate
                        binding.tvHideDate.text = lastYear
                        type = 4
                        mViewModel.getUricAcidData(
                            type,
                            /* RxTimeTool.getCurTimeString(SimpleDateFormat("yyyy-MM-dd"))*/
                            binding.tvShowDate.text.toString(),
                            binding.tvHideDate.text.toString(), id
                        )
//                        binding.mLineChart.visibility = View.GONE
//                        binding.mBarChart.visibility = View.VISIBLE
                    }
                }
//                mViewModel.getUricAcidData(type, binding.tvShowDate.text.toString(), id)TODO
            }

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

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

        val dateFormat = SimpleDateFormat("yyyy-MM", Locale.getDefault())
        val previousMonth = dateFormat.format(calendar.time)

        return previousMonth
    }

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

        val currentDate = calendar.time

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

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

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

        return startDate + "至$endDate"
    }

    lateinit var list: MutableList<ModelCompare>
    private lateinit var listCompare: MutableList<ModelCompare>
    private fun setChartdata(data: UricAcidBean) {
        setAvgInfo(data)
        list = data.model
        listCompare = data.modelCompare
        lineValue.clear()
        lineValueCompare.clear()
        barValue.clear()
        barValueCompare.clear()
        var rever: IntProgression
        if (list.size < listCompare.size) {
            rever = (listCompare.indices).reversed()
        } else {
            rever = (list.indices).reversed()
        }
        if (type == 3) {
            var compare = listCompare.size - list.size
            if (compare > 0) {
                for (Int in 1..compare) {
                    list.add(list.size,ModelCompare(listCompare[list.size].time, 0f))
                }
            } else if (compare < 0) {
                compare = 0 - compare
                for (Int in 1..compare) {
                    listCompare.add(
                        listCompare.size,
                       ModelCompare(list[listCompare.size].time, 0f)
                    )
                }
            }
        }
        for (i in rever) {
            //中间两端在x轴显示尺度 其他情况下不显示
            if (type == 1) {
                var listTipG = mutableListOf<String>()
                listTipG.add(list[list.size - 1 - i].time)
                listTipG.add("0")
                listTipG.add(list[list.size - 1 - i].uaValue.toString())
                listTipG.add(listCompare[listCompare.size - 1 - i].uaValue.toString())

                if (list[list.size - 1 - i].uaValue == 0f) {
                    list[list.size - 1 - i].uaValue = Float.NaN
                } else {
                    list[list.size - 1 - i].uaValue
                }
                barValue.add(
                    BarEntry(
                        (list.size - 1 - i).toFloat(),
                        list[list.size - 1 - i].uaValue,
                        listTipG
                    )
                )

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

                barValueCompare.add(
                    BarEntry(
                        (listCompare.size - 1 - i).toFloat(),
                        listCompare[listCompare.size - 1 - i].uaValue,
                        listTipG
                    )
                )

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

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

                var listTipY = mutableListOf<String>()
                listTipY.add(list[list.size - 1 - i].time)
                listTipY.add("0")
                listTipY.add(list[list.size - 1 - i].uaValue.toString())
                listTipY.add(listCompare[listCompare.size - 1 - i].uaValue.toString())
                barValue.add(
                    BarEntry(
                        (list.size - 1 - i).toFloat(),
                        list[list.size - 1 - i].uaValue,
                        listTipY
                    )
                )
                barValueCompare.add(
                    BarEntry(
                        (listCompare.size - 1 - i).toFloat(),
                        listCompare[listCompare.size - 1 - i].uaValue,
                        listTipY
                    )
                )
            } else {
                var listTipY = mutableListOf<String>()
                listTipY.add(list[list.size - 1 - i].time)
                listTipY.add("0")
                listTipY.add(list[list.size - 1 - i].uaValue.toString())
                listTipY.add(listCompare[listCompare.size - 1 - i].uaValue.toString())
                barValue.add(
                    BarEntry(
                        (list.size - 1 - i).toFloat(),
                        list[list.size - 1 - i].uaValue,
                        listTipY
                    )
                )
                barValueCompare.add(
                    BarEntry(
                        (listCompare.size - 1 - i).toFloat(),
                        listCompare[listCompare.size - 1 - i].uaValue,
                        listTipY
                    )
                )
            }
        }
//        binding.mLineChart.clear()
        binding.mBarChart.clear()

       val min = if (data.value.minData.toFloat() == 0f && data.value.compareMinData.toFloat() != 0f) {
           if(data.value.compareMinData.toFloat()-20<0){
               0f
           }else{
               data.value.compareMinData.toFloat()-20
           }
        } else if (data.value.compareMinData.toFloat() == 0f && data.value.minData.toFloat() != 0f) {
           if( data.value.minData.toFloat()-20<0){
               0f
           }else{
               data.value.minData.toFloat()-20
           }
        } else {
           if(  min(data.value.minData.toFloat(), data.value.compareMinData.toFloat())-20<0){
               0f
           }else{
               min(data.value.minData.toFloat(), data.value.compareMinData.toFloat())-20
           }
        }

      val max = if (data.value.maxData.toFloat() == 0f && data.value.compareMaxData.toFloat() != 0f) {
            data.value.compareMaxData.toFloat()
        } else if (data.value.compareMaxData.toFloat() == 0f && data.value.maxData.toFloat() != 0f) {
            data.value.maxData.toFloat()
        } else {
            max(data.value.maxData.toFloat(), data.value.compareMaxData.toFloat())
        }

        initChart(min, max)

    }

    @SuppressLint("SuspiciousIndentation")
    private fun setAvgInfo(valueData: UricAcidBean) {
        var list: MutableList<ValueMap> = mutableListOf()
        list = setdataList(valueData.value, list)

        adapter.setNewInstance(list)

    }

    private fun setdataList(
        valueData: Value,
        list: MutableList<ValueMap>
    ): MutableList<ValueMap> {
        // 标题头
        val data0 = ValueMap().apply {
            title = contentStr[0]
            if (type == 2) {
                var tv1 = binding.tvHideDate.text.toString()
                var tvarray = tv1.split("至")
                tv1 = tvarray[0].substring(5, tvarray[0].length)
                valueCompare = "对比周\n$tv1"
                tv1 = tvarray[1].substring(5, tvarray[0].length)
                valueCompare += "至$tv1"

                tv1 = binding.tvShowDate.text.toString()
                tvarray = tv1.split("至")
                tv1 = tvarray[0].substring(5, tvarray[0].length)
                value = "选择周\n$tv1"
                tv1 = tvarray[1].substring(5, tvarray[0].length)
                value += "至$tv1"
            } else {
                when (type) {
                    3 -> {//月
                        valueCompare = "对比月\n" + binding.tvHideDate.text
                        value = "选择月\n" + binding.tvShowDate.text
                    }

                    4 -> {//年
                        valueCompare = "对比年\n" + binding.tvHideDate.text
                        value = "选择年\n" + binding.tvShowDate.text
                    }

                    else -> {//日
                        valueCompare = "对比日期\n" + binding.tvHideDate.text
                        value = "选择日期\n" + binding.tvShowDate.text
                    }
                }
            }
            state = 0
        }
        list.add(data0)
        if (type == 1){  //日对比数据只有两项
            //测量次数
            val data1 = ValueMap().apply {
                title = contentStr[1]
                state =
                    if (valueData.normal.toInt() > valueData.compareNormal.toInt())
                        1
                    else if (valueData.normal.toInt() < valueData.compareNormal.toInt())
                        2
                    else if (valueData.normal.toInt() == 0 && valueData.compareNormal.toInt() == 0)
                        3 else 0
                valueCompare =  "${valueData.compareNormal}次"
                value =  "${valueData.normal}次"

            }
            list.add(data1)
            //高尿酸
            val data2 = ValueMap().apply {
                title = contentStr[2]
                state =
                    if (valueData.high.toFloat() > valueData.highCompare.toFloat()) 1 else if (valueData.high.toInt() < valueData.highCompare.toInt()) 2 else 0
                valueCompare =  "${valueData.highCompare}次"
                value =  "${valueData.high}次"
            }

            list.add(data2)
        }else{  //周，年，月有7项
            //累计次数
            val data1 = ValueMap().apply {
                title = otherContentStr[1]
                state =
                    if (valueData.count.toInt() > valueData.compareCount.toInt())
                        1
                    else if (valueData.count.toInt() < valueData.compareCount.toInt())
                        2
                    else if (valueData.count.toInt() == 0 && valueData.compareCount.toInt() == 0)
                        3 else 0
                valueCompare =  "${valueData.compareCount}次"
                value =  "${valueData.count}次"

            }
            list.add(data1)

            //平均尿酸
            val data2 = ValueMap().apply {
                title = otherContentStr[2]
                state =
                    if (valueData.avgData.toFloat() > valueData.compareAvgData.toFloat()) 1 else if (valueData.avgData.toFloat() < valueData.compareAvgData.toFloat()) 2 else 0
                valueCompare =  "${valueData.compareAvgData}μmol/L"
                value =  "${valueData.avgData}μmol/L"
            }
            list.add(data2)

            //最高尿酸
            val data3 = ValueMap().apply {
                title = otherContentStr[3]
                state =
                    if (valueData.maxData.toFloat() > valueData.compareMaxData.toFloat()) 1 else if (valueData.maxData.toFloat() < valueData.compareMaxData.toFloat()) 2 else 0
                valueCompare =  "${valueData.compareMaxData}μmol/L"
                value =  "${valueData.maxData}μmol/L"
            }
            list.add(data3)

            //最低尿酸
            val data4 = ValueMap().apply {
                title = otherContentStr[4]
                state =
                    if (valueData.minData.toFloat() > valueData.compareMinData.toFloat()) 1 else if (valueData.minData.toFloat() < valueData.compareMinData.toFloat()) 2 else 0
                valueCompare =  "${valueData.compareMinData}μmol/L"
                value =  "${valueData.minData}μmol/L"
            }
            list.add(data4)

            //正常次数
            val data5 = ValueMap().apply {
                title = otherContentStr[5]
                state =
                    if (valueData.normal.toFloat() > valueData.compareNormal.toFloat()) 1 else if (valueData.normal.toFloat() < valueData.compareNormal.toFloat()) 2 else 0
                valueCompare =  "${valueData.compareNormal}次"
                value =  "${valueData.normal}次"
            }
            list.add(data5)

            //高尿酸次数
            val data6 = ValueMap().apply {
                title = otherContentStr[6]
                state =
                    if (valueData.high.toFloat() > valueData.highCompare.toFloat()) 1 else if (valueData.high.toFloat() < valueData.highCompare.toFloat()) 2 else 0
                valueCompare =  "${valueData.highCompare}次"
                value =  "${valueData.high}次"
            }
            list.add(data6)
        }

        return list
    }

    @SuppressLint("SuspiciousIndentation")
    private fun initChart(min: Float, max: Float) {
//        if (type == 1) {
//            binding.mLineChart.let {
//                it.clear()
//                it.setNoDataText(getString(R.string.line_chart_not_data))
//                it.setNoDataTextColor(ContextCompat.getColor(requireContext(), R.color.col_455))
//                it.setLayerType(View.LAYER_TYPE_SOFTWARE, null)
//
//                it.setBackgroundColor(Color.WHITE) ///color
//                it.description.isEnabled = false
//                it.setTouchEnabled(true)
//
//                it.setScaleEnabled(true)
//                it.setPinchZoom(false)
//
//                val minScale = 2f // 最小缩放比例
//                val maxScale = 10f // 最大缩放比例
//
//                it.setVisibleXRangeMaximum(maxScale)
//                it.setVisibleXRangeMinimum(minScale)
//                it.setDrawGridBackground(false)
//                it.maxHighlightDistance = 300f
//
//
//                it.isDragEnabled = true
//                val m = Matrix()
//                m.postScale(5f, 1f)
//                it.viewPortHandler.refresh(m, it, false)
//                it.isScaleXEnabled = true                 //支持x轴缩放
//                it.isScaleYEnabled = false
//
//
//                val x = it.xAxis
//                x.granularity = 1f  //精准设置
//                x.textColor = ContextCompat.getColor(requireContext(), R.color.col_92a)
//                x.isEnabled = true
//                x.setDrawGridLines(false)  //不绘制y
//                x.setDrawAxisLine(false)
//
//                x.position = XAxis.XAxisPosition.BOTTOM
//                x.setAvoidFirstLastClipping(false)
//                x.setValueFormatter { value, axis ->
//                    var index = value.toInt()
//                    //Log.e("x轴", "$value")
//                    if (index < 0 || index >= lineValue.size) {
//                        ""
//                    } else {
//                        "${(lineValue[value.toInt()].data as MutableList<String>)[0]}"
//                    }
//                }
//                //y轴
//                //y轴
//                val y = it.axisLeft
//
//                y.setLabelCountAndMaxMinValue(6, true, min , max)
//                y.textColor = ContextCompat.getColor(requireContext(), R.color.col_92a)
//                y.setDrawAxisLine(false)
//                y.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
//                y.gridColor = ContextCompat.getColor(requireContext(), R.color.col_92a)
//                y.setGridDashedLine(DashPathEffect(floatArrayOf(5f, 5f), 0f))
//                y.setDrawGridLines(true)  //绘制横者的x轴
//                y.setDrawZeroLine(true)
//
//                var markerView = ICompareMarkView(
//                    requireContext(), R.layout.mark_view_compare, "μmol/L",
//                    ICompareMarkView.MarkPage.UricAcid
//                )
//                it.marker = markerView
//                markerView.chartView = it
//                it.axisRight.isEnabled = false
//                it.legend.isEnabled = false
//
//                //   it.animateXY(2000, 2000)  //设置xy轴进入的动画
//                it.invalidate()
//                if (!lineValue.isNullOrEmpty()) {
//                    val barsetsNew: java.util.ArrayList<ILineDataSet> = java.util.ArrayList()
//
//                    var segments = splitDataIntoSegments(list)
//                    if (segments.size > 0) {
//                        segments = checkData(segments)
//                    }
//                    val dataSets = segments.mapNotNull { segment ->
//                        if (segment.isEmpty()) return@mapNotNull null
//
//                        val entries = segment.mapIndexed { index, model ->
//                            Entry(
//                                convertTimeToIndex(model.time).toFloat(),
//                                model.uaValue,
//                                lineValue[convertTimeToIndex(model.time)].data
//                            )
//                        }
//
//                        return@mapNotNull setData(entries)
//                    }
//                    var segmentsCompare = splitDataIntoSegments(listCompare)
//                    if (segmentsCompare.size > 0) {
//                        segmentsCompare = checkData(segmentsCompare)
//                    }
//                    val dataSetsCompare = segmentsCompare.mapNotNull { segment ->
//                        if (segment.isEmpty()) return@mapNotNull null
//
//                        val entries = segment.mapIndexed { index, model ->
//                            Entry(
//                                convertTimeToIndex(model.time).toFloat(),
//                                model.uaValue,
//                                lineValueCompare[convertTimeToIndex(model.time)].data
//                            )
//                        }
//                        return@mapNotNull setData2(entries)
//                    }
//                    barsetsNew.addAll(dataSets)
//                    barsetsNew.addAll(dataSetsCompare)
//                    val lineData = LineData(barsetsNew)
//                    lineData.setValueTextSize(9f)
//                    lineData.setDrawValues(false)
//                    it.data = lineData
//
//                    it.moveViewToX(lineValue[lineValue.size - 1].x)
//                }
//            }
//        } else {
            binding.mBarChart.let {
                it.clear()
                it.setNoDataText(getString(R.string.line_chart_not_data))
                it.setNoDataTextColor(ContextCompat.getColor(requireContext(), R.color.col_455))
                it.setLayerType(View.LAYER_TYPE_SOFTWARE, null)
                if (barValue.size == 0 && barValueCompare.size == 0) {
                    return@let
                }
                it.setBackgroundColor(Color.WHITE) ///color
                it.description.isEnabled = false
                it.setTouchEnabled(true)
                it.setPinchZoom(true)//柱形图的横坐标缩放，

                it.setDrawGridBackground(false)//背景网格是否绘制
                it.maxHighlightDistance = 300f//设置高亮（Highlight）的最大距离


                it.isDragEnabled = true//是否启用拖动（drag）功能。
//                val m = Matrix()
//                m.postScale(1.5f, 1f)
//                it.viewPortHandler.refresh(m, it, false)
                setChartData(barValue.size, it)
                it.isScaleXEnabled = true  //支持x轴缩放
                it.isScaleYEnabled = false //支持Y轴缩放

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

//                x.labelCount = 6
                x.isEnabled = true
                x.setDrawGridLines(false)  //不绘制y
                x.setDrawAxisLine(false)
                x.xOffset = 0.6f
                x.position = XAxis.XAxisPosition.BOTTOM
                x.setValueFormatter { value, axis ->
                    var index = value.toInt()
                    //Log.e("x轴", "$value")
                    if (index < 0 || index >= barValue.size) {
                        ""
                    } else {
                        "${(barValue[value.toInt()].data as MutableList<String>)[0]}"
                    }
                }
//                x.setValueFormatter { value, axis ->
//                    var index = value.toInt()
////                LogUtils.d("x轴:$value")
//                    if (index < 0 || index >= dbpBarValue.size) {
//                        ""
//                    } else {
//                        "${(dbpBarValue[value.toInt()].data as MutableList<String>)[0]}"
//                    }
//                }
                //y轴
                val y = it.axisLeft
                y.setLabelCountAndMaxMinValue(6, true, min, max)
                y.textColor = ContextCompat.getColor(requireContext(), R.color.col_92a)
                y.setDrawAxisLine(false)
                y.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
                y.gridColor = ContextCompat.getColor(requireContext(), R.color.col_92a)
                y.setGridDashedLine(DashPathEffect(floatArrayOf(5f, 5f), 0f))
                y.setDrawGridLines(true)  //绘制横者的x轴
                y.setDrawZeroLine(true)
                y.xOffset = 5f
                var markerView = ICompareMarkView(
                    requireContext(), R.layout.mark_view_compare, "μmol/L",
                    ICompareMarkView.MarkPage.UricAcid
                )
                it.marker = markerView
                markerView.chartView = it
                it.axisRight.isEnabled = false
                it.legend.isEnabled = false

                //   it.animateXY(2000, 2000)  //设置xy轴进入的动画
//                binding.mBarChart.moveViewToX(gbpBarValue[gbpBarValue.size - 1].x)
                val sets: java.util.ArrayList<IBarDataSet> = java.util.ArrayList()
                val set1 = BarDataSet(barValue, "DataSet 1")
                set1.setDrawValues(false) // 不显示值
                set1.valueTextColor = ContextCompat.getColor(requireContext(), R.color.col_9BDd)
                set1.highLightColor =
                    ContextCompat.getColor(requireContext(), R.color.col_C6B)  //设置点后高亮颜色
                set1.color =
                    ContextCompat.getColor(requireContext(), R.color.col_9BDd) //xian de yanse
                sets.add(set1)

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

                val set2 = BarDataSet(barValueCompare, "DataSet2")
                set2.valueTextColor = ContextCompat.getColor(requireContext(), R.color.col_8c6)
                set2.highLightColor =
                    ContextCompat.getColor(requireContext(), R.color.col_8c6)  //设置点后高亮颜色
                set2.color =
                    ContextCompat.getColor(requireContext(), R.color.col_9BD) //xian de yanse
                val data2 = BarData(set2)
                sets.add(set2)
//            sets.add(setBarData())
//            sets.add(setBarOtherData())
//            setLegend()min.toFloat()
//            setAxis()
                var d = BarData(sets)
                d.setValueTextSize(9f)
                d.setDrawValues(false)
                val spaceForBar: Float
                if (type == 2) {
                    spaceForBar = 0.14f // 柱形图之间的间隔
                    d.barWidth = 0.34f
                } else {
                    spaceForBar = 0.14f // 柱形图之间的间隔
                    d.barWidth = calculateBarWidth(d.dataSetCount)
                }
                d.groupBars(0f, spaceForBar, 0.03f)
                x.setCenterAxisLabels(true)
                x.axisMinimum = 0f //最小值 从0开始

                x.axisMaximum = barValueCompare.size.toFloat() //最大值


                val groupSpace = 0.2f
                val barSpace = 0.04f
                val barWidth = 0.36f
                //设置柱子宽度
                //关键的地方在于 需要满足该等式,标签才能居中：
                //(barSpace + barWidth) * 柱形图数量(比如我的是每组两个) + groupSpace = 1

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


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

            }

        }
//    }


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

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

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

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

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

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

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

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

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

    }
}