package com.zj365.health.fragment

import android.graphics.Color
import android.graphics.Typeface
import android.os.Build
import android.text.Spannable
import android.text.SpannableString
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.PieEntry
import com.github.mikephil.charting.manager.MPieChartManager
import com.tamsiree.rxkit.RxTimeTool
import com.xty.base.fragment.BaseVmFrag
import com.xty.common.FileUtils
import com.xty.common.TimeUtils
import com.xty.common.audioUtils.RecordAudio
import com.xty.common.util.SpannableUtils
import com.xty.common.weight.CenterImageSpan
import com.zj365.health.R
import com.zj365.health.act.HealthMainAct
import com.zj365.health.adapter.SleepAdapter
import com.zj365.health.adapter.SleepIntroAdapter
import com.zj365.health.databinding.FragSleepDayStaticsBinding
import com.zj365.health.databinding.SleepScaleInfoBinding
import com.zj365.health.model.SleepIntroBean
import com.zj365.health.vm.SleepVm
import com.zj365.health.weight.HealthDialog
import com.xty.network.model.SleepBean
import java.io.File
import java.io.FileOutputStream
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.*

/**
 * 睡眠日子筛选
 */
class SleepStaticDayFrag : BaseVmFrag<SleepVm>() {
    var isDemonstrate: Boolean = false
    var type = 2
    val binding by lazy { FragSleepDayStaticsBinding.inflate(layoutInflater) }
    private val scaleInfoBinding by lazy { SleepScaleInfoBinding.bind(binding.root) }
    private val pieChart by lazy { MPieChartManager(scaleInfoBinding.mPieChart) }
    override fun setLayout(): View = binding.root
    override fun setViewModel() = SleepVm()

    var lineValue = arrayListOf<Entry>()  //曲线数据
    val fomartStr by lazy { arrayOf("MM-dd", "yyyy-MM") }
    val weekStr by lazy { resources.getStringArray(R.array.week_day) }
    private val mIntroAdapter by lazy { SleepIntroAdapter() }
    val mAdapter by lazy { SleepAdapter() }

    var tip =
        "睡眠判断的依据是相关体征数据的特征比对。部分用户新陈代谢较慢，脑供血不足时，在静坐平躺状态下，血压心率下降，虽然没有睡着，但是体征符合正常人睡眠状态，这个时候系统可能会误判为睡眠。同理如身体患有基础慢病，如炎症、甲亢等疾病，新陈代谢较快，即使处于睡眠过程中，系统可能会误判用户此时为浅睡或清醒。如出现app内显示睡眠时间与实际不符，请注意调整身体状态"
    val tipDialog by lazy {
        HealthDialog(requireContext(), true, tip) {
        }
    }


    var id :String?= ""

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

    val audioUtils by lazy { RecordAudio() }
    var isAudioPlay = false

    @RequiresApi(Build.VERSION_CODES.O)
    override fun initView() {
        isDemonstrate = (requireActivity() as HealthMainAct).isDemonstrate
        super.initView()
//        mViewModel.getSetting(Const.SLEEP_SETTING)
        getData(TimeUtils.getCurrentTime(), isDemonstrate)


        val assets = context?.assets?.open("forest.mp3")

        //保存到手机的路劲
        val appDir = File(context?.let { FileUtils.getCacheFile(it) } + "/asset")
        if (!appDir.exists()) {
            appDir.mkdir()
        }
        val file = File(appDir, "forest.mp3")
        val fos = FileOutputStream(file)
        var bytes = ByteArray(1024)
        var byteCount: Int = assets!!.read(bytes)
        while (byteCount !== -1) {
            fos.write(bytes, 0, byteCount)
            byteCount = assets.read(bytes)
        }
        fos.flush()
        assets.close()
        fos.close()

        setScaleInfo()
    }



    fun getData(date: String, isDemonstrate: Boolean) {
        mViewModel.getSleepLastTata(id,date,isDemonstrate)
    }

    /**
     * 评分信息
     */
    private fun updateScoreInfo(score: Int) {
        binding.mScoreInfo.let {
            //分数已经评星
            it.mScore.apply {
                text = ""
                var text = "$score 分"
                append(setStrSpan(text, 28, getColor(R.color.col_02c), Typeface.BOLD, 0, text.length - 1))
                append("\t")
                var selectStarImage = context.getDrawable(R.mipmap.ic_sel_sleep)
                selectStarImage?.setBounds(
                    0,
                    0,
                    selectStarImage.minimumWidth,
                    selectStarImage.minimumHeight
                )

                var unSelectStarImage = context.getDrawable(R.mipmap.ic_unsel_sleep)
                unSelectStarImage?.setBounds(
                    0,
                    0,
                    unSelectStarImage.minimumWidth,
                    unSelectStarImage.minimumHeight
                )

                for (i in 1..5) {
                    val spanStr = SpannableString("custom$i")
                    var span =
                        (if (calcStarLevel(score) >= i) selectStarImage else unSelectStarImage)?.let { starDrawable ->
                            CenterImageSpan(starDrawable)
                        }
                    spanStr.setSpan(span, 0, spanStr.length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
                    append("\t")
                    append(spanStr)
                }
            }

            //排行
            it.mRank.apply {
                var percent = "${score + 1}%"//临时值，目前没有这个排名 app写的分数+1
                var content = String.format(getString(R.string.sleep_rank), percent)
                text =
                    setStrSpan(content, 13, getColor(R.color.col_02c), Typeface.BOLD, content.length - 3 - percent.length, content.length - 3)
            }
        }
    }

    /**
     * 计算评分星级
     */
    private fun calcStarLevel(score: Int): Int {
        return when (score) {
            0 -> {
                0
            }
            in 1..39 -> {
                1
            }
            in 40..59 -> {
                2
            }
            in 60..79 -> {
                3
            }
            in 80..94 -> {
                4
            }
            else -> {
                5
            }
        }
    }

    /**
     * 更新睡眠比例信息
     */
    private fun setScaleInfo() {
        initPieChartView()
        initSleepIntro()
    }


    /**
     * 初始化图表控件
     */
    private fun initPieChartView() {
        // 是否有中心圆
        pieChart.initCenter(true, 80f, 61f, getColor(R.color.white), 110)
        //中心圆中是否有字
        pieChart.setCenterText(true, "睡眠\n比例", getColor(R.color.col_828), 18f)
        // 是否可以拖拽旋转
        pieChart.setRotation(isRation = false, isPercent = true)
        // 是否有描述
        pieChart.setDescription(false)

        // 获取图例
        pieChart.setLegend(isEnacled = false)
        scaleInfoBinding.mPieChart.setDrawEntryLabels(true);

        scaleInfoBinding.mPieChart.setEntryLabelColor(Color.WHITE)

    }


    /**
     * 深睡浅睡信息添加
     *
     * @param lightSleepTime 浅睡时长
     * @param deepSleepTime 深睡时长
     * @param sobelSleepTime 清醒时长
     */
    private fun setSleepScaleChildInfo(lightSleepTime: Long, deepSleepTime: Long, sobelSleepTime: Long) {
        scaleInfoBinding.mLinearLayout.removeAllViews()
        val allSleepTime = lightSleepTime + deepSleepTime + sobelSleepTime
        val decimalFormat = DecimalFormat("#.0")
        for (i in 1..3) {
            var childView =
                LayoutInflater.from(context).inflate(R.layout.child_sleep_info, null, false)
            childView.layoutParams =
                LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1.0f)
            var image = childView.findViewById<ImageView>(R.id.mImage)
            var title = childView.findViewById<TextView>(R.id.mTitle)
            var time = childView.findViewById<TextView>(R.id.mTvTime)
            var percent = childView.findViewById<TextView>(R.id.mPercent)

            when (i) {
                1 -> {//深睡
                    image.setBackgroundResource(R.drawable.shape_deep_sleep)
                    title.text = "深睡"
//                    time.text = "1小时50分"
                    time.text = TimeUtils.secToStrHour(deepSleepTime)
                    percent.text = (decimalFormat.format(deepSleepTime.toFloat() / allSleepTime *100)).toString().padStart(3, '0') + "%"
                }

                2 ->
                {//浅睡
                    image.setBackgroundResource(R.drawable.shape_light_sleep)
                    title.text = "浅睡"
//                    time.text = "2小时37分"
                    time.text = TimeUtils.secToStrHour(lightSleepTime)
                    percent.text = (decimalFormat.format(lightSleepTime.toFloat() / allSleepTime *100)).toString().padStart(3, '0') + "%"
                }

                3 -> {//清醒
                    image.setBackgroundResource(R.drawable.shape_sober_sleep)
                    title.text = "清醒"
//                    time.text = "3小时01分"
                    time.text = TimeUtils.secToStrHour(sobelSleepTime)
                    if (sobelSleepTime == 0L){
                        percent.text = "0%"
                    } else {
                        percent.text = (decimalFormat.format(sobelSleepTime.toFloat() / allSleepTime *100)).toString().padStart(3, '0') + "%"
                    }
                }
            }
            scaleInfoBinding.mLinearLayout.addView(childView)
        }


        //填充数据，在这里换成自己的数据源
        var yVals1 = mutableListOf<PieEntry>()
        if (deepSleepTime > 0){//深睡
            val pieEntry = PieEntry(deepSleepTime.toFloat() / allSleepTime * 100, "深睡")
            pieEntry.label= ""
            yVals1.add(pieEntry)
        }

        if (lightSleepTime > 0){//浅睡
            val pieEntry = PieEntry(lightSleepTime.toFloat() / allSleepTime * 100, "浅睡")
            pieEntry.label= ""
            yVals1.add(pieEntry)
        }

        if (sobelSleepTime > 0){//清醒
            val pieEntry = PieEntry(sobelSleepTime.toFloat() / allSleepTime * 100, "清醒")
            pieEntry.label= ""
            yVals1.add(pieEntry)
        }
//        binding.m..setEntryLabelColor(Color.TRANSPARENT);
       // scaleInfoBinding.mPieChart.setDrawEntryLabels(false)
      //  scaleInfoBinding.mPieChart.setEntryLabelColor(Color.TRANSPARENT)
        /************  创建  初始化数据并赋值 ( 必写 ) ************/
        pieChart.setData(yVals1, getSleepStatuColors(yVals1), "pieChartView", 1f, 0f)
        pieChart.setRotationAngle(270f)
        pieChart.setPercent(true)
        //是否显示饼图上文字
        pieChart.showLabels(true)

        /************ 刷新数据( 必写 ) ************/
        pieChart.invalidate()

        /**1秒动画**/
        pieChart.animateX(1000)

    }


    private var introList: MutableList<SleepIntroBean>? = null
    /**
     * 封装睡眠信息介绍内容
     *
     * @param lightSleepTime 浅睡时长
     * @param deepSleepTime 深睡时长
     * @param sobelTime 清醒次数
     *
     */
    private fun setSleepIntroInfo(lightSleepTime: Long, deepSleepTime: Long, sobelTime: Int){
        introList = mutableListOf()

        introList?.apply {
            val allSleepTime = lightSleepTime + deepSleepTime

            var sleep = SleepIntroBean(
                String.format(
                    getString(R.string.sleep_time_tittle),
                    TimeUtils.secToStrHour(allSleepTime)
                ),
                getString(R.string.sleep_time_intro),
                getIntroStatu(IntroDefine.Sleep, allSleepTime = allSleepTime)
            )
            add(sleep)

            var deepBean = SleepIntroBean(
                String.format(
                    getString(R.string.sleep_deepPercent_tittle),
                    String.format("%.1f", deepSleepTime.toFloat() / allSleepTime * 100)
                ),
                getString(R.string.sleep_deepPercent_intro),
                getIntroStatu(
                    IntroDefine.Deep,
                    deepSleepTime = deepSleepTime,
                    allSleepTime = allSleepTime
                )
            )

            add(deepBean)

            var lightBean = SleepIntroBean(
                String.format(
                    getString(R.string.sleep_lightPercent_tittle),
                    String.format("%.1f", lightSleepTime.toFloat() / allSleepTime * 100)
                ),
                getString(R.string.sleep_lightPercent_intro),
                getIntroStatu(
                    IntroDefine.Light,
                    lightSleepTime = lightSleepTime,
                    allSleepTime = allSleepTime
                )
            )

            add(lightBean)

            var sobelBean = SleepIntroBean(
                String.format(
                    getString(R.string.sleep_soberTime_tittle), sobelTime
                ),
                getString(R.string.sleep_soberTime_intro),
                getIntroStatu(
                    IntroDefine.Sober,
                    sobelTime = sobelTime
                )
            )

            add(sobelBean)

            var ooBean = SleepIntroBean(
                String.format(
                    getString(R.string.sleep_oo_tittle), 96
                ),
                getString(R.string.sleep_oo_intro),
                getIntroStatu(
                    IntroDefine.Oo,
                    ooValue = 96
                )
            )

            add(ooBean)
        }

        showIntroList(introList)
    }
    var parentFragmentData:Fragment?=null
    fun setParentFragment(parentFragment: Fragment?) {
        parentFragmentData = parentFragment
    }

    enum class IntroDefine {
        /**睡眠**/
        Sleep,
        /**浅睡**/
        Light,
        /**深睡**/
        Deep,
        /**清醒**/
        Sober,
        /**血氧**/
        Oo,
    }

    /**
     * 睡眠介绍信息状态判断
     */
    private fun getIntroStatu(
        intro: IntroDefine,
        allSleepTime: Long = 0L,
        lightSleepTime: Long = 0L,
        deepSleepTime: Long = 0L,
        sobelTime: Int = 0,
        ooValue: Int = 0
    ): String {
        return when (intro) {
            IntroDefine.Sleep -> {
//                正常：6≤A≤10
//                偏高：A>10
//                偏低：A<6
                when (allSleepTime / 60) {
                    in 6..10 -> {
                        "正常"
                    }
                    in 0 until 6 -> {
                        "偏低"
                    }
                    else -> {
                        "偏高"
                    }
                }
            }
            IntroDefine.Light -> {
//                正常：C<55%
//                偏高：C≥55%
                when ((String.format("%.2f", lightSleepTime.toFloat() / allSleepTime)
                    .toFloat() * 100).toInt()) {
                    in 0..54 -> {
                        "正常"
                    }
                    else -> {
                        "偏高"
                    }
                }
            }
            IntroDefine.Deep -> {
//                正常：20%≤B≤60%
//                偏高：B>60%
//                偏低：B<20%
                when ((String.format("%.2f", deepSleepTime.toFloat() / allSleepTime)
                    .toFloat() * 100).toInt()) {
                    in 20..60 -> {
                        "正常"
                    }
                    in 0..20 -> {
                        "偏低"
                    }
                    else -> {
                        "偏高"
                    }
                }
            }
            IntroDefine.Sober -> {
//                正常：D≤2
//                偏高：D>2
               if (sobelTime > 2){
                   "偏高"
               }else{
                   "正常"
               }
            }
            IntroDefine.Oo -> {
//                正常：E≥95%
//                偏低：E<95%
                if (ooValue > 94) {
                    "正常"
                } else {
                    "偏低"
                }
            }
        }
    }

    /**
     * 睡眠信息介绍
     */
    private fun initSleepIntro() {
        scaleInfoBinding.mRecycle.apply {
            adapter = mIntroAdapter
            isNestedScrollingEnabled = false
            //分割线
            val divider = DividerItemDecoration(context, RecyclerView.VERTICAL)
            divider.setDrawable(resources.getDrawable(R.drawable.shape_item_decoration, null))
            addItemDecoration(divider)
            layoutManager = LinearLayoutManager(context)
//            mIntroAdapter.setNewInstance(null)
        }

        scaleInfoBinding.mOper.setOnClickListener {

            when (it.tag) {
                1 -> {//展开状态
                    scaleInfoBinding.mOper.tag = 0
                    scaleInfoBinding.mOper.text = "收起"
                    showIntroList(introList)
                }
                else -> {
                    scaleInfoBinding.mOper.tag = 1
                    scaleInfoBinding.mOper.text = "展开"
                    hideIntroList()
                }
            }
            update()
        }

    }

    fun update(){
        parentFragmentData?.let {
            if (it is SleepFrag){
                val sleepFrag = it as SleepFrag
                this.view?.let { it1 -> sleepFrag.updatePagerHeightForChild(it1) }
            }
        }
    }
    /**
     * 显示睡眠分析列表
     */
    private fun showIntroList(introList: MutableList<SleepIntroBean>?) {
        mIntroAdapter.setNewInstance(introList)
        binding.scaleInfo.mRecycle.visibility = View.VISIBLE


    }

    /**
     * 隐藏睡眠分析列表
     */
    private fun hideIntroList() {
//        mIntroAdapter.setNewInstance(null)
//        mIntroAdapter.notifyDataSetChanged()
        binding.scaleInfo.mRecycle.visibility = View.GONE

    }

    /**
     * 手动计算RecyclerView的高度
     * 步骤：
     * 1.获取ItemView的高度
     * 2.ItemView的数量
     * 3.两者相乘得出RecyclerView的高度
     */
    private fun setRecyclerViewHeight() {
//        //获取ItemView的数量
//        val itemCount = scaleInfoBinding.mRecycle.childCount
//
//        if (itemCount > 0) {
//            //两者相乘得出RecyclerView的高度
//            val recyclerViewHeight =
//                itemCount * scaleInfoBinding.mRecycle.getChildAt(0).layoutParams.height
//            //设置RecyclerView的高度
//            scaleInfoBinding.mRecycle.layoutParams.height = recyclerViewHeight
//        }
    }


    /**
     * 获取颜色信息
     */
    private fun getSleepStatuColors(entry: List<Entry>): List<Int> {
        var colors = mutableListOf<Int>()
        entry.forEachIndexed { index, _ ->
            when (index) {
                0 -> {//深睡
                    colors.add(getColor(R.color.col_72d))
                }
                1 -> {//浅睡
                    colors.add(getColor(R.color.col_d2fbef))
                }
                2 -> {//清醒
                    colors.add(getColor(R.color.col_ffe095))
                }
                else -> {
                    colors.add(getColor(R.color.col_d2fbef))
                }
            }
        }

        return colors
    }


    override fun onDestroy() {
        audioUtils.stopPlay()
        super.onDestroy()
    }

    /**
     * 计算评分
     */
    private fun calcScore(model: SleepBean.Model) :Int{
        val allSleepTime = model.deepSleepTotal + model.lightSleepTotal
        var lightSleep = model.lightSleepTotal//浅睡时长
        var deepSleep = model.deepSleepTotal //深睡时长


        //总睡眠时间
        val totalSleepHourTime = allSleepTime / 60.0
        var score =
            if (totalSleepHourTime <= 0){
                0.0
            }else if (totalSleepHourTime in 6.0..8.0){//睡眠时间大于等于6小时小于等于8小时
                60.0
            } else if (totalSleepHourTime > 0 && totalSleepHourTime < 6){
                totalSleepHourTime / 6.0 * 60.0
            }else {
                8.0 / totalSleepHourTime * 60.0
            }


        //深睡占比
        score += when (val deepSleepPercent =
            (String.format("%.2f",deepSleep.toFloat() / allSleepTime)
                .toFloat() * 100).toInt()) {
            in 20..40 -> {//深睡占比20%-40%
                10.0
            }
            in 0 until 20 -> {//深睡占比小于20%
                deepSleepPercent / 20.0 * 10.0
            }
            else -> {
                40.0 / deepSleepPercent * 10.0
            }
        }.toFloat()

        //浅睡占比
        score += when (val lightSleepPercent =
            (String.format("%.2f", lightSleep.toFloat() / allSleepTime)
                .toFloat() * 100).toInt()) {
            in 50..60 -> {//浅睡占比50%-60%
                10.0
            }
            in 0 until 50 -> {//深睡占比小于20%
                lightSleepPercent / 50.0 * 10.0
            }
            else -> {
                60.0 / lightSleepPercent * 10.0
            }
        }.toFloat()

        //清醒次数
        score += if (model.soberSleepCount < 4){
            10.0 * (10 - model.soberSleepCount) / 10.0
        } else {
            0.0
        }

        //平均血氧(目前未做计算直接给10分)
//        E1 = 10分
//        如果E≥95%，则E1=E1；
//        如果E＜95%，则E1=(E*100-70)/25*E1；
//        如果E＜85%，则E1=0
//        睡眠得分Y=A1+B1+C1+D1+E1。
        score += 10.0

        val mm = RxTimeTool.milliseconds2String(model.startTime.toLong() * 1000, SimpleDateFormat("mm")).toInt()
        when (RxTimeTool.milliseconds2String(model.startTime.toLong() * 1000, SimpleDateFormat("HH"))
            .toInt()) {
            in 0..2 -> {//0点-2点睡觉
                if (mm > 0) {
                    score -= 5.0
                }
            }
            in 2 until 20 -> {//2点-20点之间
                if (mm > 0) {
                    score -= 10.0
                }
            }
        }

        return if (score < 0) 0 else score.toInt()
    }

    override fun observer() {
        mViewModel.sleepLive.observe(this) {

            if (it.data == null) {
                return@observe
            }

            if (it.data.value.isNullOrEmpty()){
                setViewShowOrHide(false)
                return@observe
            } else {
                setViewShowOrHide(true)
            }
            it.data!!.model.let { model ->

                if (model.startTime == 0) {
                    return@let
                }

                //评分信息更新
                updateScoreInfo(calcScore(model))
                var allTimeSecond = (model.endTime.toLong() -(model.startTime.toLong()))/60
                var sleepTimeSecond =(model.deepSleepTotal + model.lightSleepTotal).toLong()
                var soberTimeSecond = (allTimeSecond - sleepTimeSecond)*60
                var allTimeStr =
                    TimeUtils.secToStrMinutes(sleepTimeSecond)//总睡眠时间

                var lightSleep = model.lightSleepTotal
//                    max(model.deepSleepTotal, model.lightSleepTotal)//浅睡时长
                var deepSleep = model.deepSleepTotal
//                    min(model.deepSleepTotal, model.lightSleepTotal)//深睡时长

                val content = getString(R.string.sleep_time, allTimeStr[0], allTimeStr[1])

                binding.mChartInfo.mSleepTime.text = SpannableUtils.setStrSpan(content, 23,
                    getColor(R.color.black), Typeface.BOLD,0, allTimeStr[0].length,
                    content.length - 1 - allTimeStr[1].length, content.length - 1)

                binding.mScoreInfo.apply {
                    mText.text = getString(R.string.sleep_intro)
//                        Html.fromHtml(getString(R.string.sleep_desc, "${allTimeStr}小时")) //desc提示
                }

                binding.mChartInfo.apply {
                    var previousTime = 0L //上一个数据的结束时间 用以判断是否为清醒
                    var allSleepTime = 0  //总睡眠时间含清醒时间  从开始睡觉-早上起床的时长
                    var listTime = mutableListOf<SleepBean.Value>()
                    var totalSoberSleepTime = 0L//清醒时间是分钟
                    it.data.value.forEachIndexed { index, value ->
                        if (index == 0) {
                            listTime.add(value)
                        } else {
                            if (previousTime + 1 == getSecondTime(value.sleepStartTime)) {  //上次结束时间加一分钟为这次开始的时间表示中间无清醒
                                listTime.add(value)
                            } else {  // 清醒了
                                //计算清醒的数据 并插入（原始数据中并没有清醒数据 所以这里需要计算并插入清醒数据）
                                var soberSleepTime =
                                    (getSecondTime(value.sleepStartTime) - previousTime).toInt() - 1
                                var bean = SleepBean.Value(
                                    soberSleepTime,//清醒时长
                                    previousTime + 1,//计算清醒开始时间
                                    999
                                )
                                totalSoberSleepTime += soberSleepTime
                                //还要加清醒时间的时间段
                                allSleepTime += soberSleepTime //单位 秒

                                listTime.add(bean)
                                //添加原来的数据
                                listTime.add(value)
                            }

                        }
                        previousTime =
                            getSecondTime(value.sleepStartTime) + value.sleepLen //上一条数据的睡眠结束时间
                        allSleepTime += value.sleepLen //单位 秒

                    }
                    //睡眠比例信息
                    setSleepScaleChildInfo(lightSleep.toLong(), deepSleep.toLong(), soberTimeSecond / 60)
                    //睡眠信息介绍
                    setSleepIntroInfo(lightSleep.toLong(), deepSleep.toLong(), model.soberSleepCount)
                    if (listTime.isEmpty()) {
                        mSLeepShow.visibility = View.GONE
                    } else {
                        mSLeepShow.setData(allSleepTime, listTime)
                    }

                    mStart.text = "入睡${
                        RxTimeTool.milliseconds2String(
                            model.startTime * 1000.toLong(),
                            SimpleDateFormat("HH:mm")
                        )
                    }"
                    mEnd.text = "起床${
                        RxTimeTool.milliseconds2String(
                            model.endTime * 1000.toLong(),
                            SimpleDateFormat("HH:mm")
                        )
                    }"

                }
            }
            update()
        }


        mViewModel.setting.observe(this) {
            if (it.data.isNotEmpty()) {
                binding.mChartInfo.mDesc.text = "${it.data[0].name}：${it.data[0].content}"
            }
            update()
        }

    }

    private fun setViewShowOrHide(isShow:Boolean) {
        if (isShow){
            binding.mScoreInfo.root.visibility = View.VISIBLE
            binding.scaleInfo.root.visibility = View.VISIBLE
            binding.mChartInfo.mStartAndEnd.visibility = View.VISIBLE
        } else {
            binding.mChartInfo.mSleepTime.text = "0时00分"
            binding.mChartInfo.mSLeepShow.setData(0, mutableListOf())
            binding.mScoreInfo.root.visibility = View.GONE
            binding.scaleInfo.root.visibility = View.GONE
            binding.mChartInfo.mStartAndEnd.visibility = View.GONE

        }
        update()
    }

    /**
     * 修正数据  不要毫秒 要的秒
     */
    private fun getSecondTime(time: Long): Long {
        if (time > 9999999999) {
            return time / 1000
        }
        return time
    }


    /**
     * 周数据
     */
    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]
    }


}