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.os.Build
import android.text.SpannableString
import android.text.Spanned
import android.text.TextUtils
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.text.style.UnderlineSpan
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 com.bigkoo.pickerview.adapter.ArrayWheelAdapter
import com.blankj.utilcode.util.TimeUtils
import com.contrarywind.view.WheelView
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.ILineDataSet
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.tamsiree.rxkit.RxConstTool
import com.tamsiree.rxkit.RxTimeTool
import com.xty.base.fragment.BaseVmFrag
import com.xty.base.utils.OrganStatusCalcUtil
import com.xty.common.LogUtils
import com.xty.common.TimeSelect
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.event.XTangOpenEvent
import com.xty.common.event.XTangUpdateEvent
import com.xty.common.event.XTangUploadEvent
import com.xty.common.setImage
import com.xty.common.util.CommonToastUtils
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.databinding.FragXtangBinding
import com.zj365.health.vm.XTangVm
import com.zj365.health.weight.HealthDialog
import com.zj365.health.weight.IMarkView
import com.zj365.health.weight.XuetangDialog
import com.xty.network.model.XTangInfoBean
import com.xty.network.model.XtNewBean
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.lang.Float.max
import java.lang.Float.min
import java.text.SimpleDateFormat
import java.util.*

/**
 * 血糖
 */
class XueTangFrag : BaseVmFrag<XTangVm>() {

    val binding by lazy { FragXtangBinding.inflate(layoutInflater) }
    override fun setLayout(): View = binding.root
    override fun setViewModel() = XTangVm()

    var isDemonstrate: Boolean = false

    private val weekStr by lazy { resources.getStringArray(R.array.week_day) }

    val fomartStr by lazy { arrayOf("HH:mm", "MM-dd", "MM-dd", "yy-MM") }
    var type = 1//type 日：0 周：1 月：2 年：3

    //    val timeSelect by lazy {
//        TimeSelect(requireContext()) {
//            type = 0
//            //根据时间来请求数据
//            requestDetail()
//        }
//    }
    var lineValue = arrayListOf<Entry>()  //曲线数据
    var barValue = arrayListOf<BarEntry>()  //柱状数据
    var id = ""


    private var isMine = false//是否是本人
    private var mModel = 0 //0 未开通 1：建模中 2：建模完成
    private var xtInfo: XTangInfoBean? = null  //血糖信息
    private var sugarInfo: XTangInfoBean? = null //血红蛋白信息
    private var xuetang: XtNewBean.Value? = null
    private var xuetangLineInfo: XtNewBean? = null
    private val icons = arrayOf(
        R.mipmap.shuzhuangtu,
        R.mipmap.ic_shuzhuangtu_yixuan,
        R.mipmap.ic_zhexiant,
        R.mipmap.zhexiant_yixuan
    )
    var tip = ""
    val tipDialog by lazy {
        HealthDialog(requireContext(), true, tip) {
        }
    }
    private var sugarDialog: XuetangDialog? = null
    private var expireTimeStr: String = ""

    override fun initData() {
        super.initData()
        id = arguments?.getString("id").toString()
        if (id.isNullOrEmpty() || id == CommonUtils.getMyUserInfo()?.id) {//如果是自己
            isMine = true

            CommonUtils.getMyUserInfo()?.let {
                id = it.id
            }
        }
    }

    override fun initView() {
        super.initView()
        initTab()
        initTimeSelect()
        binding.mLineChart.setNoDataText(getString(R.string.line_chart_not_data))
        binding.mLineChart.setNoDataTextColor(
            ContextCompat.getColor(
                requireContext(),
                R.color.col_455
            )
        )
        binding.compareTv.setOnClickListener {
            if (isDemonstrate) {
                (requireActivity() as HealthMainAct).dialogBind.show()
                return@setOnClickListener
            }
            bundle.clear()
            bundle.putString("id", id)
            bundle.putString("type", "7")// 7血糖
            RouteManager.goAct(ARouterUrl.COMPARE_DATA_ACT, bundle)
        }
        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.mGroup.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.mDay -> {
                    binding.mTvTime.visibility = View.VISIBLE
                    type = 0
                    var selTime = binding.mTvTime.text.toString()
                    val date2String = RxTimeTool.date2String(Date(), SimpleDateFormat("yyyy-MM-dd"))
                    requestDetail()
                }

                R.id.mWeek -> {
                    binding.mTvTime.visibility = View.GONE
                    type = 1
                    requestDetail()
                }

                R.id.mMonth -> {
                    binding.mTvTime.visibility = View.GONE
                    type = 2
                    requestDetail()
                }

                R.id.mYear -> {
                    binding.mTvTime.visibility = View.GONE
                    type = 3
                    requestDetail()
                }
            }

            //此处需要根据选择来请求数据
            requestInfo()
        }


        binding.mTvTime.text = RxTimeTool.getCurTimeString(SimpleDateFormat("yyyy-MM-dd"))
        binding.mTvTime.setOnClickListener {
            timeSelect.selectTime(it)
        }

        binding.mTvDynamicBloodSugar.setOnClickListener(onClickListener)
        binding.mTvGlycosylated.setOnClickListener(onClickListener)
        binding.mTvOper.setOnClickListener(onClickListener)
        binding.tvOpen.setOnClickListener(onClickListener)
        binding.tvRenew.setOnClickListener(onClickListener)
        binding.mTip.setOnClickListener(onClickListener)
        binding.tvModelingExplain.setOnClickListener(onClickListener)

        binding.mTvDynamicBloodSugar.isSelected = true//默认动态血糖为已选择

        val content = SpannableString("立即续费")
        val underlineSpan = UnderlineSpan()
        content.setSpan(
            underlineSpan,
            0,
            content.length,
            Spanned.SPAN_INCLUSIVE_INCLUSIVE
        )
        binding.tvRenew.text = content

        init()

        binding.tvTips.text = "了解血糖：\n血糖是指血液中葡萄糖的含量，属于糖代谢检查，可用于筛查、诊断及监测糖尿病、低血糖症等多种糖代谢异常相关疾病，反映了机体对葡萄糖的吸收、代谢是否正常。\n\n" +
                "无创血糖趋势算法原理：光学检测原理+核心算法\n" +
                "监测原理采用光学检测技术进行非侵入式的血糖监测。该技术利用 LED 发射器发出可见光或红外线光束，经过皮肤组织后被光电传感器接收。由于不同物质对光线吸收的特性不同，因此可以通过检测光线在皮肤组织中的吸收情况来判断血液中的成分含量；搭配核心算法，能有效算出用户血糖数值。\n" +
                "\n\n\n" +
                "测量结果仅供参考，不作为医疗诊断依据。"
    }

    private var onClickListener = View.OnClickListener {
        when (it.id) {
            //动态血糖
            R.id.mTvDynamicBloodSugar -> {
                if (isDemonstrate) {
                    (requireActivity() as HealthMainAct).dialogBind.show()
                    return@OnClickListener
                }
                binding.mTvDynamicBloodSugar.isSelected = true
                binding.mTvGlycosylated.isSelected = false
                requestInfo()
                requestDetail()
            }
            //糖化血红蛋白
            R.id.mTvGlycosylated -> {
//                binding.mTvGlycosylated.isSelected = true
//                binding.mTvDynamicBloodSugar.isSelected = false
//                requestInfo()
//                requestDetail()
                if (isDemonstrate) {
                    (requireActivity() as HealthMainAct).dialogBind.show()
                    return@OnClickListener
                }
                mViewModel.getBloodSugarInfo(id)

            }
            //首次开通
            R.id.tvOpen -> {
                bundle.clear()
//                        bundle.putBoolean("isOpen", false)
//                        bundle.putString("id", id)
//                        RouteManager.goAct(ARouterUrl.XT_OPEN, bundle)
                bundle.putString("expireTime", expireTimeStr)
                bundle.putString("userId", id)
                bundle.putInt("pageType", 1)
                RouteManager.goAct(ARouterUrl.OPEN_OR_RENEW, bundle)
            }
            //操作按钮
            R.id.mTvOper -> {
                if (isDemonstrate) {
                    (requireActivity() as HealthMainAct).dialogBind.show()
                    return@OnClickListener
                }
                when (binding.mTvOper.text.toString()) {
                    "血糖校准" -> {
                        if (mModel == 0 && !TextUtils.isEmpty(expireTimeStr)) {
                            CommonToastUtils.showToast("血糖服务已过期，请续费后再校准数据 ")
                            return@OnClickListener
                        }
                        bundle.clear()
                        bundle.putString("id", id)
                        bundle.putBoolean("isCalibration", true)
                        RouteManager.goAct(ARouterUrl.XT_UPLOAD, bundle)
                    }
                }
            }
            //续费按钮
            R.id.tvRenew -> {
//                bundle.clear()
//                bundle.putBoolean("isOpen", true)
//                bundle.putString("id", id)
//                RouteManager.goAct(ARouterUrl.XT_OPEN, bundle)
                bundle.clear()
                bundle.putString("expireTime", expireTimeStr)
                bundle.putString("userId", id)
                bundle.putInt("pageType", 1)
                RouteManager.goAct(ARouterUrl.OPEN_OR_RENEW, bundle)
            }
            //重点提示
            R.id.mTip -> {
//                var webUrl = "file:///android_asset/中健三六五无创血糖趋势监测功能说明.html"
//                bundle.clear()
//                bundle.putString("title", "中健三六五无创血糖监测")
//                bundle.putString("url", webUrl)
//                RouteManager.goAct(ARouterUrl.WEB_ACT, bundle)
                tip = "中健三六五无创血糖技术是通过人工智能算法，建立个人血糖模型，计算得出的用户1个小时内血糖平均值。" +
                        "更多的是反应用户的整体血糖变化趋势，切勿当血糖仪使用。血糖异常用户在建模完成后请第一时间完成血糖模型校准。"
                tipDialog.setHintContent(tip)
                tipDialog.show()
            }
            //建模中才可点击
            R.id.tvModelingExplain -> {
                tip = "血糖建模出值重要提示:\n" +
                        "1、建模期间，累计有效佩戴满72小时；\n" +
                        "2、最少确保一天（0-24点）有完整佩戴数据；\n" +
                        "3、高血糖用户在建模完成之后须做个人血糖模型校准；\n" +
                        "4、APP所出血糖值为前一个小时血糖平均值。"
                tipDialog.setContent(tip)
                tipDialog.show()
            }
        }
    }


    private fun init() {
        isDemonstrate = (requireActivity() as HealthMainAct).isDemonstrate
        if (isDemonstrate) {
            binding.tvXinLv.text = "6.2"
            binding.tvTestTime.text = RxTimeTool.getCurTimeString(
                SimpleDateFormat("HH:mm")
            )
            binding.mTvDynamicBloodSugar.isSelected = true
        } else {
            requestInfo()
        }
        requestDetail()
    }

    /**
     * 请求头部信息
     *
     * @see 注意，来回切换不会重复请求，动态血糖和糖化血红蛋白只会请求一次
     */
    private fun requestInfo() {
        if (!isDemonstrate) {
            if (isBloodSugar()) {//动态血糖
                mViewModel.getXtInfo(id)
//            if (xtInfo == null) {
//                mViewModel.getXtInfo(id)
//            } else {//直接更新头部内容
//                updateHeaderInfo()
//            }
            } else {//糖化血红蛋白
                mViewModel.getBloodSugarInfo(id)
//            if (sugarInfo == null) {
//                mViewModel.getBloodSugarInfo(id)
//            } else {//直接更新头部内容
//                updateHeaderInfo()
//            }
            }
        }
    }

    /**
     * 请求详细信息
     */
    private fun requestDetail() {
        var time = binding.tvShowDate.text.toString()
        mViewModel.getXtInfoDetail(id, type, time, isDemonstrate)

//        if (isBloodSugar()) {//动态血糖
//        } else {//糖化血红蛋白
//            mViewModel.getBloodSugarDetail(id, type, time)
//        }
    }

    /**
     * 是否为动态血糖
     */
    private fun isBloodSugar(): Boolean {
        if (null == binding || null == binding.mTvDynamicBloodSugar) return false
        return binding.mTvDynamicBloodSugar.isSelected
    }

    override fun observer() {
        mViewModel.xtInfo.observe(this) {
            xtInfo = it.data
            mModel = xtInfo!!.model
            updateHeaderInfo()
            if (null != xtInfo) {
                initChart(xuetangLineInfo?.model, xtInfo!!.min, xtInfo!!.max)
            }
        }

        mViewModel.bloodSugarInfo.observe(this) { body ->
            sugarInfo = body.data
            sugarInfo?.let {
                val code = it.code
                if (code == 2) {
                    it.hemoglobin?.let { result ->
                        sugarDialog = XuetangDialog(requireContext(), result)
                        sugarDialog!!.show()

                    }

                } else if (code == 1) {
                    CommonToastUtils.showToast("未满90天，暂未出具糖化血红蛋白信息！")
                } else {
                    CommonToastUtils.showToast("未开通")
                }
//                updateHeaderInfo()
            }
        }

        mViewModel.xtInfoDetail.observe(this) {
            val daysModelList: MutableList<XtNewBean.Model> = it.data.model
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                when (type) {
                    1 -> {//日
                        it.data.model = it.data.mapDataToTimeNodes(it.data.model)
                    }

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

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

                    4 -> {//年
                        it.data.model = it.data.fillMissingData(it.data.model)
                    }
                }
            }
            xuetang = it.data.value
            xuetangLineInfo = it.data
            setLine(daysModelList, it.data)
            updateHeaderInfo()
        }

//        mViewModel.bloodSugarDetail.observe(this) {
//            setLine(it.data)
//        }
    }

    private fun updateHeaderInfo() {
        val isBloodSugar = isBloodSugar()
        if (isBloodSugar) {
            if (xuetang != null) {
                binding.mAvg.setValue(String.format("%.1f", xuetang!!.sugarAvg))
                binding.mMax.setValue(String.format("%.1f", xuetang!!.sugarMax))
                binding.mLow.setValue(String.format("%.1f", xuetang!!.sugarMin))
                binding.mAvg.visibility = View.VISIBLE
                binding.mMax.visibility = View.VISIBLE
                binding.mLow.visibility = View.VISIBLE
                binding.mOrganView.root.visibility = View.VISIBLE
            }
        } else {
            binding.mAvg.visibility = View.GONE
            binding.mMax.visibility = View.GONE
            binding.mLow.visibility = View.GONE
            binding.mOrganView.root.visibility = View.GONE
        }

        var infoBean = (if (isBloodSugar) xtInfo else sugarInfo) ?: return

        expireTimeStr = infoBean.expireTime
        updateBloodsugarStatus(infoBean.model, expireTimeStr)

        if (!infoBean.introUrl.isNullOrEmpty()) {
            binding.ivXtangIntro.setImage(requireContext(), infoBean.introUrl)
        }

    }

    //设置数据
    private fun setLine(daysModelList: MutableList<XtNewBean.Model>, data: XtNewBean) {
        if (data == null) {
            return
        }
        lineValue.clear()
        barValue.clear()
        var rever = (data.model.indices).reversed()

        if (selectDay()) {
            normalTime = 0
            highTime = 0
            lowTime = 0
        }
        for (t in daysModelList.indices) {
            if (selectDay()) {//如果是当天才操作
                getOrganStatu(daysModelList[daysModelList.size - t - 1].xtDate)
            }
        }
        for (i in rever) {
            //        var index = rever.indexOf(i)
            val bean = data.model[data.model.size - 1 - i]
//            var times = bean.time!!.toLong() * 1000
//            var strTime =
//                RxTimeTool.milliseconds2String(times, SimpleDateFormat(fomartStr[type - 1]))
//            LogUtils.d("时间:${strTime}")

            LogUtils.d("yansu:${data.model.size - 1 - i}")
            lineValue.add(
                Entry(
                    (data.model.size - 1 - i).toFloat(),
                    bean.xtDate,
                    tipTime(data.model[data.model.size - 1 - i])
                )
            )
            barValue.add(
                BarEntry(
                    (data.model.size - 1 - i).toFloat(),
                    bean.xtDate,
                    tipTime(data.model[data.model.size - 1 - i])
                )
            )
        }

        if (selectDay()) {
            setOrganStatu()
        }

        if (null != xuetang) {
            initChart(data.model, xuetang!!.sugarMin, xuetang!!.sugarMax)
        } else {
            initChart(mutableListOf(), 0f, 40f)
        }
    }

    private fun tipTime(
        bean: XtNewBean.Model
    ): String {
        when (type) {
            1, 3 -> {
                if (bean.xtDate == 0f) {
                    bean.xtDate = Float.NaN
                }
                return bean.time
            }

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

                return "$month-$day"
            }

            else -> {
                return "${bean.time}月"
            }
        }
    }

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

    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
    }

    private var normalTime: Int = 0
    private var highTime: Int = 0
    private var lowTime: Int = 0
    private fun getOrganStatu(statu: Float) {
        when (OrganStatusCalcUtil.bloodSugarStatu(statu)) {//0:正常 1:低血糖 2:高血糖
            1 ->
                lowTime++

            2 ->
                highTime++

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

    /**
     * 更新血糖状态
     */
    @SuppressLint("SetTextI18n", "SimpleDateFormat")
    private fun updateBloodsugarStatus(model: Int, expireTime: String?) {
        var topText = if (isBloodSugar()) "当前血糖" else "当前糖化值"
        when (model) {
            //0 未开通 1：建模中 2：建模完成
            0 -> {
//                binding.mFull.invalidate()
                if (TextUtils.isEmpty(expireTime)) {
                    binding.compareTv.visibility = View.GONE
                    binding.mTvOper.visibility = View.GONE
//                binding.mFull.top_txt = topText
                    binding.tvXinLv.text = "未开通"
                    binding.tvAfter.text = ""
                    binding.mTvExpireTime.text = ""

                    binding.tvRenew.visibility = View.GONE
                    binding.tvOpen.visibility = View.VISIBLE
                } else {
                    binding.tvOpen.visibility = View.GONE
                    binding.mTvExpireTime.text = "到期时间：$expireTime"
                    binding.tvRenew.visibility = View.VISIBLE
                    binding.compareTv.visibility = View.VISIBLE
                    if (isMine) {
                        binding.mTvOper.visibility = View.VISIBLE
                        binding.mTvOper.text = "血糖校准"
                    }
                    if (xtInfo?.bloodsugar != 0f) {
                        binding.tvXinLv.text = if (null == xtInfo) {
                            "-"
                        } else {
                            xtInfo?.bloodsugar.toString()
                        }
                    } else {
                        binding.tvXinLv.text = "--"
                    }
                }
                binding.tvTestTime.text = RxTimeTool.getCurrentDateTime("HH:mm")
                binding.tvModelingExplain.visibility = View.GONE
            }

            1 -> {
                binding.tvRenew.visibility = View.GONE
                binding.tvOpen.visibility = View.GONE
                binding.mTvOper.visibility = View.GONE

                if (isBloodSugar()) {
                    binding.mTvOper.text = "建模中"
                    binding.mTvExpireTime.text = "到期时间：$expireTime"
                } else {
                    binding.mTvExpireTime.text = "监测周期：$expireTime"
                }
                val expireDay = RxTimeTool.getIntervalByNow(
                    expireTime,
                    RxConstTool.TimeUnit.DAY,
                    SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                ) + 1
                LogUtils.d("过期时间还剩：$expireDay 天；有效期截至：$expireTime")
                if (expireDay > 30) {
                    binding.tvRenew.visibility = View.GONE
                } else {
                    binding.tvRenew.visibility = View.VISIBLE
                }

//                binding.mFull.top_txt = topText
                binding.tvXinLv.text = "建模中"
                binding.tvModelingExplain.visibility = View.VISIBLE
                binding.tvAfter.text = ""
//                binding.mTvExpireTime.text = ""
                binding.tvTestTime.text = RxTimeTool.getCurrentDateTime("HH:mm")
            }

            2 -> {
                val centerText: String
                val unit: String
                val bottomText: String
                if (isBloodSugar()) {
                    binding.mTvOper.text = "血糖校准"
                    binding.mTvOper.visibility = if (isMine) View.VISIBLE else View.GONE
                    centerText = if (null == xtInfo) "-" else xtInfo?.bloodsugar.toString()
                    unit = "mmol/L"
                    bottomText = if (null == xtInfo) "-" else RxTimeTool.simpleDateFormat(
                        "HH:mm",
                        RxTimeTool.string2Date("yyyy-MM-dd HH:mm:ss", xtInfo?.time)
                    )
                    binding.mTvExpireTime.text = "到期时间：$expireTime"
                    val expireDay = RxTimeTool.getIntervalByNow(
                        expireTime,
                        RxConstTool.TimeUnit.DAY,
                        SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                    ) + 1
                    LogUtils.d("过期时间还剩：$expireDay 天；有效期截至：$expireTime")
                    if (expireDay > 30) {
                        binding.tvRenew.visibility = View.GONE
                    } else {
                        binding.tvRenew.visibility = View.VISIBLE
                    }
                } else {
                    binding.mTvOper.visibility = View.GONE
                    centerText =
                        if (null == sugarInfo) "-" else sugarInfo?.bloodsugar.toString()
                    unit = "%"
                    bottomText = if (null == sugarInfo) "-" else RxTimeTool.simpleDateFormat(
                        "HH:mm",
                        RxTimeTool.string2Date("yyyy-MM-dd HH:mm:ss", sugarInfo?.time)
                    )
                    binding.mTvExpireTime.text = "监测周期：$expireTime"
                    binding.tvRenew.visibility = View.GONE
                }

                if (xtInfo?.bloodsugar != 0f) {
                    binding.tvXinLv.text = centerText
                } else {
                    binding.tvXinLv.text = "--"
                }
                binding.tvAfter.text = "mmol/L"
//                binding.mTvExpireTime.text = ""
                binding.tvTestTime.text = bottomText
//                binding.mFull.center_txt = centerText
                binding.tvOpen.visibility = View.GONE
                binding.tvModelingExplain.visibility = View.GONE
            }
        }
    }

    private var yValueFormatter = mutableListOf("0", "8", "16", "24", "32")

    private fun initChart(list: MutableList<XtNewBean.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.isDragEnabled = false
            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

            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.axisMaxLabels = 8
//            if (type == 3) {
//                x.setLabelCount(8, true)
//            }
            x.position = XAxis.XAxisPosition.BOTTOM
            x.setValueFormatter { value, axis ->
                var index = value.toInt()
                LogUtils.d("x轴:$value")
                LogUtils.d("x轴Maximum:${axis.mAxisMaximum};;;lineValueSize${lineValue.size}")
                if (index == lineValue.size - 1) {
                    "${lineValue[lineValue.size - 1].data}"
                } else if (index < 0 || index >= lineValue.size) {
                    ""
                } else {
                    "${lineValue[value.toInt()].data}"
                }

            }

            //y轴
            val y = it.axisLeft
//            y.axisMaximum = max//最大血糖值
//            y.axisMinimum = min
//            y.axisMaxLabels = 6
            val minValue = if (min - 0.4f >= 0f) {
                min - 0.4f
            } else {
                min
            }
            val maxValue = if (max + 1f <= 8.2f) {
                max + 1f
            } else if (max + 0.3f <= 8.2f) {
                max + 0.3f
            } else {
                max
            }
            y.setLabelCountAndMaxMinValue(
                6,
                false,
                minValue,
                maxValue,
                minValue,
                Float.MAX_VALUE
            )
            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)
//            y.setValueFormatter { value, axis ->
//                var index = value.toInt() / 10
//                LogUtils.d("y轴:$value")
//                if (index < 0 || index >= yValueFormatter.size) {
//                    ""
//                } else {
//                    "${yValueFormatter[index]}"
//                }
//            }


            var markerView = IMarkView(
                requireContext(), R.layout.mark_view, "mmol/L",
                IMarkView.MarkPage.XTang
            )
            it.marker = markerView
            markerView.chartView = it
            it.legend.isEnabled = false
            // 设置x轴和左边Y轴的相关属性
            // 禁用右边Y轴
            // 禁止绘制右边Y轴的标签
            it.axisRight.isEnabled = false
            it.axisRight.setDrawLabels(false)

            //   it.animateXY(2000, 2000)  //设置xy轴进入的动画
            it.invalidate()
        }
        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, index).toFloat(),
                    model.xtDate,
                    lineValue[convertTimeToIndex(model.time, index)].data
                )
            }
            return@mapNotNull setData(entries)
        }
        if (lineValue.isNotEmpty()) {
            barsetsNew.addAll(dataSets)
            val bard = LineData(barsetsNew)
            binding.mLineChart.data = bard
            binding.mLineChart.invalidate()
            binding.mLineChart.moveViewToX(lineValue[lineValue.size - 1].x)
        }

        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 -> {
                        3f
                    }

                    3 -> {
                        3.5f
                    }

                    4 -> {
                        1.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.axisMinimum = -0.5f
            x.axisMaximum = (barValue.size - 0.5).toFloat()
//                x.labelCount = 6
            x.isEnabled = true
            x.setDrawGridLines(false)  //不绘制y
            x.setDrawAxisLine(false)
            x.xOffset = 0f
            x.position = XAxis.XAxisPosition.BOTTOM
            x.setValueFormatter { value, axis ->
                var index = value.toInt()
                LogUtils.d("x轴:$value")
                LogUtils.d("x轴Maximum:${axis.mAxisMaximum};;;lineValueSize${lineValue.size}")
                if (index == lineValue.size - 1) {
                    "${lineValue[lineValue.size - 1].data}"
                } else if (index < 0 || index >= lineValue.size) {
                    ""
                } else {
                    "${lineValue[value.toInt()].data}"
                }
            }
            val y = it.axisLeft
            val minValue = if (min - 0.4f >= 0f) {
                min - 0.4f
            } else {
                min
            }
            val maxValue = if (max + 1f <= 8.2f) {
                max + 1f
            } else if (max + 0.3f <= 8.2f) {
                max + 0.3f
            } else {
                max
            }
            y.setLabelCountAndMaxMinValue(
                6,
                false,
                minValue,
                maxValue,
                minValue,
                Float.MAX_VALUE
            )
            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, "mmol/L",
                IMarkView.MarkPage.XTang
            )
            it.marker = markerView
            markerView.chartView = it
            it.axisRight.isEnabled = false
            it.legend.isEnabled = false
            //   it.setVisibleXRangeMaximum(10f)
            //   it.animateXY(2000, 2000)  //设置xy轴进入的动画

        }

        if (barValue.isEmpty()) {
            return
        }
        binding.mBarChart.moveViewToX(barValue[barValue.size - 1].x)

        val dataBarSets = segments.mapNotNull { segment ->
            if (segment.isEmpty()) return@mapNotNull null
            val entries = segment.mapIndexed { index, model ->
                BarEntry(
                    convertTimeToIndex(model.time, index).toFloat(),
                    model.xtDate,
                    barValue[convertTimeToIndex(model.time, index)].data
                )
            }
            return@mapNotNull setBarData(entries)
        }

        val bard = BarData(dataBarSets)
        bard.barWidth = calculateBarWidth(bard.dataSetCount)
        binding.mBarChart.data = bard
        binding.mBarChart.invalidate()
    }

    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 2")
            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
            val data = BarData(set1)
            data.setValueTextSize(9f)
            data.setDrawValues(false)
        }
        return set1
    }

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

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

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

    fun splitDataIntoSegments(dataList: MutableList<XtNewBean.Model>?): MutableList<MutableList<XtNewBean.Model>> {
        if (dataList == null) {
            return mutableListOf()
        }
        val segments = mutableListOf<MutableList<XtNewBean.Model>>()
        var currentSegment = mutableListOf<XtNewBean.Model>()

        for (model in dataList) {
            if (model.xtDate.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<XtNewBean.Model>>): MutableList<MutableList<XtNewBean.Model>> {
        when (type) {
            1 -> {
                if (segmentsCompare[0][0].time != "00:00") {
                    val d = mutableListOf<XtNewBean.Model>()
                    val b = XtNewBean.Model(0f, "00:00")
                    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 != "23:00"
                ) {
                    val d = mutableListOf<XtNewBean.Model>()
                    val b = XtNewBean.Model(0f, "23:00")
                    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<XtNewBean.Model>()
                    val b = XtNewBean.Model(0f, start)
                    d.add(b)
                    segmentsCompare.add(d)
                }
                if (segmentsCompare[segmentsCompare.size - 1][segmentsCompare[segmentsCompare.size - 1].size - 1].time != end) {
                    val d = mutableListOf<XtNewBean.Model>()
                    val b = XtNewBean.Model(0f, end)
                    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<XtNewBean.Model>()
                    val b = XtNewBean.Model(0f, "$month-01")
                    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<XtNewBean.Model>()
                    val b = XtNewBean.Model(0f, "$month-$daysInMonth")
                    d.add(b)
                    segmentsCompare.add(d)
                }
            }

            4 -> {
                if (segmentsCompare[0][0].time != "01") {
                    val d = mutableListOf<XtNewBean.Model>()
                    val b = XtNewBean.Model(0f, "01")
                    d.add(b)
                    segmentsCompare.add(d)
                }
                if (segmentsCompare[segmentsCompare.size - 1][segmentsCompare[segmentsCompare.size - 1].size - 1].time != "12") {
                    val d = mutableListOf<XtNewBean.Model>()
                    val b = XtNewBean.Model(0f, "12")
                    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 -> {
                // 将时间格式转换为小时和分钟
                val parts = time.split(":")
                val hours = parts[0].toInt()
                val minutes = parts[1].toInt()

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

                // 计算对应的索引值
                index = totalMinutes / 60
            }

            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
    }

    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, "DataSet 1")
            set1.mode = LineDataSet.Mode.LINEAR
            set1.cubicIntensity = 0.2f
            set1.setDrawFilled(true)
            set1.lineWidth = 2.5f
            set1.circleRadius = 2f
            // 分段后，数据若有一个点需要显示
            set1.setDrawCircles(values?.size == 1)
            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_41c) //xian de yanse
            val drawable = ContextCompat.getDrawable(requireContext(), R.drawable.shape_curve)
            set1.fillDrawable = drawable
            //   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
            //binding.mLineChart!!.data = data
        }

        return set1
    }

    override fun onDestroy() {
        var infoBean = (if (isBloodSugar()) xtInfo else sugarInfo)
        if (null != infoBean && isBloodSugar()) {
            EventBus.getDefault().post(infoBean?.let { XTangUpdateEvent(it) })
        }
        super.onDestroy()
    }

    /**
     * 血糖开通/续费成功
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun xtOpenSuccess(event: XTangOpenEvent) {
        mModel = event.model
        updateBloodsugarStatus(event.model, event.expireTime)
    }

    /**
     * 血糖开通/续费成功
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun xtUploadSuccess(event: XTangUploadEvent) {
        mViewModel.getXtInfo(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: java.util.ArrayList<CustomTabEntity> = java.util.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
                    }
                }
                requestDetail()
            }

            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) {
                0, 1 -> {
                    timeSelect.selectTime(it, "yyyy-MM-dd")
                }

                2 -> {
                    bottomSheetDialog?.show()
                }

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

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

                2 -> {
                    bottomSheetDialog?.show()
                }

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

                4 -> {
                    timeYearSelect.selectTimeWithYear(binding.tvShowDate, "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()
                    requestDetail()
                    // 点击确定按钮的操作
                    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> = java.util.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()
            requestDetail()
        }
    }

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

        }
    }
    val timeYearSelect by lazy {
        TimeSelect(requireContext()) {
            type = 4
            yearDate = binding.tvShowDate.text.toString()
            requestDetail()
        }
    }

}