package com.zj365.health.fragment

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.DashPathEffect
import android.graphics.Matrix
import android.graphics.Typeface
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.text.SpannableString
import android.text.Spanned
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.text.isDigitsOnly
import androidx.fragment.app.Fragment
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.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.IFillFormatter
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.tamsiree.rxkit.RxTimeTool
import com.xty.base.fragment.BaseVmFrag
import com.xty.base.utils.OrganStatusCalcUtil
import com.xty.common.Const
import com.xty.common.LogUtils
import com.xty.common.MMkvHelper
import com.xty.common.TimeSelect
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.util.CommonUtils
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.act.HealthMainAct
import com.zj365.health.act.exception.BaseExceptionDataAct
import com.zj365.health.adapter.XyaAdapter
import com.zj365.health.databinding.FragXyaBinding
import com.zj365.health.model.XyaChildBean
import com.zj365.health.vm.XyaVm
import com.zj365.health.weight.HealthDialog
import com.zj365.health.weight.IMarkView
import com.zj365.health.weight.XyStudyDialog
import com.xty.network.model.DbpBean
import com.xty.network.utils.TimeTransformUtils
import java.lang.Float.max
import java.lang.Float.min
import java.text.SimpleDateFormat
import java.util.*

/**
 * 血压
 */
class XueyaFrag : BaseVmFrag<XyaVm>() {

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

    var isDemonstrate: Boolean = false
    val weeker by lazy { arrayOf("周一", "周二", "周三", "周四", "周五", "周六", "周日") }
    val fomartStr by lazy { arrayOf("HH:mm", "HH:mm", "MM-dd", "MM-dd", "yy-MM") }
    private val weekStr by lazy { resources.getStringArray(R.array.week_day) }

    //icon图
    private val icons = arrayOf(
        R.mipmap.shuzhuangtu,
        R.mipmap.ic_shuzhuangtu_yixuan,
        R.mipmap.ic_zhexiant,
        R.mipmap.zhexiant_yixuan
    )
    private var dbpValue = arrayListOf<Entry>()  //曲线数据
    private var gbpValue = arrayListOf<Entry>()  //曲线数据
    var dbpBarValue = arrayListOf<BarEntry>()  //低压曲线数据
    var gbpBarValue = arrayListOf<BarEntry>()  //高压曲线数据
    var type = 1
    var dialog: XyStudyDialog? = null
    var dialog1: XyStudyDialog? = null
    var dialogStuding: XyStudyDialog? = null
    var dialogStudyFail: XyStudyDialog? = null

    //是否首次校准
    var isFirstAlignTest = false

    //是否学习成功
    var isStudySuccess = false
    var studyStatus = 0
//    val timeSelect by lazy {
//        TimeSelect(requireContext()) {
//            type=0
//            mViewModel.getXyaData(type, binding.mTvTime.text.toString(),id)
//        }
//    }


    var tip =
        "智能手表因无气囊装置，且受手表佩戴松紧度，被采集人运动状态及无固定采集姿势等影响，所采集血压数据无法达到医学级精准，故手表不能替代血压计使用。如发现app内显示的血压值误差在10毫米汞柱以上，建议点击“血压校准”上传血压数据，系统会根据您上传的血压值建立个人血压模型并在2小时以内自动进行血压校准，部分用户，可能需要多次校准后血压才会相对准确。"
    val tipDialog by lazy {
        HealthDialog(requireContext(), true, tip) {
        }
    }


    val tipAdapter by lazy { XyaAdapter() }
    var id = ""
    override fun setLayout(): View = binding.root

    override fun setViewModel() = XyaVm()
    override fun initData() {
        super.initData()
        id = arguments?.getString("id").toString()
    }

    private fun isBlueTooth(): Boolean {
        return CommonUtils.isBlueTooth(MMkvHelper.getInt(Const.Watch_Device_Type)) && !CommonUtils.getBlueToothMac()
            .isNullOrEmpty()
    }

    override fun initView() {
        super.initView()
        initTab()
        initTimeSelect()
        context?.let {
            dialog = XyStudyDialog(it, "首次校准，请先完成血压学习后 再进行校准。") {
                //血压学习
                RouteManager.goAct(ARouterUrl.BLOOD_STUDY)
            }
            dialog1 = XyStudyDialog(it, "再次学习校准数据会被删除") {
                //血压学习
                RouteManager.goAct(ARouterUrl.BLOOD_STUDY)
            }

            dialogStuding = XyStudyDialog(it, "血压数据在学习中，请稍候") {
            }

            dialogStudyFail = XyStudyDialog(it, "血压学习失败，继续学习") {
                RouteManager.goAct(ARouterUrl.BLOOD_STUDY)
            }
        }
        binding.mBarChart.setNoDataText(getString(R.string.line_chart_not_data))
        binding.mBarChart.setNoDataTextColor(
            ContextCompat.getColor(
                requireContext(),
                R.color.col_455
            )
        )

        binding.mOrganView.ivSecond.setOnClickListener {
            val text = binding.mOrganView.tvSecondName.text.toString()
            bundle.clear()
            bundle.putString(BaseExceptionDataAct.exceptionKey, text)
            bundle.putStringArrayList(BaseExceptionDataAct.exceptionList, highList)
            bundle.putStringArrayList(BaseExceptionDataAct.exceptionListTime, highListTime)
            moveToErrorShow(bundle)
        }
        binding.compareTv.setOnClickListener {
            if (isDemonstrate) {
                (requireActivity() as HealthMainAct).dialogBind.show()
                return@setOnClickListener
            }
            bundle.clear()
            bundle.putString("id", id)
            bundle.putString("type", "6")// 血压
            RouteManager.goAct(ARouterUrl.COMPARE_DATA_ACT, bundle)
        }
        binding.mOrganView.ivThree.setOnClickListener {
            val text = binding.mOrganView.tvThreeName.text.toString()
            bundle.clear()
            bundle.putString(BaseExceptionDataAct.exceptionKey, text)
            bundle.putStringArrayList(BaseExceptionDataAct.exceptionList, lowList)
            bundle.putStringArrayList(BaseExceptionDataAct.exceptionListTime, lowListTime)
            moveToErrorShow(bundle)
        }
        binding.mLineChart.setNoDataText(getString(R.string.line_chart_not_data))
        binding.mLineChart.setNoDataTextColor(
            ContextCompat.getColor(
                requireContext(),
                R.color.col_455
            )
        )
        binding.zhexianTv.setOnClickListener {
            binding.mLineChart.visibility = View.VISIBLE
            binding.mBarChart.visibility = View.GONE
            binding.zhuzhuanTv.setImageResource(icons[0])
            binding.zhexianTv.setImageResource(icons[3])
        }
        binding.zhuzhuanTv.setOnClickListener {
            binding.mLineChart.visibility = View.GONE
            binding.mBarChart.visibility = View.VISIBLE
            binding.zhuzhuanTv.setImageResource(icons[1])
            binding.zhexianTv.setImageResource(icons[2])
        }
        binding.mTip.setOnClickListener {
            tipDialog.show()
        }
        binding.mGroup.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.mDay -> {
                    binding.mTvTime.visibility = View.VISIBLE
                    var selTime = binding.mTvTime.text.toString()
                    val date2String = RxTimeTool.date2String(Date(), SimpleDateFormat("yyyy-MM-dd"))
                    type = if (selTime == date2String) {   //是当天
                        1
                    } else {
                        0
                    }
                }

                R.id.mWeek -> {
                    binding.mTvTime.visibility = View.GONE
                    type = 2
                }

                R.id.mMonth -> {
                    binding.mTvTime.visibility = View.GONE
                    type = 3
                }

                R.id.mYear -> {
                    binding.mTvTime.visibility = View.GONE
                    type = 4
                }
            }
            if (type < 2) {
                mViewModel.getXyaData(type, binding.mTvTime.text.toString(), id, isDemonstrate)

            } else {
                mViewModel.getXyaData(type, null, id, isDemonstrate)
            }

        }

        isDemonstrate = (requireActivity() as HealthMainAct).isDemonstrate
        if (isDemonstrate) {
            binding.tvXinLv.text = "116/79"
            binding.tvTestTime.text = RxTimeTool.getCurTimeString(
                SimpleDateFormat("HH:mm")
            )
        } else {
            mViewModel.getLastData(id)
        }
        CommonUtils.getMyUserInfo()?.let {
            mViewModel.calibrationHistory(it.id)
        }
        mViewModel.getXyaData(
            type,
            RxTimeTool.getCurTimeString(SimpleDateFormat("yyyy-MM-dd")),
            id,
            isDemonstrate
        )
        mViewModel.getSetting(Const.DBP_SETTING)



        binding.child.mRecycle.adapter = tipAdapter
        binding.child.mRecycle.layoutManager = LinearLayoutManager(requireContext())

        /*  changeLevelColor(binding.mLevel2, R.color.col_e38)
          changeLevelColor(binding.mLevel3, R.color.col_f75)
          changeLevelColor(binding.mLevel21, R.color.col_e38)
          changeLevelColor(binding.mLevel31, R.color.col_f75)*/
        changeLevelColor(binding.mDescMax, R.color.col_9BDd)
        changeLevelColor(binding.mDescMin, R.color.col_9BD)
        binding.mTvTime.text = RxTimeTool.getCurTimeString(SimpleDateFormat("yyyy-MM-dd"))
        binding.mTvTime.setOnClickListener {
            timeSelect.selectTime(it)
        }
        if (id == MMkvHelper.getLong(Const.USER_ID).toString()) {
            binding.mCardBlood.visibility = View.VISIBLE
        } else {
            binding.mCardBlood.visibility = View.GONE
        }
        binding.mCardBlood.setOnClickListener {
            if (isDemonstrate) {
                return@setOnClickListener
            }
            RouteManager.goAct(ARouterUrl.BLOOD_ALIGN)
//            //血压校准
//            //4g才有血压学习
//            if (!isBlueTooth()){
//                //4g手表点击血压校准
//                if (isFirstAlignTest ){
//                    //如果是首次血压校准，判断血压学习数据
//
//                    when(studyStatus){
//                        0 -> {
//                            //学习成功,继续校准
//                            RouteManager.goAct(ARouterUrl.BLOOD_ALIGN)
//                            return@setOnClickListener
//                        }
//                        1 -> {
//                            //学习中
//                            dialogStuding?.show()
//                        }
//                        2 -> {
//                            //学习失败
//                            dialogStudyFail?.show()
//                        }
//                    }
//
//                } else {
//                    //有校准数据，继续校准
//                    RouteManager.goAct(ARouterUrl.BLOOD_ALIGN)
//                }
//            } else {
//                RouteManager.goAct(ARouterUrl.BLOOD_ALIGN)
//            }
        }
//        binding.mCardBloodStudy.setOnClickListener {
//            //4g才有血压学习
//            if (isFirstAlignTest ){
//                //如果是首次血压校准，跳转去血压学习
//                dialog?.show()
//                return@setOnClickListener
//            } else {
//                //如果有数据提示之后再跳转
//                dialog1?.show()
//                return@setOnClickListener
//            }
//        }
//        binding.mCardBloodStudy.visibility = View.GONE
//        if (isBlueTooth()){
//            binding.mCardBloodStudy.visibility = View.GONE
//        } else {
//            binding.mCardBloodStudy.visibility = View.VISIBLE
//        }


        binding.tvTips.text = "了解血压：\n血压是指血液在血管内流动时作用于单位面积血管壁的侧压力，它是推动血液在血管内流动的动力。" +
                "由两个数值组成，收缩压显示心脏收缩或跳动时的血管压力，俗称高压；舒张压显示心脏在两次跳动之间舒张时的血管压力，俗称低压。\n\n" +
                "血压算法原理：\n手表测血压的原理是使用光电传感器和算法估算出血压值，也叫光学测量法；光学测量技术，即使用LED发出绿光，" +
                "然后绿光穿过皮肤照射到血液中，感受到的反射光变化后计算出血压值。这种技术被称为光学脉搏波技术，它利用了光波通过人体不同颜色组织时的衰减特性，" +
                "通过物理算法计算出起始点和终止点的时间和速度，从而测量血压。\n\n\n" +
                "测量结果仅供参考，不作为医疗诊断依据。"
    }

    private fun moveToErrorShow(bundle: Bundle) {
        RouteManager.goAct(ARouterUrl.XUEYA_EXCEPTION_DATA_ACT, bundle)
    }

    fun changeLevelColor(tv: TextView, color: Int) {
        val draw = ContextCompat.getDrawable(requireContext(), R.drawable.shape_dot_96d)
        val bg = draw as GradientDrawable
        bg.setColor(ContextCompat.getColor(requireContext(), color))
        bg.mutate()
        bg.setBounds(0, 0, bg.minimumWidth, bg.minimumHeight)
        tv.setCompoundDrawables(bg, null, null, null)
    }

    override fun observer() {
        mViewModel.dbpValue.observe(this) {
            if (it == null || it[type] == null) {
                return@observe
            }
            // 这里把日的原始数据暂存起来，跳转异常页面时使用
            val daysModelList: MutableList<DbpBean.Model> = it[type]!!.model
            when (type) {
                1 -> {//日
                    it[type]!!.model = it[type]!!.mapDataToTimeNodes(it[type]!!.model)
                }

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

                3 -> {//月
                    it[type]!!.model = it[type]!!.fillMissingData(
                        it[type]!!.model,
                        binding.tvShowDate.text.toString()
                    )
                }

                4 -> {//年
                    it[type]!!.model = it[type]!!.fillMissingData(it[type]!!.model)
                }
            }

            setValuss(daysModelList, it[type])
            it[type]?.let { bean ->
                bean.value.let { value ->
                    if (bean == null) {
                        binding.mAvgDbp.setValue("-")
                        binding.mMaxDbp.setValue("-")
                        binding.mLowDbp.setValue("-")
                    } else {
                        binding.mAvgDbp.setValue("${value.highAvg}/${value.lowAvg}")
                        binding.mMaxDbp.setValue("${value.highMax}/${value.lowMax}")
                        binding.mLowDbp.setValue("${value.highMin}/${value.lowMin}")

                    }
                    //                    binding.mAvhighDbp.text="${value.highAvg}/${value.lowAvg}"
                    //                    binding.mMaxDbp.text="${value.highMax}/${value.lowMax}"
                    //                    binding.mLowDbp.text="${value.highMin}/${value.lowMin}"
                }
            }
        }
        mViewModel.calibrationHistoryLive.observe(this) {
            var result = 0
            it.data.let {
                result = it.size
            }
            isFirstAlignTest = result == 0
        }
        mViewModel.recordList.observe(this) {
            var result = 0
            it.data.let {
                result = it.size
            }
            isStudySuccess = result == 0
        }
        mViewModel.setting.observe(this) {
            if (it.data.isNotEmpty()) {
                var map = LinkedHashMap<String, XyaChildBean>()
                var list = mutableListOf<XyaChildBean>()
                var topBean = XyaChildBean().apply {
                    this.sbp = "收缩（高压）"
                    this.dbp = "舒张（低压）"
                    this.desc = "类别（危险程度）"
                }
                list.add(topBean)
                it.data.forEach {
                    if (map.containsKey(it.name)) {
                        map[it.name]!!.dbp = it.content
                    } else {
                        var bean = XyaChildBean()
                        bean.sbp = it.content
                        bean.desc = it.name
                        map.put(it.name, bean)
                    }
                }
                var iterator = map.iterator()
                while (iterator.hasNext()) {
                    list.add(iterator.next().value)
                }
                tipAdapter.setNewInstance(list)
            }
        }

        mViewModel.lastData.observe(this) {
            it.data?.let {
                binding.tvXinLv.text = "${it.gdbp}/${it.ddbp}"
                binding.tvTestTime.text = RxTimeTool.milliseconds2String(
                    it.time.toLong() * 1000,
                    SimpleDateFormat("HH:mm")
                )
            }
        }
    }

    private fun setOrganStatu() {

        binding.mOrganView.tvFirstName.text = "正常"
        binding.mOrganView.tvFirstValue.text = setSpan(normalTime)
        if (normalTime == 0) {
            binding.mOrganView.ivFirst.visibility = View.INVISIBLE
        } else {
            binding.mOrganView.ivFirst.visibility = View.VISIBLE
        }
        binding.mOrganView.tvSecondName.text = "高血压"
        binding.mOrganView.tvSecondValue.text = setSpan(highTime)
        if (highTime == 0) {
            binding.mOrganView.ivSecond.visibility = View.INVISIBLE
        } else {
            binding.mOrganView.ivSecond.visibility = View.VISIBLE
        }
        binding.mOrganView.tvThreeName.text = "低血压"
        binding.mOrganView.tvThreeValue.text = setSpan(lowTime)
        if (lowTime == 0) {
            binding.mOrganView.ivThree.visibility = View.INVISIBLE
        } else {
            binding.mOrganView.ivThree.visibility = View.VISIBLE
        }

        binding.mOrganView.root.visibility = View.VISIBLE
    }

    private fun setSpan(time: Int): SpannableString {
        var statuSpan = SpannableString("${time}次")

        statuSpan.setSpan(
            ForegroundColorSpan(
                //设置字体颜色
                ContextCompat.getColor(
                    requireContext(), R.color.black
                )
            ), 0, statuSpan.length - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        //设置字体大小(绝对值,单位：像素),第二个参数boolean dip，如果为true，表示前面的字体大小单位为dip，否则为像素
        statuSpan.setSpan(
            AbsoluteSizeSpan(24, true),
            0, statuSpan.length - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        //设置字体样式: NORMAL正常，BOLD粗体，ITALIC斜体，BOLD_ITALIC粗斜体
        statuSpan.setSpan(
            StyleSpan(Typeface.BOLD),
            0, statuSpan.length - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )

        return statuSpan
    }

    var normalTime: Int = 0
    var highTime: Int = 0
    var lowTime: Int = 0

    var highList = ArrayList<String>()
    var lowList = ArrayList<String>()
    var highListTime = ArrayList<String>()
    var lowListTime = ArrayList<String>()
    private fun getOrganStatu(model: DbpBean.Model) {
        var statu = model.highDbp

        when (OrganStatusCalcUtil.bloodStatu(statu.toFloat())) {//0:正常 1：低血压 2:1级高血压 3:2级高血压 4:3级高血压
            1 -> {
                lowTime++
                lowList.add(statu.toInt().toString() + "/" + model.lowDbp.toInt())
                lowListTime.add(model.time)
            }

            2, 3, 4 -> {
                highTime++
                highList.add(statu.toInt().toString() + "/" + model.lowDbp.toInt())
                highListTime.add(model.time)
            }

            else ->
                normalTime++
        }
    }

    /**
     * 周数据
     */
    private fun getWeeks(time: Long): String {
        var calendear = Calendar.getInstance()
        var strData = RxTimeTool.milliseconds2String(time, SimpleDateFormat("yyyy-MM-dd"))
        var times = strData.split("-")
        calendear.set(times[0].toInt(), times[1].toInt() - 1, times[2].toInt())
        var intWeek = calendear.get(Calendar.DAY_OF_WEEK)
        return weekStr[intWeek - 1]
    }

    /**
     * 是否是选的日，只有选日的时候才会刷新正常，异常状态
     */
    private fun selectDay(): Boolean {
        return type < 2
    }

    //设置数据
    private fun setValuss(daysModelList: MutableList<DbpBean.Model>, bean: DbpBean?) {
        if (bean == null) {
            return
        }
        //setAvgInfo(bean.value)
        val list = bean.model
        dbpValue.clear()
        gbpValue.clear()
        dbpBarValue.clear()
        gbpBarValue.clear()
        val rever = (list.indices).reversed()

        if (selectDay()) {//如果是当天才操作
            normalTime = 0
            lowTime = 0
            highTime = 0
            highList.clear()
            highListTime.clear()
            lowList.clear()
            lowListTime.clear()
        }
        for (t in daysModelList.indices) {
            if (selectDay()) {//如果是当天才操作
                getOrganStatu(daysModelList[daysModelList.size - t - 1])
            }
        }
        for (i in rever) {
            val bean = list[list.size - i - 1]
//            var times = bean.time.toLong() * 1000
//            var strTime = RxTimeTool.milliseconds2String(times, SimpleDateFormat(fomartStr[type]))

            //中间两端在x轴显示尺度 其他情况下不显示
            val listTipG = mutableListOf<String>()
            //按顺序 分别是  时间 0 高压 1 低压
            setTipTime(listTipG, i, list, bean)
            listTipG.add("0")
            listTipG.add(bean.highDbp.toString())
            listTipG.add(bean.lowDbp.toString())
            gbpValue.add(
                Entry(
                    (list.size - 1 - i).toFloat(),
                    bean.highDbp.toFloat(),
                    listTipG
                )
            )
            gbpBarValue.add(
                BarEntry(
                    (list.size - 1 - i).toFloat(),
                    bean.highDbp.toFloat(),
                    listTipG
                )
            )
            val listTipD = mutableListOf<String>()
            //按顺序 分别是  时间  高压 低压
            setTipTime(listTipD, i, list, bean)
            listTipD.add("1")
            listTipD.add(bean.highDbp.toString())
            listTipD.add(bean.lowDbp.toString())
            dbpValue.add(
                Entry(
                    (list.size - 1 - i).toFloat(),
                    bean.lowDbp!!.toFloat(),
                    listTipD
                )
            )
            dbpBarValue.add(
                BarEntry(
                    (list.size - 1 - i).toFloat(),
                    bean.lowDbp!!.toFloat(), listTipD

                )
            )
        }
        if (selectDay()) {//如果是当天才操作
            setOrganStatu()
        }
        val min: Float
        val max: Float
        if (bean.value.lowMin.toInt() == 0 && bean.value.highMin.toInt() != 0) {
            min = bean.value.highMin.toFloat()
        } else if (bean.value.highMin.toInt() == 0 && bean.value.lowMin.toInt() != 0) {
            min = bean.value.lowMin.toFloat()
        } else if (bean.value.highMin.toInt() == 0 && bean.value.lowMin.toInt() != 0) {
            min = 50f
        } else {
            min = min(bean.value.lowMin.toFloat(), bean.value.highMin.toFloat())
        }

        if (bean.value.lowMax.toInt() == 0 && bean.value.highMax.toInt() != 0) {
            max = bean.value.highMax.toFloat()
        } else if (bean.value.highMax.toInt() == 0 && bean.value.lowMax.toInt() != 0) {
            max = bean.value.lowMax.toFloat()
        } else if (bean.value.highMax.toInt() == 0 && bean.value.lowMax.toInt() == 0) {
            max = 160f
        } else {
            max = max(bean.value.lowMax.toFloat(), bean.value.highMax.toFloat())
        }

        initChart(list, min, max)
    }

    private fun setTipTime(
        listTipG: MutableList<String>,
        i: Int,
        list: MutableList<DbpBean.Model>,
        bean: DbpBean.Model
    ) {
        when (type) {
            1, 3 -> {
                if (list[list.size - 1 - i].highDbp == 0f && list[list.size - 1 - i].lowDbp == 0f) {
                    list[list.size - 1 - i].highDbp = Float.NaN
                    list[list.size - 1 - i].lowDbp = Float.NaN
                }
                listTipG.add(bean.time)
            }

            2 -> {
                val parts = bean.time.split("-")
                val year = parts[0]
                val month = parts[1]
                val day = parts[2]

                listTipG.add("$month-$day")
            }

            else -> {
                listTipG.add("${bean.time}月")
            }
        }
    }

    private fun initChart(list: MutableList<DbpBean.Model>, min: Float, max: Float) {
        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(false)
            it.setPinchZoom(false)

            it.setDrawGridBackground(false)
            it.maxHighlightDistance = 300f


            it.isDragEnabled = true
            val m = Matrix()
            m.postScale(1.5f, 1f)
            it.viewPortHandler.refresh(m, it, false)
            it.isScaleXEnabled = true                 //支持x轴缩放
            it.isScaleYEnabled = false
//            if (dbpValue.size > 10) {
//                it.isDragEnabled = true
//                val m = Matrix()
//                m.postScale(1.5f, 1f)
//                it.viewPortHandler.refresh(m, it, false)
//                it.isScaleXEnabled = true                 //支持x轴缩放
//                it.isScaleYEnabled = false
//            } else {
//                it.isDragEnabled = false
//                it.isScaleXEnabled = false                 //支持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.setValueFormatter { value, axis ->
                var index = value.toInt()
//                LogUtils.d("x轴:$value")
                if (index < 0 || index >= dbpValue.size) {
                    ""
                } else {
                    "${(dbpValue[value.toInt()].data as MutableList<String>)[0]}"
                }
            }
            //y轴
            val y = it.axisLeft
//            y.axisMaximum=max
//            y.axisMinimum=min
//            y.setLabelCount(6, true)
            y.setLabelCountAndMaxMinValue(6, false, min - 30, max + 20)
            // y.setLabelCount(6, true)
            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_0F2)
            y.setGridDashedLine(DashPathEffect(floatArrayOf(5f, 0f), 0f))
            y.setDrawGridLines(true)  //绘制横者的x轴
            y.setDrawZeroLine(true)

            var markerView = IMarkView(
                requireContext(), R.layout.mark_view, "mmHg",
                IMarkView.MarkPage.XYa
            )
            it.marker = markerView
            markerView.chartView = it
            it.axisRight.isEnabled = false
            it.legend.isEnabled = false

            //   it.animateXY(2000, 2000)  //设置xy轴进入的动画


        }

        if (dbpValue.isNotEmpty() && gbpValue.isNotEmpty()) {
            binding.mLineChart.moveViewToX(gbpValue[gbpValue.size - 1].x)
        }

        val barsetsNew: java.util.ArrayList<ILineDataSet> = java.util.ArrayList()
        var segments = splitDataIntoSegments(list)
        if (segments.size > 0) {
            segments = checkData(segments)
        }
        // 高压
        val dataSetsGdp = segments.mapNotNull { segment ->
            if (segment.isEmpty()) return@mapNotNull null

            val entries = segment.mapIndexed { index, model ->
                Entry(
                    convertTimeToIndex(model.time, index).toFloat(),
                    model.highDbp,
                    gbpValue[convertTimeToIndex(model.time, index)].data
                )
            }
            return@mapNotNull setData(entries)
        }
        // 低压
        val dataSetsDdp = segments.mapNotNull { segment ->
            if (segment.isEmpty()) return@mapNotNull null

            val entries = segment.mapIndexed { index, model ->
                Entry(
                    convertTimeToIndex(model.time, index).toFloat(),
                    model.lowDbp,
                    dbpValue[convertTimeToIndex(model.time, index)].data
                )
            }
            return@mapNotNull setDataOther(entries)
        }

        barsetsNew.addAll(dataSetsGdp)
        barsetsNew.addAll(dataSetsDdp)

        val bard = LineData(barsetsNew)

        binding.mLineChart.data = bard
        binding.mLineChart.invalidate()

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

            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(
                when (type) {
                    1 -> {
                        11.5f
                    }

                    3 -> {
                        3.5f
                    }

                    else -> {
                        1f
                    }
                }, 0f
            )
            it.viewPortHandler.refresh(m, it, false)
            it.isScaleXEnabled = true  //支持x轴缩放
            it.isScaleYEnabled = false //支持Y轴缩放

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

//                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 ->
                if (value.toInt() >= 0 && value.toInt() < dbpBarValue.size) {
                    val str = "${(dbpBarValue[value.toInt()].data as MutableList<String>)[0]}"
                    LogUtils.d(
                        "size: " + dbpBarValue.size.toString() + "...IAxisValueFormatter   String:$str" + "value :" + value.toInt()
                            .toString()
                    )
                    str
                } else {
                    ""
                }
            }
            val y = it.axisLeft
            y.setLabelCountAndMaxMinValue(6, false, min - 30, max + 20)
            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_0F2)
            y.setGridDashedLine(DashPathEffect(floatArrayOf(5f, 0f), 0f))
            y.setDrawGridLines(true)  //绘制横者的x轴
            y.setDrawZeroLine(true)

            var markerView = IMarkView(
                requireContext(), R.layout.mark_view, "mmHg",
                IMarkView.MarkPage.XYa
            )
            it.marker = markerView
            markerView.chartView = it
            it.axisRight.isEnabled = false
            it.legend.isEnabled = false

            //   it.animateXY(2000, 2000)  //设置xy轴进入的动画

            if (dbpBarValue.isEmpty() && gbpBarValue.isEmpty()) {
                return
            }

            // 因为数组末尾可能添加了两个占位Entry（00:00,23:59）,所以实际最近数据的为第一个子集的倒数第1个
            if (segments.size > 1 && segments[0].isNotEmpty()) {
                it.moveViewToX(
                    convertTimeToIndex(
                        segments[0][segments[0].size - 1].time,
                        0
                    ).toFloat()
                )
            }
            // 需遵循公式 (barwidth + barspace) * 条数 + groupspace = 1，否则位置可能偏移
            // https://stackoverflow.com/questions/43480358/mpandroidchart-bar-chart-how-to-group-bars-with-random-x-axis-intervals-in-bet
            val groupSpace = 0.26f//组间隔
            val barSpace = 0.03f //每个柱状图的间隔
            val barWidth = 0.34f //每个柱状图的宽度

            val dataSets = ArrayList<IBarDataSet>()
            dataSets.add(setBarOtherData(gbpBarValue))
            dataSets.add(setBarData(dbpBarValue))
            val bard2 = BarData(dataSets)
            bard2.barWidth = barWidth //calculateBarWidth(dbpBarValue.size)
            it.data = bard2

            x.axisMinimum = -0.5f
            x.axisMaximum =
                0 + it.barData.getGroupWidth(groupSpace, barSpace) * gbpBarValue.size
            x.setCenterAxisLabels(true)

            bard2.groupBars(0f, groupSpace, barSpace)

            it.invalidate()
        }
    }

    private fun setBarOtherData(entries: List<BarEntry>): BarDataSet {
        val set1: BarDataSet
        if (binding.mBarChart.data != null && binding.mBarChart.data.dataSetCount > 0) {
            set1 = binding.mBarChart.data.getDataSetByIndex(0) as BarDataSet
            set1.entries = entries
            binding.mBarChart.data.notifyDataChanged()
            binding.mBarChart.notifyDataSetChanged()
        } else {
            // create a dataset and give it a type
            set1 = BarDataSet(entries, "DataSet 2")
//            set1.mode = LineDataSet.Mode.LINEAR

            set1.setDrawValues(false) // 不显示值
            set1.valueTextColor = ContextCompat.getColor(requireContext(), R.color.col_9BDd)
            set1.highLightColor =
                ContextCompat.getColor(requireContext(), R.color.col_EFF)  //设置点后高亮颜色
            set1.color = ContextCompat.getColor(requireContext(), R.color.col_9BDd) //xian de yanse

            // create a data object with the data sets
            val data = BarData(set1)
            //data.setValueTypeface(tfLight)
            data.setValueTextSize(9f)
            data.setDrawValues(false)
            // set data
            //binding. mLineChart!!.data = data
        }

        return set1
    }


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

        for (model in dataList) {
            if (model.highDbp.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<DbpBean.Model>>): MutableList<MutableList<DbpBean.Model>> {
        when (type) {
            1 -> {
                val (startTime, endTime) =
                    TimeTransformUtils.calculateStartTimeAndEndTime(segmentsCompare[0][0].time)
                if (segmentsCompare[0][0].time != startTime) {
                    val d = mutableListOf<DbpBean.Model>()
                    val b = DbpBean.Model(startTime, 0f, 0f, null, null)
                    d.add(b)
                    segmentsCompare.add(d)
                }
                if (!TimeUtils.isToday(
                        binding.tvShowDate.text.toString(),
                        SimpleDateFormat("yyyy-MM-dd")
                    ) &&
                    segmentsCompare[segmentsCompare.size - 1][segmentsCompare[segmentsCompare.size - 1].size - 1].time != endTime
                ) {
                    val d = mutableListOf<DbpBean.Model>()
                    val b = DbpBean.Model(endTime, 0f, 0f, null, null)
                    d.add(b)
                    segmentsCompare.add(d)
                }
            }

            2 -> {
                val split = binding.tvShowDate.text.toString().split("至")
                val start = split[0]
                val end = split[1]

                if (segmentsCompare[0][0].time != start) {
                    val d = mutableListOf<DbpBean.Model>()
                    val b = DbpBean.Model(start, 0f, 0f, null, null)
                    d.add(b)
                    segmentsCompare.add(d)
                }
                if (segmentsCompare[segmentsCompare.size - 1][segmentsCompare[segmentsCompare.size - 1].size - 1].time != end) {
                    val d = mutableListOf<DbpBean.Model>()
                    val b = DbpBean.Model(end, 0f, 0f, null, null)
                    d.add(b)
                    segmentsCompare.add(d)
                }
            }

            3 -> {
                val split = binding.tvShowDate.text.toString().split("-")
                val year = split[0]//2023
                val month = split[1]//08

                val calendar = Calendar.getInstance()
                calendar.set(Calendar.YEAR, year.toInt())
                calendar.set(Calendar.MONTH, month.toInt() - 1) // Calendar.MONTH is 0-based
                val daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH)

                if (segmentsCompare[0][0].time != "$month-01") {
                    val d = mutableListOf<DbpBean.Model>()
                    val b = DbpBean.Model("$month-01", 0f, 0f, null, null)
                    d.add(b)
                    segmentsCompare.add(d)
                }
                if (!isCurYearMonth(
                        binding.tvShowDate.text.toString(),
                        SimpleDateFormat("yyyy-MM")
                    ) &&
                    segmentsCompare[segmentsCompare.size - 1][segmentsCompare[segmentsCompare.size - 1].size - 1].time != "$month-$daysInMonth"
                ) {
                    val d = mutableListOf<DbpBean.Model>()
                    val b = DbpBean.Model("$month-$daysInMonth", 0f, 0f, null, null)
                    d.add(b)
                    segmentsCompare.add(d)
                }
            }

            4 -> {
                if (segmentsCompare[0][0].time != "01") {
                    val d = mutableListOf<DbpBean.Model>()
                    val b = DbpBean.Model("01", 0f, 0f, null, null)
                    d.add(b)
                    segmentsCompare.add(d)
                }
                if (segmentsCompare[segmentsCompare.size - 1][segmentsCompare[segmentsCompare.size - 1].size - 1].time != "12") {
                    val d = mutableListOf<DbpBean.Model>()
                    val b = DbpBean.Model("12", 0f, 0f, null, null)
                    d.add(b)
                    segmentsCompare.add(d)
                }
            }
        }

        return segmentsCompare
    }

    private fun isCurYearMonth(dateString: String, dateFormat: SimpleDateFormat): Boolean {
        val date = dateFormat.parse(dateString)
        if (date == null) {
            LogUtils.w("isCurYearMonth, date == null")
            return false
        }
        val calendar = Calendar.getInstance()
        calendar.time = date

        val currentYear = Calendar.getInstance().get(Calendar.YEAR)
        val currentMonth = Calendar.getInstance().get(Calendar.MONTH)

        val isCurrentYear = calendar.get(Calendar.YEAR) == currentYear
        val isCurrentMonth = calendar.get(Calendar.MONTH) == currentMonth

        return isCurrentYear && isCurrentMonth
    }

    fun convertTimeToIndex(time: String, cur: Int): Int {
        var index = 0
        when (type) {
            1 -> {
                // 将时间格式转换为小时和分钟
                return findTimeIndex(time)
            }

            2 -> {
                val split = binding.tvShowDate.text.toString().split("至")
                val rangeStart = split[0]
                val rangeEnd = split[1]
                val formatter = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
                try {
                    val startDate = formatter.parse(rangeStart)
                    val endDate = formatter.parse(rangeEnd)
                    val inputDateObj = formatter.parse(time)
                    if (startDate == null || endDate == null || inputDateObj == null) {
                        LogUtils.w("data formatter result is null")
                        return 0
                    }
                    val calendar = Calendar.getInstance()
                    calendar.time = startDate
                    while (calendar.time <= endDate) {
                        if (calendar.time == inputDateObj) {
                            println("Index: $index")
                            break
                        }
                        calendar.add(Calendar.DATE, 1)
                        index++
                    }

                } catch (e: java.text.ParseException) {
                    e.printStackTrace()
                }
            }

            3 -> {
                // 将08-01格式转换为序号
                val parts = time.split("-")
                val month = parts[0].toInt()
                val day = parts[1].toInt()
                index = day - 1
            }

            else -> {
                index = if (time.isDigitsOnly()) (time.toInt() - 1) else 0
            }
        }

        return if (index < 0) cur + 1 else index
    }

    fun findTimeIndex(targetTime: String): Int {
        val targetTimeObj = SimpleDateFormat("HH:mm", Locale.getDefault()).parse(targetTime)
        val calendar = Calendar.getInstance()
        calendar.time = targetTimeObj

        val hours = calendar.get(Calendar.HOUR_OF_DAY)
        val minutes = calendar.get(Calendar.MINUTE)

        val index = (hours * 60 + minutes) / 10
        return index
    }

    private fun setBarData(entries: List<BarEntry>): BarDataSet {
        val set1: BarDataSet
        if (binding.mBarChart.data != null && binding.mBarChart.data.dataSetCount > 0) {
            set1 = binding.mBarChart.data.getDataSetByIndex(1) as BarDataSet
            set1.entries = entries
            binding.mBarChart.data.notifyDataChanged()
            binding.mBarChart.notifyDataSetChanged()
        } else {

            set1 = BarDataSet(entries, "DataSet 1")
//            set1.mode = BarDataSet.Mode.LINEAR
//            set1.isDrawValuesEnabled =true
            set1.valueTextColor = ContextCompat.getColor(requireContext(), R.color.col_e0b)
            set1.highLightColor =
                ContextCompat.getColor(requireContext(), R.color.col_e0b)  //设置点后高亮颜色
            set1.color = ContextCompat.getColor(requireContext(), R.color.col_9BD) //xian de yanse
            val data = BarData(set1)
            data.setValueTextSize(9f)
            data.setDrawValues(false)
        }
        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 setData(entries: 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.entries = entries
            binding.mLineChart.data.notifyDataChanged()
            binding.mLineChart.notifyDataSetChanged()
        } else {
            // create a dataset and give it a type
            set1 = LineDataSet(entries, "DataSet 1")
            set1.mode = LineDataSet.Mode.LINEAR
            set1.cubicIntensity = 0.2f
            set1.setDrawFilled(false)
            set1.lineWidth = 3f
            set1.circleRadius = 2f
            // 分段后，数据若有一个点需要显示
            set1.setDrawCircles(entries.size == 1)
            set1.highLightColor =
                ContextCompat.getColor(requireContext(), R.color.col_7CF)  //设置点后高亮颜色
            set1.enableDashedHighlightLine(10f, 5f, 0f)
            set1.setCircleColor(
                ContextCompat.getColor(
                    requireContext(),
                    R.color.col_02c
                )
            )    //#41C4AF
            set1.color = ContextCompat.getColor(requireContext(), R.color.col_9BDd) //xian de yanse

            set1.fillAlpha = 100
            set1.setDrawHorizontalHighlightIndicator(false)
            set1.fillFormatter =
                IFillFormatter { dataSet, dataProvider -> binding.mLineChart.axisLeft.axisMinimum }

            set1.setValueFormatter { value, entry, dataSetIndex, viewPortHandler ->

                "$value"
            }
            // create a data object with the data sets
            val data = LineData(set1)
            //data.setValueTypeface(tfLight)
            data.setValueTextSize(9f)
            data.setDrawValues(false)

            // set data
            //binding. mLineChart!!.data = data
        }

        return set1
    }

    private fun setDataOther(entries: 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.entries = entries
            binding.mLineChart.data.notifyDataChanged()
            binding.mLineChart.notifyDataSetChanged()
        } else {
            // create a dataset and give it a type
            set1 = LineDataSet(entries, "DataSet 1")
            set1.mode = LineDataSet.Mode.LINEAR
            set1.cubicIntensity = 0.2f
            set1.setDrawFilled(false)
            set1.lineWidth = 3f
            set1.circleRadius = 2f
            set1.setDrawCircles(entries.size == 1)
            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.RED);
            set1.fillAlpha = 100
            set1.setDrawHorizontalHighlightIndicator(false)
            set1.fillFormatter =
                IFillFormatter { dataSet, dataProvider -> binding.mLineChart.axisLeft.axisMinimum }

            set1.setValueFormatter { value, entry, dataSetIndex, viewPortHandler ->

                "$value"
            }
            // create a data object with the data sets
            val data = LineData(set1)
            //data.setValueTypeface(tfLight)
            data.setValueTextSize(9f)
            data.setDrawValues(false)

            // set data

        }
        return set1
    }


    /*
        @Subscribe(threadMode = ThreadMode.MAIN)
        fun refresh(event: BloodCalibrationEvent){
            if (type<2) {
                mViewModel.getXyaData(type, binding.mTvTime.text.toString(),id)
            } else {
                mViewModel.getXyaData(type, null,id)
            }
            mViewModel.getLastData(id)
        }
    */
    var dayDate = ""
    var weekDate = ""
    var mouthDate = ""
    var yearDate = ""
    private fun getDateAdd(days: Int): Date? {
        val c = Calendar.getInstance()
        c.add(Calendar.DAY_OF_MONTH, -days)
        return c.time
    }

    private val mTabEntities: ArrayList<CustomTabEntity> = ArrayList()
    private val mFragments: SparseArray<Fragment> = SparseArray()
    private val mTitles = arrayOf(
        "日", "周", "月", "年"
    )

    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()
        mFragments.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 -> {
                        binding.tvShowDate.text = dayDate
                        type = 1
                    }

                    1 -> {
                        binding.tvShowDate.text = weekDate
                        type = 2
                    }

                    2 -> {
                        binding.tvShowDate.text = mouthDate
                        type = 3
                    }

                    3 -> {
                        binding.tvShowDate.text = yearDate
                        type = 4
                    }
                }
                mViewModel.getXyaData(type, binding.tvShowDate.text.toString(), id, isDemonstrate)
            }

            override fun onTabReselect(position: Int) {
            }

        })

    }

    private fun initTimeSelect() {
        //日筛选
        val calendar = Calendar.getInstance()
        timeSelect.startDate.set(1922, 1, 1)
        timeSelect.endDate.set(
            calendar[Calendar.YEAR], calendar[Calendar.MONTH], if (calendar[Calendar.HOUR] >= 11) {
                calendar[Calendar.DATE]
            } else {
                calendar[Calendar.DATE]
            }
        )
        binding.tvShowDate.text = RxTimeTool.getCurTimeString(SimpleDateFormat("yyyy-MM-dd"))

        binding.tvShowDate.setOnClickListener {
            when (type) {
                1 -> {
                    timeSelect.selectTime(it, "yyyy-MM-dd")
                }

                2 -> {
                    bottomSheetDialog?.show()
                }

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

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

    private var bottomSheetDialog: BottomSheetDialog? = null

    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)
                val wheelView = view.findViewById<WheelView>(R.id.wheelView)
                wheelView.setCyclic(false)
                wheelView.adapter = ArrayWheelAdapter(buildWeekLower26())
                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 {
                    // 点击确定按钮的操作
                    val item = wheelView.adapter.getItem(wheelView.currentItem)
                    binding.tvShowDate.text = item.toString()
                    weekDate = binding.tvShowDate.text.toString()
                    mViewModel.getXyaData(
                        type,
                        binding.tvShowDate.text.toString(),
                        id,
                        isDemonstrate
                    )
                    // 点击确定按钮的操作
                    dialog.dismiss()
                }
            }
        }
    }

    fun buildWeekLower26(): MutableList<String> {
        val startDate = Calendar.getInstance()
        startDate.firstDayOfWeek = Calendar.MONDAY
        startDate.add(Calendar.YEAR, -1)
        val endDate = Calendar.getInstance()

        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
    }

    val timeSelect by lazy {
        TimeSelect(requireContext()) {
            type = 1
            dayDate = binding.tvShowDate.text.toString()
            mViewModel.getXyaData(type, binding.tvShowDate.text.toString(), id, isDemonstrate)
        }
    }

    val timeMonthSelect by lazy {
        TimeSelect(requireContext()) {
            type = 3
            mouthDate = binding.tvShowDate.text.toString()
            mViewModel.getXyaData(type, binding.tvShowDate.text.toString(), id, isDemonstrate)
//            mViewModel.getXlData(type, binding.tvShowDate.text.toString(), id)

        }
    }
    val timeYearSelect by lazy {
        TimeSelect(requireContext()) {
            type = 4
            yearDate = binding.tvShowDate.text.toString()
            mViewModel.getXyaData(type, binding.tvShowDate.text.toString(), id, isDemonstrate)
        }
    }

}