package com.zj365.health.act

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.DashPathEffect
import android.graphics.Matrix
import android.graphics.drawable.GradientDrawable
import android.text.Html
import android.text.Spannable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextUtils
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.view.get
import androidx.core.view.size
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.androidkun.xtablayout.XTabLayout
import com.bigkoo.pickerview.adapter.ArrayWheelAdapter
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.view.OptionsPickerView
import com.blankj.utilcode.util.TimeUtils
import com.contrarywind.view.WheelView
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.BarData
import com.github.mikephil.charting.data.BarDataSet
import com.github.mikephil.charting.data.BarEntry
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.tamsiree.rxkit.RxTimeTool
import com.xty.base.act.BaseVmAct
import com.xty.base.utils.UserInfoDefin
import com.xty.common.AESCrypt
import com.xty.common.BuildConfig
import com.xty.common.Const
import com.xty.common.LogUtils
import com.xty.common.MMkvHelper
import com.xty.common.TimeSelect
import com.xty.common.WxUtils
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.event.IntegralEvent
import com.xty.common.model.ReportBean
import com.xty.common.setImageUser
import com.xty.common.setOrganStatus
import com.xty.common.util.CommonToastUtils
import com.xty.common.util.CommonUtils
import com.xty.common.util.DeviceFunctionUtils
import com.xty.common.weight.CenterImageSpan
import com.xty.common.weight.HealthBodyView
import com.xty.network.model.DeviceFunctionBean
import com.zj365.health.R
import com.zj365.health.act.exception.BaseExceptionDataAct
import com.zj365.health.adapter.DayReportInfoAdapter
import com.zj365.health.adapter.ReportAnalysisAdapter
import com.zj365.health.adapter.ReportInfoAdapter
import com.zj365.health.databinding.ActHealthWeekMonthHourReportBinding
import com.zj365.health.model.MyReportBean
import com.zj365.health.vm.ReportVm
import com.zj365.health.weight.DialogTip
import com.zj365.health.weight.GridDividerItemDecoration
import com.zj365.health.weight.HealthDialog
import com.zj365.health.weight.PopWindowUserInfo
import com.xty.network.model.RespBody
import com.zj365.health.adapter.HealthSignDataAdapter
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.json.JSONArray
import org.json.JSONObject
import java.math.BigDecimal
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date

/**
 * （近7或近30）天健康评估
 */
@Route(path = ARouterUrl.HEALTH_WEEK_MONTH_HOUR_REPORT)
class HealthWeekMonthHourReportAct : BaseVmAct<ReportVm>() {

    private val binding by lazy { ActHealthWeekMonthHourReportBinding.inflate(layoutInflater) }
    override fun setLayout(): View = binding.root

    private var isX1X2 = false
    private var isDemonstrate = false //是否是演示模式
    private var isEstimate = false  //是否是评估页面
    private var isNearMouth = false // 是否是近30天，只有在评估界面才有该数据 判断是近7天或者近30天的
    private var userId = ""
    private var titleName = ""
    private var index = ReportVm.ReportInfoType.Day
    private var dayDate = ""
    private var weekDate = ""
    private var mouthDate = ""
    private var yearDate = ""
    private var sex = "1"
    private var formatStr = ""
    private var user: com.xty.network.model.ReportBean.User? = null

    private var isSelectTable = false
    private var isScrollTable = false
    private var launch: Job? = null

    private val listInfo = mutableListOf<com.xty.network.model.ReportBean.HrInfo>()
    private val xiyiList = mutableListOf<MyReportBean>()

    /**
     * 点击器官时器官趋势时间TextView
     */
    private val organTimeTvArray = arrayListOf<TextView>()

    /**
     * 健康趋势时间TextView
     */
    private val healthTimeTvArray = arrayListOf<TextView>()

    private var list = mutableListOf<BarEntry>()
    private var mapWeek = LinkedHashMap<String, String>() //仅在周日报查询的时候使用
    private lateinit var mWeekPickerView: OptionsPickerView<String>

    private val popWindow by lazy { PopWindowUserInfo() }
    private var bottomSheetDialog: BottomSheetDialog? = null

    private val mAnasylsAdapter by lazy { ReportInfoAdapter() }
    private val mAdapter by lazy { ReportAnalysisAdapter() }
    private val infoAdapter by lazy { DayReportInfoAdapter() }

    private val mTitless = mutableListOf<String>()

    /**
     * 综合分析列表
     */
    private val healthSignDataGriddingAdapter by lazy { HealthSignDataAdapter() }
    private val healthSignDataAdapter by lazy { HealthSignDataAdapter() }
    private val signDataGriddingList = mutableListOf<String>()
    private val signDataList = mutableListOf<String>()


    var functionList = ArrayList<DeviceFunctionBean>()

    private val tipDialog by lazy {
        //-1 建模中 0数据不足 1健康 2亚健康 3疾病
        val title = when (mViewModel.infoLive.value!!.data.analyse.status.toInt()) {
            0 -> {
                getString(R.string.tip_nodata_data)
            }

            1 -> {
                getString(R.string.tip_health_data)
            }

            2 -> {
                getString(R.string.tip_subhealth_data)
            }

            3 -> {
                getString(R.string.tip_disease_data)
            }

            else -> {
                getString(R.string.tip_modeling)
            }
        }
        HealthDialog(this, true, title) {
        }
    }

    private val timeMonthSelect by lazy {
        TimeSelect(this) {
            if (isDemonstrate) {
                setDemoMoth()
            } else {
                mouthDate = binding.mTime.text.toString()
                mViewModel.getReportInfoNeW(
                    index,
                    binding.mTime.text.toString(),
                    userId,
                    isDemonstrate
                )
//                mViewModel.getReportAvgNew(
//                    index.reportType,
//                    binding.mTime.text.toString(),
//                    userId,
//                    isDemonstrate
//                )
            }
        }
    }

    private val dialogBind by lazy {
        DialogTip(this, "需绑定中健三六五健康手表，才能查看", "去绑定") {
            RouteManager.goAct(ARouterUrl.DEVICE_CHOICE)
        }
    }

    private val shareDialogBind by lazy {
        DialogTip(this, "需绑定中健三六五健康手表，才能分享", "去绑定") {
            RouteManager.goAct(ARouterUrl.DEVICE_CHOICE)
        }
    }

    private val timeYearSelect by lazy {
        TimeSelect(this) {
            yearDate = binding.mTime.text.toString()
            mViewModel.getReportInfoNeW(index, binding.mTime.text.toString(), userId, isDemonstrate)
        }
    }

    private val timSelect by lazy {
        TimeSelect(this) {
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initData() {
        super.initData()
        isX1X2 = MMkvHelper.getBoolean(Const.X1_X2_Device, false)

        isNearMouth = intent.getBooleanExtra("isNearMouth", false)
        userId = intent.getStringExtra("id").toString()
        titleName = intent.getStringExtra("titleName").toString()
        index = intent.getSerializableExtra("index") as ReportVm.ReportInfoType
        isDemonstrate = intent.getBooleanExtra("isDemonstrate", false)
        isEstimate = intent.getBooleanExtra("isEstimate", false)

        if(intent.extras!!.containsKey("functionList")){
            functionList = intent.extras!!.getParcelableArrayList<DeviceFunctionBean>("functionList")!!
        }

        if (isEstimate) {
            binding.mTime.setCompoundDrawablesWithIntrinsicBounds(
                null,  // left
                null,  // top
                null,                           // right (set to null)
                null   // bottom
            )
            binding.mTime.isEnabled = false
            if (isNearMouth) {
                //近30天
                binding.mTv1.text = "近30天健康状态趋势"
                binding.mTime.text = CommonUtils.getSpaceTime(29)

                if (isDemonstrate) {
                    setDemoMoth()
                }
            } else {
                //近7天
                binding.mTv1.text = "近7天健康状态趋势"
                binding.mTime.text = CommonUtils.getSpaceTime(6)
            }
        } else {
            when (index) {
                ReportVm.ReportInfoType.Week -> {
                    formatStr = "yyyy-MM-dd"
                    binding.mTv1.text = "周健康状态趋势"
                    weekMonday()
                    selectOption()

                    mapWeek.keys.forEachIndexed { position, str ->
                        if (position == mapWeek.keys.size - 1) {
                            binding.mTime.text = str
                        }
                    }
                }

                ReportVm.ReportInfoType.Month -> {
                    binding.mTv1.text = "月健康状态趋势"
                    formatStr = "yyyy-MM"
                    timSelect.showDay = false

                    //月状态 结束时间为上月
                    val canlendar = Calendar.getInstance()
                    timeMonthSelect.endDate.add(Calendar.MONTH, -1)
                    // 如果当前月份是一月，将年份减一，并将月份设置为十二月
                    if (timeMonthSelect.endDate.get(Calendar.MONTH) == Calendar.JANUARY) {
                        timeMonthSelect.endDate.add(Calendar.YEAR, -1)
                        timeMonthSelect.endDate.set(Calendar.MONTH, Calendar.DECEMBER)
                    }
                    canlendar.add(Calendar.MONTH, -1)
                    val month = canlendar.get(Calendar.MONTH) + 1

                    binding.mTime.text =
                        "${canlendar.get(Calendar.YEAR)}-${if (month > 9) "$month" else "0$month"}"

                    if (isDemonstrate) {
                        setDemoMoth()
                    }
                }

                ReportVm.ReportInfoType.Year -> {
                    binding.mTv1.text = "本年度健康状态趋势"
                    formatStr = "yyyy"
                    timSelect.showDay = false
                    timSelect.showMonth = false
                    //年状态 结束时间为上年
                    val canlendar = Calendar.getInstance()
                    canlendar.set(
                        canlendar.get(Calendar.YEAR) - 1,
                        11,
                        canlendar.getActualMaximum(Calendar.DAY_OF_MONTH)
                    )
                    timSelect.endDate.set(
                        canlendar.get(Calendar.YEAR),
                        canlendar.get(Calendar.MONTH),
                        canlendar.get(Calendar.DATE)
                    )
                    binding.mTime.text = "${canlendar.get(Calendar.YEAR)}"
                }

                else -> {}
            }
        }

        /**
         * 综合分析列表
         */
        binding.recyclerViewGridding.layoutManager = GridLayoutManager(this, 2)
        binding.recyclerViewGridding.adapter = healthSignDataGriddingAdapter
        binding.recyclerViewList.layoutManager = LinearLayoutManager(this)
        binding.recyclerViewList.adapter = healthSignDataAdapter
    }

    @SuppressLint("SetTextI18n")
    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        if (isDemonstrate) {
            binding.title.mTvTitle.text = "${titleName}(演示模式)"
        } else {
            binding.title.mTvTitle.text = titleName
        }
        binding.title.mIvBack.setOnClickListener {
            finish()
        }
        binding.title.mIvReight.apply {
            visibility = if (!isEstimate) {
                View.VISIBLE
            } else {
                View.GONE
            }
            this.setImageResource(R.mipmap.icon_share)
            this.setOnClickListener {
                if (isDemonstrate) {
                    shareDialogBind.show()
                    return@setOnClickListener
                }
                mViewModel.shareRecordRequest()
            }
        }

        if(functionList.size == 0){
            mViewModel.getDeviceFunctionList(userId)
        }

        //设置tab
        //"用户信息", "健康状态趋势", "器官功能分析", "中医分析", "中医养生指导", "西医分析", "西医指导",
        // "饮食指导", "运动指导", "睡眠方案建议", "营养处方建议", "统计分析", "综合分析"
        binding.xTablayout.setOnTabSelectedListener(object : XTabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: XTabLayout.Tab?) {
                if (!isScrollTable) {
                    Log.e("mTag", "选择的${tab?.position!!}")
                    isSelectTable = true
                    if (launch != null) {
                        launch?.cancel()
                    }
                    var rvPosition = 0
                    run breaking@{
                        xiyiList.forEachIndexed { index, _ ->
                            if (mTitless[tab.position] == xiyiList[index].name) {
                                rvPosition = index
                                return@breaking
                            }
                        }
                    }
                    if (binding.mRecycle1.size > 0) {
                        val top = binding.mRecycle1.top
                        val itemTop = binding.mRecycle1[rvPosition].top
                        when (mTitless[tab.position]) {
                            "用户信息" -> {
                                binding.scrollView.smoothScrollTo(
                                    0,
                                    binding.clUserTitle.top
                                )
                            }

                            "健康状态趋势" -> {
                                binding.scrollView.smoothScrollTo(
                                    0,
                                    binding.clUserTitle.top
                                )
                            }

                            "器官功能分析" -> {
                                binding.scrollView.smoothScrollTo(
                                    0,
                                    binding.clUserTitle.top
                                )
                            }

//                            "器官功能分析" -> {
//                                binding.scrollView.smoothScrollTo(
//                                    0,
//                                    binding.child.llApparatusTitle.top
//                                )
//                            }

                            "中医分析" -> {
                                binding.scrollView.smoothScrollTo(
                                    0,
                                    top + itemTop
                                )
                            }

                            "中医养生指导" -> {
                                binding.scrollView.smoothScrollTo(
                                    0,
                                    top + itemTop
                                )
                            }

                            "西医分析" -> {
                                binding.scrollView.smoothScrollTo(
                                    0,
                                    top + itemTop
                                )
                            }

                            "西医指导" -> {
                                binding.scrollView.smoothScrollTo(
                                    0,
                                    top + itemTop
                                )
                            }

                            "饮食指导" -> {
                                binding.scrollView.smoothScrollTo(
                                    0,
                                    top + itemTop
                                )
                            }

                            "运动指导" -> {
                                binding.scrollView.smoothScrollTo(
                                    0,
                                    top + itemTop
                                )
                            }

                            "睡眠方案建议" -> {
                                binding.scrollView.smoothScrollTo(
                                    0,
                                    top + itemTop
                                )
                            }

                            "营养处方建议" -> {
                                binding.scrollView.smoothScrollTo(
                                    0,
                                    top + itemTop
                                )
                            }

                            "统计分析" -> {
                                binding.scrollView.smoothScrollTo(
                                    0,
                                    binding.clStatistics.top
                                )
                            }

                            "综合分析" -> {
                                binding.scrollView.smoothScrollTo(
                                    0,
                                    binding.mLinAllInfo.top
                                )
                            }
                        }
                    }

                    launch = GlobalScope.launch {
                        delay(1000) // 延迟一秒
                        // 在这里执行你的操作
                        isSelectTable = false
                    }
                }
            }

            override fun onTabUnselected(tab: XTabLayout.Tab?) {
            }

            override fun onTabReselected(tab: XTabLayout.Tab?) {
            }

        })
        binding.scrollView.setOnScrollChangeListener(
            NestedScrollView.OnScrollChangeListener { _, _, scrollY, _, _ ->
                if (mTitless.size > 0) {
                    if (!isSelectTable) {
                        Log.e("mTag", "移动的${scrollY}")
                        isScrollTable = true
                        val selectedTabPosition = binding.xTablayout.selectedTabPosition
                        if (scrollY >= binding.mLinAllInfo.top) {
                            if (selectedTabPosition != mTitless.size - 1) {
                                binding.xTablayout.getTabAt(mTitless.size - 1)?.select()
                            }
                        } else if (scrollY >= binding.clStatistics.top) {
                            if (selectedTabPosition != mTitless.size - 2) {
                                binding.xTablayout.getTabAt(mTitless.size - 2)?.select()
                            }
                        } else if (scrollY >= binding.mRecycle1.top) {
                            //"用户信息", "健康状态趋势", "器官功能分析", "中医分析", "中医养生指导", "西医分析", "西医指导",
                            //"饮食指导", "运动指导", "睡眠方案建议", "营养处方建议", "统计分析", "综合分析"
                            if (binding.mRecycle1.size - 1 > 0 &&
                                scrollY >= binding.mRecycle1.top + binding.mRecycle1[binding.mRecycle1.size - 1].top
                            ) {
                                if (selectedTabPosition != getTabPosition(binding.mRecycle1.size - 1)) {
                                    binding.xTablayout.getTabAt(getTabPosition(binding.mRecycle1.size - 1))
                                        ?.select()
                                }
                            } else if (binding.mRecycle1.size - 2 > 0 &&
                                scrollY >= binding.mRecycle1.top + binding.mRecycle1[binding.mRecycle1.size - 2].top
                            ) {
                                if (selectedTabPosition != getTabPosition(binding.mRecycle1.size - 2)) {
                                    binding.xTablayout.getTabAt(getTabPosition(binding.mRecycle1.size - 2))
                                        ?.select()
                                }
                            } else if (binding.mRecycle1.size - 3 > 0 &&
                                scrollY >= binding.mRecycle1.top + binding.mRecycle1[binding.mRecycle1.size - 3].top
                            ) {
                                if (selectedTabPosition != getTabPosition(binding.mRecycle1.size - 3)) {
                                    binding.xTablayout.getTabAt(getTabPosition(binding.mRecycle1.size - 3))
                                        ?.select()
                                }
                            } else if (binding.mRecycle1.size - 4 > 0 &&
                                scrollY >= binding.mRecycle1.top + binding.mRecycle1[binding.mRecycle1.size - 4].top
                            ) {
                                if (selectedTabPosition != getTabPosition(binding.mRecycle1.size - 4)) {
                                    binding.xTablayout.getTabAt(getTabPosition(binding.mRecycle1.size - 4))
                                        ?.select()
                                }
                            } else if (binding.mRecycle1.size - 5 > 0 && getListPosition(binding.mRecycle1.size - 5) != "西医指导" &&
                                scrollY >= binding.mRecycle1.top + binding.mRecycle1[binding.mRecycle1.size - 5].top
                            ) {
                                if (selectedTabPosition != getTabPosition(binding.mRecycle1.size - 5)) {
                                    binding.xTablayout.getTabAt(getTabPosition(binding.mRecycle1.size - 5))
                                        ?.select()
                                }
                            } else if (binding.mRecycle1.size - 5 > 0 && getListPosition(binding.mRecycle1.size - 5) == "西医指导" &&
                                scrollY >= binding.mRecycle1.top + binding.mRecycle1[binding.mRecycle1.size - 5].top
                            ) {
                                if (selectedTabPosition != getTabPosition(binding.mRecycle1.size - 6)) {
                                    binding.xTablayout.getTabAt(getTabPosition(binding.mRecycle1.size - 6))
                                        ?.select()
                                }
                            } else if (binding.mRecycle1.size - 6 > 0 && getListPosition(binding.mRecycle1.size - 6) != "中医养生指导" &&
                                scrollY >= binding.mRecycle1.top + binding.mRecycle1[binding.mRecycle1.size - 6].top
                            ) {
                                if (selectedTabPosition != getTabPosition(binding.mRecycle1.size - 6)) {
                                    binding.xTablayout.getTabAt(getTabPosition(binding.mRecycle1.size - 6))
                                        ?.select()
                                }
                            } else if (binding.mRecycle1.size - 6 > 0 && getListPosition(binding.mRecycle1.size - 6) == "中医养生指导" &&
                                scrollY >= binding.mRecycle1.top + binding.mRecycle1[binding.mRecycle1.size - 6].top
                            ) {
                                if (selectedTabPosition != getTabPosition(binding.mRecycle1.size - 7)) {
                                    binding.xTablayout.getTabAt(getTabPosition(binding.mRecycle1.size - 7))
                                        ?.select()
                                }
                            } else if (binding.mRecycle1.size - 7 > 0 && getListPosition(binding.mRecycle1.size - 7) != "中医养生指导" &&
                                scrollY >= binding.mRecycle1.top + binding.mRecycle1[binding.mRecycle1.size - 7].top
                            ) {
                                if (selectedTabPosition != getTabPosition(binding.mRecycle1.size - 7)) {
                                    binding.xTablayout.getTabAt(getTabPosition(binding.mRecycle1.size - 7))
                                        ?.select()
                                }
                            } else if (binding.mRecycle1.size - 7 > 0 && getListPosition(binding.mRecycle1.size - 7) == "中医养生指导" &&
                                scrollY >= binding.mRecycle1.top + binding.mRecycle1[binding.mRecycle1.size - 7].top
                            ) {
                                if (selectedTabPosition != getTabPosition(binding.mRecycle1.size - 8)) {
                                    binding.xTablayout.getTabAt(getTabPosition(binding.mRecycle1.size - 8))
                                        ?.select()
                                }
                            } else if (binding.mRecycle1.size - 8 > 0 &&
                                scrollY >= binding.mRecycle1.top + binding.mRecycle1[binding.mRecycle1.size - 8].top
                            ) {
                                if (selectedTabPosition != getTabPosition(binding.mRecycle1.size - 8)) {
                                    binding.xTablayout.getTabAt(getTabPosition(binding.mRecycle1.size - 8))
                                        ?.select()
                                }
                            } else if (scrollY >= binding.mRecycle1.top + binding.mRecycle1[1].top) {
                                if (selectedTabPosition != getTabPosition(1)) {
                                    binding.xTablayout.getTabAt(getTabPosition(1))
                                        ?.select()
                                }
                            } else if (scrollY >= binding.mRecycle1.top + binding.mRecycle1[3].top) {
                                if (selectedTabPosition != getTabPosition(3)) {
                                    binding.xTablayout.getTabAt(getTabPosition(3))
                                        ?.select()
                                }
                            } else {
                                if (selectedTabPosition != getTabPosition(0)) {
                                    binding.xTablayout.getTabAt(getTabPosition(0))?.select()
                                }
                            }
                        } else if (scrollY >= binding.child.llApparatusTitle.top) {
                            if (selectedTabPosition != 0) {
                                binding.xTablayout.getTabAt(0)?.select()
                            }
                        } else if (scrollY >= binding.clChartTitle.top) {
                            if (selectedTabPosition != 0) {
                                binding.xTablayout.getTabAt(0)?.select()
                            }
                        } else if (scrollY >= binding.clUserTitle.top) {
                            if (selectedTabPosition != 0) {
                                binding.xTablayout.getTabAt(0)?.select()
                                binding.xTablayout.setScrollPosition(0, 0F, true)
                            }
                        }
                        isScrollTable = false
                    }
                }
            })

        if (!isEstimate) {
            initTimeSelect()
        }

        if (isDemonstrate && index == ReportVm.ReportInfoType.Month) {  //如果时演示模式,同时是月报
            binding.llDemoTime.visibility = View.VISIBLE
            binding.mLinTime.visibility = View.GONE
        }

        if (isDemonstrate) {
            binding.tvGuid.text = "退出演示模式"
        } else {
            binding.tvGuid.visibility = View.GONE
            binding.vDemoShow.visibility = View.GONE
        }
        binding.tvGuid.setOnClickListener {
            if (isDemonstrate) {
                finish()
            }
        }

        popWindow.myPopWindow(this, R.layout.pop_report)
        initHealthTrendTime()
        changeTopShape(R.color.col_9BDd, binding.status1)
        changeTopShape(R.color.col_9BD, binding.status2)
        changeTopShape(R.color.col_FDA481, binding.status3)
        changeTopShape(R.color.col_7b8, binding.status0)
        changeTopShape(R.color.col_EFF, binding.status4)

        initAnysisRecycle()
        initRecycle()
        initRecycleInfo()
        initBarChart()

        when (index) {
            ReportVm.ReportInfoType.Week -> {
                mViewModel.getReportInfoNeW(
                    index,
                    binding.mTime.text.toString(),
                    userId,
                    isDemonstrate
                )
//                mViewModel.getReportAvgNew(
//                    index.reportType,
//                    binding.mTime.text.toString(),
//                    userId,
//                    isDemonstrate
//                )
            }

            ReportVm.ReportInfoType.Month -> {
                val canlendar = Calendar.getInstance()
                canlendar.add(Calendar.MONTH, -1)

                mViewModel.getReportInfoNeW(
                    index,
                    binding.mTime.text.toString(),
                    userId,
                    isDemonstrate
                )
//                mViewModel.getReportAvgNew(
//                    index.reportType,
//                    binding.mTime.text.toString(),
//                    userId,
//                    isDemonstrate
//                )
            }

            ReportVm.ReportInfoType.Year -> {
                //年状态 结束时间为上年
                mViewModel.getReportInfoNeW(
                    index,
                    binding.mTime.text.toString(),
                    userId,
                    isDemonstrate
                )
//                mViewModel.getReportAvgNew(
//                    index.reportType,
//                    binding.mTime.text.toString(),
//                    userId,
//                    isDemonstrate
//                )
            }

            else -> {}
        }
    }

    private fun getTabPosition(listPosition: Int): Int {
        var rvPosition = 0
        run breaking@{
            mTitless.forEachIndexed { index, _ ->
                if (mTitless[index] == xiyiList[listPosition].name) {
                    rvPosition = index
                    return@breaking
                }
            }
        }
        return rvPosition
    }

    private fun getListPosition(title: Int): String {
        var rvPosition = ""
        run breaking@{
            xiyiList.forEachIndexed { index, titleStr ->
                if (title == index) {
                    rvPosition = titleStr.name
                    return@breaking
                }
            }
        }
        return rvPosition
    }

    private fun initAnysisRecycle() {
        binding.mRecycle1.adapter = mAnasylsAdapter
//        binding.mRecycle1.addItemDecoration(RecycleItem(this, 30))
        binding.mRecycle1.layoutManager = LinearLayoutManager(this)
        mAnasylsAdapter.addChildClickViewIds(R.id.mExpans)

        mAnasylsAdapter.setOnItemChildClickListener { adapter, view, position ->
            val bean = adapter.getItem(position) as MyReportBean
            val tv = view.tag as TextView
            bean.isLaunch = tv.maxLines == 3
            mAnasylsAdapter.notifyItemChanged(position)
        }
    }

    /**
     * 底部圆形分析
     */
    private fun initRecycle() {
        binding.mRecycle.adapter = mAdapter
        binding.mRecycle.layoutManager = LinearLayoutManager(this)
    }

    /**
     * 分析依据
     */
    private fun initRecycleInfo() {
        binding.mRecycleInfo.adapter = infoAdapter
        binding.mRecycleInfo.layoutManager = GridLayoutManager(this, 2)
        binding.mRecycleInfo.addItemDecoration(GridDividerItemDecoration(0, 2))
    }

    private fun initBarChart() {
        binding.mBar.clear()
        binding.mBar.setNoDataText(getString(R.string.line_chart_not_data))
        binding.mBar.setNoDataTextColor(ContextCompat.getColor(this, R.color.col_455))
        setSleepBg(R.color.col_5a5, binding.m1)
        setSleepBg(R.color.col_b1b, binding.m2)
        //为第一组添加数据
        if (list.isNullOrEmpty()) {
            return
        }
        val barDataSet = BarDataSet(list, "")
        barDataSet.stackLabels = arrayOf("", "")
        barDataSet.valueTextColor = ContextCompat.getColor(this, R.color.col_455)
        //柱体颜色
        barDataSet.setColors(
            ContextCompat.getColor(this, R.color.col_b1b),
            ContextCompat.getColor(this, R.color.col_5a5)
        )

        val barData = BarData(barDataSet) //加上第一组
        barData.barWidth = 0.2f
        binding.mBar.data = barData
        val m = Matrix()
        m.postScale(1.1f, 1f)
        binding.mBar.viewPortHandler.refresh(m, binding.mBar, false)
        binding.mBar.setBackgroundColor(Color.WHITE) ///color


        binding.mBar.description.isEnabled = false //右下角一串英文字母不显示
        binding.mBar.legend.isEnabled = false  //自带的颜色标示不用

        binding.mBar.setTouchEnabled(true)
        binding.mBar.isDragEnabled = true
        binding.mBar.setScaleEnabled(false)

        binding.mBar.setLayerType(View.LAYER_TYPE_SOFTWARE, null)

        //X轴坐标的个数    第二个参数一般填false     true表示强制设置标签数 可能会导致X轴坐标显示不全等问题
        //    binding.mBar.getXAxis().setLabelCount(7, false)
        binding.mBar.axisRight.isEnabled = false //右侧Y轴不显示   默认为显示

        //x轴
        val x = binding.mBar.xAxis

        // x.axisMinimum = 0f
        //  x.axisMaximum = list.size.toFloat()+1
        x.granularity = 1f  //精准设置        //最大值*//*
        x.textColor = ContextCompat.getColor(this, R.color.col_92a)
        x.isEnabled = true
        x.setDrawGridLines(false)  //不绘制y
        x.setDrawAxisLine(true)
        x.setAxisLineDashedLine(DashPathEffect(floatArrayOf(5f, 5f), 0f))
        x.position = XAxis.XAxisPosition.BOTTOM
        x.setValueFormatter { value, axis ->
            var index = value.toInt()
            //Log.e("x轴", "$value")
            if (index < 0 || index >= list.size) {
                ""
            } else {
                RxTimeTool.milliseconds2String(
                    list[index].data.toString().toLong() * 1000,
                    SimpleDateFormat("MM-dd")
                )
            }
        }
        //y轴
        val y = binding.mBar.axisLeft
        y.setGridDashedLine(DashPathEffect(floatArrayOf(5f, 5f), 0f))
        y.axisMinimum = 0f
        y.gridColor = ContextCompat.getColor(this, R.color.col_92a)
        y.setDrawGridLines(true)  //绘制横者的x轴
        y.setDrawZeroLine(false)
        y.setDrawAxisLine(false)
    }

    private fun initTimeSelect() {
        val currentDay = Date()
        dayDate = TimeUtils.date2String(currentDay, "yyyy-MM-dd")
        weekDate = com.xty.common.TimeUtils.getPreviousWeekDateRange()
        mouthDate = TimeUtils.date2String(currentDay, "yyyy-MM")
        when (index) {
            ReportVm.ReportInfoType.Week -> {
                binding.mTime.text = weekDate
            }

            ReportVm.ReportInfoType.Month -> {
                mouthDate = binding.mTime.text.toString()
            }

            ReportVm.ReportInfoType.Year -> {
                yearDate = binding.mTime.text.toString()
            }

            else -> {

            }
        }

        binding.mTime.setOnClickListener {
            when (index) {
                ReportVm.ReportInfoType.Week -> {
                    bottomSheetDialog?.show()
                }

                ReportVm.ReportInfoType.Month -> {
                    timeMonthSelect.selectTimeWithYearMonth(it, "yyyy-MM")
                }

                ReportVm.ReportInfoType.Year -> {
                    timeYearSelect.selectTimeWithYear(it, "yyyy")
                }

                else -> {

                }
            }
        }
        initBottomDialog()
    }

    private fun initBottomDialog() {
        if (bottomSheetDialog == null) {
            bottomSheetDialog = BottomSheetDialog(this)
            bottomSheetDialog?.let { dialog ->
                val view = LayoutInflater.from(this).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.mTime.text = item.toString()
                    weekDate = binding.mTime.text.toString()
                    mViewModel.getReportInfoNeW(
                        index,
                        binding.mTime.text.toString(),
                        userId,
                        isDemonstrate
                    )
//                    mViewModel.getReportAvgNew(
//                        index.reportType,
//                        binding.mTime.text.toString(),
//                        userId,
//                        isDemonstrate
//                    )
//                    mViewModel.getXlData(2, binding.tvShowDate.text.toString(), id)
                    // 点击确定按钮的操作
                    dialog.dismiss()
                }
            }
        }
    }

    /**
     * 设置demo时间
     */
    @SuppressLint("SimpleDateFormat", "SetTextI18n")
    private fun setDemoMoth() {
        val cal = Calendar.getInstance()
        val selectTime = binding.mTime.text
        val format = SimpleDateFormat("yyyy-MM")
        cal.time = format.parse(selectTime.toString())!!
        val month = cal.get(Calendar.MONTH) + 1
        val lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH)

        val monthStr = if (month < 10) {
            "0$month"
        } else {
            month.toString()
        }
        val lastStr = if (lastDay < 10) {
            "0$lastDay"
        } else {
            lastDay.toString()
        }
        binding.tvStart.text = "$monthStr-01"
        binding.tvEnd.text = "$monthStr-$lastStr"
    }

    private fun changeTopShape(color: Int, textView: TextView) {
        val drawable = ContextCompat.getDrawable(this, R.drawable.shape_dot_481)
        val gradientDrawable = drawable as GradientDrawable
        gradientDrawable.setColor(ContextCompat.getColor(this, color))
        drawable.mutate()
        drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
        textView.setCompoundDrawables(drawable, null, null, null)
    }

    private fun initHealthTrendTime() {
        var total: Int = when (index) {
            ReportVm.ReportInfoType.Week, ReportVm.ReportInfoType.Month -> 6
            ReportVm.ReportInfoType.Year -> 10
            else -> 1
        }
        // 如果是近30天，也只显示开始和结束时间
        if (isNearMouth) {
            total = 8
        }
        for (i in 0..total) {
            val lp: LinearLayout.LayoutParams =
                LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT)
            lp.weight = 1f
            lp.gravity = Gravity.CENTER
            organTimeTvArray.add(getTimeTextView(binding.child.mOrganHealthTime, lp))
        }
        for (i in 0..total) {
            val lp: LinearLayout.LayoutParams =
                LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT)
            lp.weight = 1f
            lp.gravity = Gravity.CENTER
            healthTimeTvArray.add(getTimeTextView(binding.mLinTime, lp))
        }
    }

    private fun getTimeTextView(parent: ViewGroup, lp: LinearLayout.LayoutParams): TextView {
        val textView = TextView(this)
        textView.setTextColor(ContextCompat.getColor(this, R.color.col_313))
        textView.textSize = 12f
        textView.gravity = Gravity.CENTER
        parent.addView(textView, lp)
        return textView
    }

    @SuppressLint("SimpleDateFormat")
    private 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()
        val currentMonday = startDate.clone() as Calendar
        currentMonday.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY)

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

            // Exclude current week
            if (currentSunday.after(Calendar.getInstance())) {
                break
            }
            val formattedDateRange =
                SimpleDateFormat("yyyy-MM-dd").format(currentMonday.time) + "至" + SimpleDateFormat(
                    "yyyy-MM-dd"
                ).format(
                    currentSunday.time
                )
            dateRanges.add(formattedDateRange)

            currentMonday.add(Calendar.WEEK_OF_YEAR, 1)
        }

        dateRanges.reverse()
        return dateRanges
    }

    /**
     * 睡眠颜色配置
     */
    private fun setSleepBg(color: Int, textView: TextView) {
        val drawable = ContextCompat.getDrawable(this, R.drawable.shape_status)
        val gradientDrawable = drawable as GradientDrawable
        gradientDrawable.setColor(ContextCompat.getColor(this, color))
        drawable.mutate()
        drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
        textView.setCompoundDrawables(drawable, null, null, null)
    }

    @SuppressLint("SetTextI18n", "SimpleDateFormat")
    override fun liveObserver() {
        mViewModel.exceptionUricAcidData.observe(this) {
            val mData1 = arrayListOf<String>()
            val mTime1 = arrayListOf<String>()

            it.data.high.forEach { data ->
                mData1.add(data.data.toString())
                mTime1.add(data.time)
            }

            bundle.clear()
            bundle.putString("sex", sex)
            bundle.putString(BaseExceptionDataAct.exceptionKey, "尿酸异常数据")
            bundle.putStringArrayList(BaseExceptionDataAct.exceptionList, mData1)
            bundle.putStringArrayList(BaseExceptionDataAct.exceptionListTime, mTime1)
            RouteManager.goAct(ARouterUrl.URIC_ACID_EXCEPTION_DATA_ACT, bundle)
        }

        mViewModel.infoLive.observe(this) {
            if (it.data == null) {
                CommonToastUtils.showToast("无当前时间的数据")
                return@observe
            }
            user = it.data.user
            if (index == ReportVm.ReportInfoType.Year) {
                if (isDemonstrate) {  //演示模式
                    it.data.healthTrend = it.data.fillDemoChildStatusList(
                        binding.mTime.text.toString(),
                        it.data.healthTrend
                    )
                } else {
                    it.data.healthTrend =
                        it.data.fillChildStatusList(
                            binding.mTime.text.toString(),
                            it.data.healthTrend
                        )
                }
            }

            val sbMedical = java.lang.StringBuilder()
            if (!it.data.user.historyName.isNullOrEmpty()) {
                sbMedical.append(it.data.user.historyName).append(",")
            }
            if (!it.data.user.tumour.isNullOrEmpty()) {
                sbMedical.append(it.data.user.tumour).append(",")
            }
            if (!it.data.user.other.isNullOrEmpty()) {
                sbMedical.append(it.data.user.other).append(",")
            }
            if (sbMedical.toString().isNotEmpty()) {
                val mecid = sbMedical.toString()
                binding.mTvDis.text = mecid.substring(0, mecid.length - 1)
            }
           // addClickableText(binding.mTvDis)

            binding.mImage.setImageUser(this, it.data.user.avatarUrl, it.data.user.sex)
            binding.mName.text = it.data.user.name
            val sexim =
                String.format(UserInfoDefin.getSexArray(this)[it.data.user.sex.toInt() - 1])
            sex = if ("男" == sexim) {
                binding.icMale.setImageResource(R.mipmap.ic_male_1)
                "1"
            } else {
                binding.icMale.setImageResource(R.mipmap.ic_female_1)
                "2"
            }

            setHealthStatuAndStarInfo(it)

            val ageHtml = String.format(getString(R.string.info_msg), "年龄", it.data.user.age)
            binding.mAge.text = Html.fromHtml(ageHtml + "岁")
            val heightHtml =
                String.format(
                    getString(R.string.info_msg),
                    "身高",
                    "${String.format("%.1f", it.data.user.height)}cm"
                )
            binding.mHeight.text = Html.fromHtml(heightHtml)
            val weightHtml =
                String.format(getString(R.string.info_msg), "体重", "${it.data.user.weight}kg")
            binding.mWeight.text = Html.fromHtml(weightHtml)

            setHealthStatuAndStarInfo(it)

            setAnalysisInfo(it)

            xiyiList.clear()
            mTitless.clear()
//            mTitless.add("用户信息")
//            mTitless.add("健康状态趋势")
            mTitless.add("器官功能分析")
            xiyiList.add(setAnaList(it.data.analysis.TcmAnalysis!!, "中医分析"))
            mTitless.add("中医分析")
            xiyiList.add(setAnaList(it.data.analysis.tcm!!, "中医养生指导"))
//            mTitless.add("中医养生指导")
            xiyiList.add(setAnaList(it.data.analysis.WmAnalysis!!, "西医分析"))
            mTitless.add("西医分析")
            if (!it.data.analysis.WmAnalysis.isNullOrEmpty()) {
                xiyiList.add(setAnaList(it.data.analysis.wm!!, "西医指导"))
//                mTitless.add("西医指导")
            }
            xiyiList.add(setAnaList(it.data.analysis.diet!!, "饮食指导"))
            mTitless.add("饮食指导")
            xiyiList.add(setAnaList(it.data.analysis.exercise!!, "运动指导"))
            mTitless.add("运动指导")
            if (!it.data.analysis.sleep.isNullOrEmpty()) {
                xiyiList.add(setAnaList(it.data.analysis.sleep!!, "睡眠方案建议"))
                mTitless.add("睡眠方案建议")
            } else {
                xiyiList.add(setAnaList(arrayListOf(), "睡眠方案建议"))
                mTitless.add("睡眠方案建议")
            }
            xiyiList.add(setAnaList(it.data.analysis.nutrition!!, "营养处方建议"))
            mTitless.add("营养处方建议")
            mTitless.add("统计分析")
            mTitless.add("综合分析")
            //设置tab
            mTitless.forEach { tabData ->
                val tab = binding.xTablayout.newTab()
                tab.text = tabData
                binding.xTablayout.addTab(tab)
            }

            mAnasylsAdapter.setNewInstance(xiyiList)

            it.data.statistical?.let { statisticalData ->
                statisticalData.forEachIndexed { index, statistical ->
                    if (statistical.start_time > 0) {
                        list.add(
                            BarEntry(
                                index.toFloat(),
                                floatArrayOf(statistical.min.toFloat(), statistical.max.toFloat()),
                                statistical.start_time
                            )
                        )
                    }
                }
            }

            initBarChart()

            binding.sleepMeasure.mDayAll.text = "${it.data.statistical!![0].count}"
            binding.sleepMeasure.DayMAx.text = "最大值${it.data.statistical!![0].max}"
            binding.sleepMeasure.DayMin.text = "最小值${it.data.statistical!![0].max}"
            binding.sleepMeasure.DayMin.text = "最小值${it.data.statistical!![0].max}"
            binding.sleepMeasure.mDayMaxTime.text = RxTimeTool.milliseconds2String(
                it.data.statistical!![0].maxStartTime * 1000,
                SimpleDateFormat("MM-dd")
            )
            binding.sleepMeasure.mDayMinTime.text = RxTimeTool.milliseconds2String(
                it.data.statistical!![0].minStartTime * 1000,
                SimpleDateFormat("MM-dd")
            )

            binding.sleepMeasure.mNightAll.text = "${it.data.statistical!![1].count}"
            binding.sleepMeasure.NightMAx.text = "最大值${it.data.statistical!![1].max}"
            binding.sleepMeasure.NightMin.text = "最小值${it.data.statistical!![1].max}"
            binding.sleepMeasure.mNightMax.text = RxTimeTool.milliseconds2String(
                it.data.statistical!![1].maxStartTime * 1000,
                SimpleDateFormat("MM-dd")
            )
            binding.sleepMeasure.mNightMin.text = RxTimeTool.milliseconds2String(
                it.data.statistical!![1].maxStartTime * 1000,
                SimpleDateFormat("MM-dd")
            )

            binding.sleepMeasure.mAllMeasure.text = "共测量${it.data.statistical!![2].count}次"
            binding.sleepMeasure.mEffMeasure.text =
                "有效测量${it.data.statistical!![2].validCount}次"

            setStatus(it)
            initProgress(it.data.healthTrend, it.data.healthTotal)

            //分析依据
            //基础信息
            listInfo.clear()
            val bsseInfo = it.data.signData
            listInfo.add(
                com.xty.network.model.ReportBean.HrInfo(
                    "心率",
                    bsseInfo.hr.avg,
                    bsseInfo.hr.min,
                    bsseInfo.hr.max,
                    bsseInfo.hr.count,
                    "",
                    R.mipmap.xl_small
                )
            )
            listInfo.add(
                com.xty.network.model.ReportBean.HrInfo(
                    "血氧",
                    bsseInfo.so.avg,
                    bsseInfo.so.min,
                    bsseInfo.so.max,
                    bsseInfo.so.count,
                    "",
                    R.mipmap.xy_small
                )
            )
            listInfo.add(
                com.xty.network.model.ReportBean.HrInfo(
                    "呼吸率",
                    string2IntStr(bsseInfo.respiratory.avg),
                    string2IntStr(bsseInfo.respiratory.min),
                    string2IntStr(bsseInfo.respiratory.max),
                    string2IntStr(bsseInfo.respiratory.count),
                    "",
                    R.mipmap.hxl_small
                )
            )

            if (DeviceFunctionUtils.hasFunction(functionList,"temp") || isDemonstrate) {  //如果是演示模式都要显示体温
                listInfo.add(
                    com.xty.network.model.ReportBean.HrInfo(
                        "体温",
                        setavq(bsseInfo.temp.avg),
                        bsseInfo.temp.min,
                        bsseInfo.temp.max,
                        bsseInfo.temp.count,
                        "",
                        R.mipmap.tw_small
                    )
                )
            }

            listInfo.add(
                com.xty.network.model.ReportBean.HrInfo(
                    "运动",
                    bsseInfo.stepData.avg,
                    bsseInfo.stepData.min,
                    bsseInfo.stepData.max,
                    bsseInfo.stepData.count,
                    bsseInfo.step.step,
                    R.mipmap.step_small
                )
            )
            listInfo.add(
                com.xty.network.model.ReportBean.HrInfo(
                    "睡眠",
                    "",
                    "",
                    "",
                    bsseInfo.sleep.count,
                    "",
                    R.mipmap.ic_report_sleep,
                    avgLight = bsseInfo.sleep.avgLight,
                    maxTime = bsseInfo.sleep.maxTime,
                    avgTime = bsseInfo.sleep.avgTime,
                    minTime = bsseInfo.sleep.minTime,
                    avgDeep = bsseInfo.sleep.avgDeep,
                    sleepDuration = index.reportType
                )
            )
            listInfo.add(
                com.xty.network.model.ReportBean.HrInfo(
                    "血压",
                    bsseInfo.dbp.avg,
                    bsseInfo.dbp.min,
                    bsseInfo.dbp.max,
                    bsseInfo.dbp.count,
                    "",
                    R.mipmap.xya_small
                )
            )
            listInfo.add(
                com.xty.network.model.ReportBean.HrInfo(
                    "血糖",
                    setavq(bsseInfo.bloodSugar.avg),
                    setavq(bsseInfo.bloodSugar.min),
                    setavq(bsseInfo.bloodSugar.max),
                    setavq(bsseInfo.bloodSugar.count),
                    "",
                    R.mipmap.xt_small
                )
            )

            if (bsseInfo.uricAcid == null) {
                listInfo.add(
                    com.xty.network.model.ReportBean.HrInfo(
                        "尿酸",
                        "36",
                        "21",
                        "46",
                        "1",
                        "",
                        R.mipmap.ic_uric_acid_small
                    )
                )

            } else {
                listInfo.add(
                    com.xty.network.model.ReportBean.HrInfo(
                        "尿酸",
                        bsseInfo.uricAcid.avg,
                        bsseInfo.uricAcid.min,
                        bsseInfo.uricAcid.max,
                        bsseInfo.uricAcid.count,
                        "",
                        R.mipmap.ic_uric_acid_small
                    )
                )
            }

            if(bsseInfo.bloodFat == null){
                listInfo.add(
                    com.xty.network.model.ReportBean.HrInfo(
                        "血脂",
                        "0",
                        "0",
                        "0",
                        "1",
                        "",
                        R.mipmap.ic_uric_acid_small
                    )
                )

            }else{
                listInfo.add(
                    com.xty.network.model.ReportBean.HrInfo(
                        "血脂",
                        "0",
                        "0",
                        "0",
                        "${bsseInfo.bloodFat.count}",
                        "",
                        R.mipmap.ic_uric_acid_small
                    )
                )
            }

            infoAdapter.setNewInstance(listInfo)

            mViewModel.getReportAvgNew(
                index.reportType,
                binding.mTime.text.toString(),
                userId,
                isDemonstrate
            )
        }

        //换图数据
        mViewModel.avgLive.observe(this) {
            val list = mutableListOf<ReportBean>()

            val hr = ReportBean().apply {
                title = "心率"
                count = it.data.hrMean.count
                listNum.add(it.data.hrMean.normal)
                listNum.add(it.data.hrMean.bradycardia)
                listNum.add(it.data.hrMean.tachycardia)
                listName.add("正常")
                listName.add("心动过缓")
                listName.add("心动过速")
                if (listInfo.size > 0) {
                    listInfo.forEach { synthesize ->
                        if (synthesize.name == "心率") {
                            synthesizeList = synthesize
                        }
                    }
                }
                isShow = true
            }
            list.add(hr)

            val soMean = ReportBean().apply {
                title = "血氧"
                count = it.data.soMean.count
                listNum.add(it.data.soMean.normal)
                listNum.add(it.data.soMean.deficiency)
                listNum.add(it.data.soMean.hyoxemia)
                listName.add("正常")
                listName.add("供氧不足")
                listName.add("低血氧")
                if (listInfo.size > 0) {
                    listInfo.forEach { synthesize ->
                        if (synthesize.name == "血氧") {
                            synthesizeList = synthesize
                        }
                    }
                }
                isShow = true
            }
            list.add(soMean)

            val respiratoryMean = ReportBean().apply {
                title = "呼吸率"
                count = it.data.respiratoryMean.count
                listNum.add(it.data.respiratoryMean.normal)
                listNum.add(it.data.respiratoryMean.oligopnea)
                listNum.add(it.data.respiratoryMean.tachypnea)
                listName.add("正常")
                listName.add("呼吸过缓")
                listName.add("呼吸过速")
                if (listInfo.size > 0) {
                    listInfo.forEach { synthesize ->
                        if (synthesize.name == "呼吸率") {
                            synthesizeList = synthesize
                        }
                    }
                }
                isShow = true
            }
            list.add(respiratoryMean)

            if (DeviceFunctionUtils.hasFunction(functionList,"temp") || isDemonstrate) {
                val tempMean = ReportBean().apply {
                    title = "体温"
                    count = it.data.tempMean.count
                    listNum.add(it.data.tempMean.normal)
                    listNum.add(it.data.tempMean.centre)
                    listNum.add(it.data.tempMean.low)
                    listNum.add(it.data.tempMean.tall)
                    listNum.add(it.data.tempMean.ultrahyperpyexia)
                    listName.add("正常")
                    listName.add("中热")
                    listName.add("低热")
                    listName.add("高热")
                    listName.add("超高热")
                    if (listInfo.size > 0) {
                        listInfo.forEach { synthesize ->
                            if (synthesize.name == "体温") {
                                synthesizeList = synthesize
                            }
                        }
                    }
                    isShow = true
                }
                list.add(tempMean)
            }

            val dbMean = ReportBean().apply {
                title = "血压"
                count = it.data.dbMean.count
                listNum.add(it.data.dbMean.normal)
                listNum.add(it.data.dbMean.hypotension)
                listNum.add(it.data.dbMean.first)
                listNum.add(it.data.dbMean.two)
                listNum.add(it.data.dbMean.three)
                listName.add("正常")
                listName.add("低血压")
                listName.add("一级高血压")
                listName.add("二级高血压")
                listName.add("三级高血压")
                if (listInfo.size > 0) {
                    listInfo.forEach { synthesize ->
                        if (synthesize.name == "血压") {
                            synthesizeList = synthesize
                        }
                    }
                }
                isShow = true
            }
            list.add(dbMean)

            if (it.data.bloodsugar.count != 0) {
                val bloodsugar = ReportBean().apply {
                    title = "血糖"
                    count = it.data.bloodsugar.count
                    listNum.add(it.data.bloodsugar.bloodsugarNormal)
                    listNum.add(it.data.bloodsugar.bloodsugarHigh)
                    listNum.add(it.data.bloodsugar.bloodsugarLow)
                    listName.add("正常")
                    listName.add("血糖过高")
                    listName.add("血糖过低")
                    if (listInfo.size > 0) {
                        listInfo.forEach { synthesize ->
                            if (synthesize.name == "血糖") {
                                synthesizeList = synthesize
                            }
                        }
                    }
                    isShow = true
                }
                list.add(bloodsugar)
            } else {
                val bloodsugar = ReportBean().apply {
                    title = "血糖"
                    count = 0
                    listNum.add(0)
                    listNum.add(0)
                    listNum.add(0)
                    listName.add("正常")
                    listName.add("血糖过高")
                    listName.add("血糖过低")
                    if (listInfo.size > 0) {
                        listInfo.forEach { synthesize ->
                            if (synthesize.name == "血糖") {
                                synthesizeList = synthesize
                            }
                        }
                    }
                    isShow = true
                }
                list.add(bloodsugar)
            }

            val uricAcid = if (it.data.uricAcid == null) {
                ReportBean().apply {
                    title = "尿酸"
                    count = 1
                    listNum.add(1)
                    listNum.add(1)

                    listName.add("正常")
                    listName.add("高尿酸")
                    if (listInfo.size > 0) {
                        listInfo.forEach { synthesize ->
                            if (synthesize.name == "尿酸") {
                                synthesizeList = synthesize
                            }
                        }
                    }
                    isShow = true
                }
            } else {
                ReportBean().apply {
                    title = "尿酸"
                    count = it.data.uricAcid.count
                    listNum.add(it.data.uricAcid.normal)
                    listNum.add(it.data.uricAcid.high)

                    listName.add("正常")
                    listName.add("高尿酸")
                    if (listInfo.size > 0) {
                        listInfo.forEach { synthesize ->
                            if (synthesize.name == "尿酸") {
                                synthesizeList = synthesize
                            }
                        }
                    }
                    isShow = true
                }
            }
            list.add(uricAcid)

            val bloodFat = if (it.data.bloodFat == null) {  //服务端没有返回数据
               ReportBean().apply {
                    title = "血脂"
                    count = 1
                    listNum.add(1)
                    listNum.add(1)

                    listName.add("正常")
                    listName.add("异常")
                    if (listInfo.size > 0) {
                        listInfo.forEach { synthesize ->
                            if (synthesize.name == "血脂") {
                                synthesizeList = synthesize
                            }
                        }
                    }
                    isShow = true
                }
            } else {
                ReportBean().apply {
                    title = "血脂"
                    count = it.data.bloodFat.count
                    listNum.add(it.data.bloodFat.normal)
                    listNum.add(it.data.bloodFat.abnormal)

                    listName.add("正常")
                    listName.add("异常")
                    if (listInfo.size > 0) {
                        listInfo.forEach { synthesize ->
                            if (synthesize.name == "血脂") {
                                synthesizeList = synthesize
                            }
                        }
                    }
                    isShow = true
                }
            }
            list.add(bloodFat)

            val yundong = ReportBean().apply {
                title = "运动"
                if (listInfo.size > 0) {
                    listInfo.forEach { synthesize ->
                        if (synthesize.name == "运动") {
                            synthesizeList = synthesize
                        }
                    }
                }
                isShow = false
            }
            list.add(yundong)

            val shuimian = ReportBean().apply {
                title = "睡眠"
                if (listInfo.size > 0) {
                    listInfo.forEach { synthesize ->
                        if (synthesize.name == "睡眠") {
                            synthesizeList = synthesize
                        }
                    }
                }
                isShow = false
            }
            list.add(shuimian)

            mAdapter.setNewInstance(list)
            mAdapter.addChildClickViewIds(R.id.tvInto)
            mAdapter.setOnItemChildClickListener { adapter, view, position ->
                when (list[position].title) {
                    "心率" -> {
                        goExceptionActivity(Const.xlHeartRate)
                    }

                    "血氧" -> {
                        goExceptionActivity(Const.xyBloodOxygen)
                    }

                    "呼吸率" -> {
                        goExceptionActivity(Const.hxlBreathingRate)
                    }

                    "体温" -> {
                        goExceptionActivity(Const.twTemperature)
                    }

                    "血压" -> {
                        goExceptionActivity(Const.xyBloodPressure)
                    }

                    "尿酸" -> {
                        if (isDemonstrate) {
                            dialogBind.show()
                            return@setOnItemChildClickListener
                        }

                        val type = when (index) {
                            ReportVm.ReportInfoType.Week -> {
                                "2"
                            }
                            ReportVm.ReportInfoType.Month -> {
                                "3"
                            }
                            ReportVm.ReportInfoType.Year -> {
                                "4"
                            }
                            else -> {
                                "1"
                            }
                        }
                        mViewModel.getWatchAbnormalDataUricAcid(
                            userId,
                            type,
                            binding.mTime.text.toString(),
                            "9"
                        )
                    }

                    "血脂" ->{
                        goExceptionActivity(Const.bloodFatExcep)
                    }

                    else -> {}
                }
            }
        }

        //分享记录返回方法
        mViewModel.shareLive.observe(this) {
            if (it.code == 0) {
                EventBus.getDefault().post(IntegralEvent())
                share()
            } else {
                CommonToastUtils.showToast("分享记录失败")
            }
        }

        mViewModel.functionLiveData.observe(this){
            functionList.addAll(it.data)
        }
    }

    private fun goExceptionActivity(exceptionType: Int) {
        if (isDemonstrate) {
            dialogBind.show()
            return
        }
        bundle.clear()
        bundle.putString("id", userId)
        bundle.putInt("timeType", index.reportType)
        bundle.putString("time", binding.mTime.text.toString())
        bundle.putInt("exceptionType", exceptionType)
        RouteManager.goAct(ARouterUrl.ALL_EXCEPTION_DATA_ACT, bundle)
    }

    /**
     * String 类型去除小数点
     */
    private fun string2IntStr(str: String): String {
        if (str.isNullOrEmpty()) {
            return ""
        }
        return str.toDouble().toInt().toString()
    }

    /**
     * 四舍五入
     * */
    private fun setavq(str: String): String {
        var num = BigDecimal(str)
        num = num.setScale(1, BigDecimal.ROUND_HALF_UP)
        return num.toString()
    }

    /**
     * 加载趋势
     */
    private fun initProgress(
        list: List<com.xty.network.model.ReportBean.ChildStatus>,
        totals: List<com.xty.network.model.ReportBean.totalBean>
    ) {
        val ednIndex = if (index == ReportVm.ReportInfoType.Year) {
            7
        } else {
            10
        }
        //  status_0">数据不足
        //  status_1">健康
        //  status_2">亚健康
        //  status_3">疾病
        //  status_4">建模中
        var zhengchang = 0
        var yajiankan = 0
        var jibing = 0
        var jianmozhi = 0
        var shujubuzu = 0
        totals.forEach {
            when (it.result) {
                //-1 建模中 0数据不足 1健康 2亚健康 3疾病
                -1 -> {
                    //建模中
                    jianmozhi = it.count
                }

                0 -> {
                    shujubuzu = it.count
                }

                1 -> {
                    zhengchang = it.count
                }

                2 -> {
                    yajiankan = it.count
                }

                3 -> {
                    jibing = it.count
                }

                else -> {}
            }
        }
        setnum(shujubuzu, binding.numTv0)
        setnum(zhengchang, binding.numTv1)
        setnum(yajiankan, binding.numTv2)
        setnum(jibing, binding.numTv3)
        setnum(jianmozhi, binding.numTv4)

        binding.mDayStatus.setData(
            list as MutableList<com.xty.network.model.ReportBean.ChildStatus>,
            ednIndex
        )
        if (!isDemonstrate) {
            binding.mLinTime.visibility = if (list.isEmpty()) View.GONE else View.VISIBLE
        }
        showHealthTrendTime(ednIndex, list, healthTimeTvArray)
    }

    private fun setnum(num: Int, textView: TextView) {
        textView.text = num.toString()
    }

    /**
     * 添加属性
     */
    private fun addClickableText(textView: TextView) {
        val originalText = textView.text.toString() + "  "
        val clickableText = "点击查看"
        val textColor = ContextCompat.getColor(this, R.color.col_02c)
        val spannableString = SpannableString("$originalText$clickableText")
        // 设置点击事件
        val clickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                if (isDemonstrate) {
                    dialogBind.show()
                    return
                }
                // 在这里实现点击事件的逻辑
                // 例如打开一个新的界面或执行某些操作
                if (user != null) {
                    val array = JSONArray()
                    user!!.diseaseList.forEach {
                        val json = JSONObject()
                        json.put("name", it.name)
                        json.put("type", it.type)
                        json.put("time", it.time)
                        array.put(json)
                    }
                    val diseaseList = array.toString()
                    bundle.clear()
                    bundle.putString("ids", user!!.historyId)
                    bundle.putString("other", user!!.other)
                    bundle.putString("tumour", user!!.tumour)

                    bundle.putString("arrays", diseaseList)
                    bundle.putString("historyName", user!!.historyName)
                    RouteManager.goAct(ARouterUrl.MEDICAL_HISTORY, bundle)
                }
            }
        }
        spannableString.setSpan(
            clickableSpan,
            originalText.length,
            spannableString.length,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        // 设置颜色
        val colorSpan = ForegroundColorSpan(textColor)
        spannableString.setSpan(
            colorSpan,
            originalText.length,
            spannableString.length,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )

        // 设置下划线
        val underlineSpan = UnderlineSpan()
        spannableString.setSpan(
            underlineSpan,
            originalText.length,
            spannableString.length,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )

        textView.text = spannableString
        textView.movementMethod = android.text.method.LinkMovementMethod.getInstance()
    }

    /**
     * 设置健康状态以及星级评价
     */
    @SuppressLint("UseCompatLoadingForDrawables")
    private fun setHealthStatuAndStarInfo(it: RespBody<com.xty.network.model.ReportBean>) {
        binding.mTvcValue.apply {
            val statusInt = it.data.analyse.status.toInt()
            val star = if (it.data.star.isEmpty()) 0 else Integer.valueOf(it.data.star)

            text = UserInfoDefin.getHealthArray(context)[statusInt + 1]
            setTextColor(
                ContextCompat.getColor(
                    context,
                    UserInfoDefin.healthCol[statusInt + 1]
                )
            )

            append("\t\t")

            val selectStarImage = UserInfoDefin.getStarImage(context, statusInt)
            selectStarImage.setBounds(
                0,
                0,
                selectStarImage.minimumWidth,
                selectStarImage.minimumHeight
            )

            val unSelectStarImage = context.getDrawable(R.mipmap.icon_insufficient)
            unSelectStarImage?.setBounds(
                0,
                0,
                unSelectStarImage.minimumWidth,
                unSelectStarImage.minimumHeight
            )

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

            setOnClickListener {
                tipDialog.show()
            }
        }
        binding.mTvStatus.apply {
            setOnClickListener {
                tipDialog.show()
            }
        }
    }

    /**
     * 设置综合分析内容
     */
    @SuppressLint("SetTextI18n", "UseCompatLoadingForDrawables")
    private fun setAnalysisInfo(it: RespBody<com.xty.network.model.ReportBean>) {
        val analyse = it.data.analyse
        if (analyse != null) {
            var sleep = analyse.sleep
            if (TextUtils.isEmpty(sleep)) {
                sleep = "--小时"
            }
            val list = mutableListOf<String>()
            list.add("平均心率: ${analyse.hr}")
            list.add("平均血氧: ${analyse.so}")
            list.add("平均呼吸率: ${analyse.respiratory}")
            if (DeviceFunctionUtils.hasFunction(functionList, "temp")) {
                val tempAvg = it.data.signData.temp.avg.toFloat()
                list.add(
                    "平均体温: ${
                        if (tempAvg > 0) {
                            tempAvg
                        } else {
                            "--"
                        }
                    }"
                )
            }
            list.add("平均步数: ${analyse.exerciseStep}")
            list.add("平均睡眠时间: $sleep")
            list.add("平均血压: ${analyse.dbp}")
            list.add("平均血糖: ${analyse.bloodsugar}")
            list.add("平均尿酸: ${analyse.uricAcid}")
            list.add("平均总胆固醇: ${analyse.tc}")
            list.add("平均甘油三酯: ${analyse.tg}")
            list.add("平均高密度脂蛋白: ${analyse.hdl}")
            list.add("平均低密度脂蛋白: ${analyse.ldl}")
            signDataList.clear()
            signDataGriddingList.clear()
            if (list.isNotEmpty()) {
                list.forEachIndexed { index, data ->
                    if (index < 8) {
                        signDataGriddingList.add(data)
                    } else {
                        signDataList.add(data)
                    }
                }
                if (signDataGriddingList.size > 0) {
                    binding.recyclerViewGridding.visibility = View.VISIBLE
                    healthSignDataGriddingAdapter.setNewInstance(signDataGriddingList)
                }
                if (signDataList.size > 0) {
                    binding.recyclerViewList.visibility = View.VISIBLE
                    healthSignDataAdapter.setNewInstance(signDataList)
                }
            } else {
                binding.recyclerViewGridding.visibility = View.GONE
                binding.recyclerViewList.visibility = View.GONE
            }
            /*binding.analysisTv1.text = "平均心率: " + it.data.analyse.hr
        binding.analysisTv2.text = "平均血氧: " + it.data.analyse.so
        binding.analysisTv3.text = "平均呼吸率: " + it.data.analyse.respiratory
        if (!DeviceFunctionUtils.hasFunction(functionList,"temp")) {
            binding.analysisTv8.visibility = View.GONE
        } else {
            binding.analysisTv8.text =
                "平均体温: " + CommonUtils.stringToDoubleOne(it.data.signData.temp.avg) + "°C"
        }
        if (!TextUtils.isEmpty(it.data.signData.uricAcid.avg)) {
            binding.analysisTv4.text = "平均尿酸：${it.data.signData.uricAcid.avg}μmol/L"
        } else {
            binding.analysisTv4.text = "平均尿酸：0μmol/L"
        }
        binding.analysisTv5.text = "平均步数: " + it.data.analyse.exerciseStep
        binding.analysisTv6.text = "平均睡眠: $sleep"
        binding.analysisTv7.text = "平均血压: " + it.data.analyse.dbp*/

            /* if(!TextUtils.isEmpty(it.data.signData.bloodFat.tgAvg)){
            binding.analysisTv9.text = "平均血脂：" + it.data.signData.bloodFat.tgAvg + "mmol"

        }else{
            binding.analysisTv9.text = "平均血脂：0mmol"

        }*/
            binding.state.apply {
                val statusInt = analyse.status.toInt()
                val star = if (it.data.star.isEmpty()) 0 else Integer.valueOf(it.data.star)
                text = UserInfoDefin.getHealthArray(context)[statusInt + 1]
                setTextColor(
                    ContextCompat.getColor(
                        context,
                        UserInfoDefin.healthCol[statusInt + 1]
                    )
                )
                append("\t")
                val selectStarImage = UserInfoDefin.getStarImage(context, statusInt)
                selectStarImage.setBounds(
                    0,
                    0,
                    selectStarImage.minimumWidth,
                    selectStarImage.minimumHeight
                )

                val unSelectStarImage = context.getDrawable(R.mipmap.icon_insufficient)
                unSelectStarImage?.setBounds(
                    0,
                    0,
                    unSelectStarImage.minimumWidth,
                    unSelectStarImage.minimumHeight
                )

                for (i in 1..5) {//五颗星
                    val spanStr = SpannableString("custom$i ")
                    val span =
                        (if (star >= i) selectStarImage else unSelectStarImage)?.let { starDrawable ->
                            CenterImageSpan(starDrawable)
                        }
                    spanStr.setSpan(span, 0, spanStr.length - 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
                    //添加至textview
                    append(spanStr)
                }
                setOnClickListener {
                    tipDialog.show()
                }
            }
            binding.tipsIcon.apply {
                setOnClickListener {
                    tipDialog.show()
                }
            }
        }
    }

    /**
     * 组装 数据
     */
    private fun setAnaList(
        data: List<com.xty.network.model.ReportBean.Content>,
        name: String
    ): MyReportBean {
        val bean = MyReportBean()
        val sb = StringBuffer()
        bean.name = name
        if (data.isEmpty()) {
            bean.content = "身体健康，请继续保持"
        } else {
            when (bean.name) {
                "西医分析" -> {
                    data.forEachIndexed { _, beanData ->
                        if (beanData.dictName != "考虑症状") {
                            sb.append(
                                String.format(
                                    getString(R.string.analysis_desc),
                                    beanData.dictName,
                                    beanData.name
                                )
                            ).append("\n")
                            sb.append(
                                String.format(
                                    getString(R.string.analysis_name),
                                    beanData.name
                                )
                            )
                                .append("\n")
                            sb.append(beanData.content).append("\n")
                        }
                    }

                    data.forEachIndexed { _, beanData ->
                        if (beanData.dictName == "考虑症状") {
                            sb.append(
                                String.format(
                                    getString(R.string.analysis_agree),
                                    "${beanData.dictName}${beanData.name}？"
                                )
                            ).append("\n")
                            sb.append(beanData.content).append("\n")
                        }
                    }

                    bean.content = sb.toString().trim()
                }

                "中医分析" -> {
                    data.forEach {
                        sb.append(it.dictName).append("\n")
                        sb.append(it.content).append("\n")
                    }
                    bean.content = sb.toString()
                }

                "中医养生指导" -> {
                    data.forEach {
                        sb.append(it.name).append("</br>")
                        sb.append(it.dictName).append("</br>")
                        sb.append(it.content).append("\n")
                    }
                    bean.content = sb.toString().trim()
                }

                else -> {
                    data.forEach {
                        sb.append(it.name).append("\n")
                        sb.append(it.content).append("\n")
                    }
                    bean.content = sb.toString().trim()
                }
            }

        }

        return bean
    }

    /**
     * 器官分析
     */
    fun setStatus(respBody: RespBody<com.xty.network.model.ReportBean>) {
        //健康状态-1:数据不足 0：健康 1：亚健康 2：疾病 3：建模中
        val statusInt = if (respBody.data.analyse == null) {
            0
        } else {
            respBody.data.analyse.status.toInt()
        }
        val bodyImgResId = if (statusInt == 2) {
            if (mViewModel.infoLive.value!!.data.user.sex == "1") {
                R.mipmap.icon_health_man_2
            } else {
                R.mipmap.icon_health_women_2
            }
        } else if (statusInt == 3) {
            if (mViewModel.infoLive.value!!.data.user.sex == "1") {
                R.mipmap.icon_health_man_3
            } else {
                R.mipmap.icon_health_women_3
            }
        } else if (statusInt == 1) {
            if (mViewModel.infoLive.value!!.data.user.sex == "1") {
                R.mipmap.icon_health_man_1
            } else {
                R.mipmap.icon_health_women_1
            }
        } else {
            if (mViewModel.infoLive.value!!.data.user.sex == "1") {
                R.mipmap.icon_health_man_4
            } else {
                R.mipmap.icon_health_women_4
            }
        }

        binding.child.clBody.imgSexBody.setImageResource(bodyImgResId)

        val organ = mViewModel.infoLive.value!!.data.organ

        var organName = ArrayList<String>()
        var organImg = ArrayList<Int>()
        organName.add("胆经")
        organName.add("肝经")
        organName.add("肺经")
        organName.add("大肠经")
        organName.add("胃经")
        organName.add("脾经")

        organName.add("心经")
        organName.add("小肠经")
        organName.add("膀胱经")
        organName.add("肾经")
        organName.add("心包经")
        organName.add("三焦经")

        organImg.add(UserInfoDefin.gallIcon[getHealthStatus(organ.cholecyst.model)])
        organImg.add(UserInfoDefin.liverIcon[getHealthStatus(organ.liver.model)])
        organImg.add(UserInfoDefin.lungIcon[getHealthStatus(organ.lungs.model)])
        organImg.add(UserInfoDefin.largeIcon[getHealthStatus(organ.largeIntestine.model)])
        organImg.add(UserInfoDefin.stomachIcon[getHealthStatus(organ.stomach.model)])
        organImg.add(UserInfoDefin.spleenIcon[getHealthStatus(organ.spleen.model)])
        organImg.add(UserInfoDefin.heartIcon[getHealthStatus(organ.heart.model)])

        organImg.add(UserInfoDefin.smallIcon[getHealthStatus(organ.smallIntestine.model)])
        organImg.add(UserInfoDefin.bladderIcon[getHealthStatus(organ.bladder.model)])
        organImg.add(UserInfoDefin.kidneyIcon[getHealthStatus(organ.kidney.model)])

        organImg.add(UserInfoDefin.pericardiumIcon[getHealthStatus(organ.pericardium.model)])
        organImg.add(UserInfoDefin.lymphIcon[getHealthStatus(organ.lymph.model)])
        binding.child.clBody.healthBody.setOnClicklisteners(object : HealthBodyView.onItemClicked{

            override fun onPositionClicked(postion: Int) {
                LogUtils.e("healthBody","view:${postion}")
                when(postion){
                    0 ->{
                        refreshOrganHealthView(
                            organ.cholecyst.model,
                            binding.child.mGallbladder.viscera,
                            UserInfoDefin.gallIcon,
                            organ.cholecystListData
                        )
                    }

                    1->{
                        refreshOrganHealthView(
                            organ.liver.model,
                            binding.child.mLiver.viscera,
                            UserInfoDefin.liverIcon,
                            organ.liverListData
                        )
                    }

                    2->{
                        refreshOrganHealthView(
                            organ.lungs.model,
                            binding.child.mLung.viscera,
                            UserInfoDefin.lungIcon,
                            organ.lungsListData
                        )
                    }

                    3->{
                        refreshOrganHealthView(
                            organ.largeIntestine.model,
                            binding.child.mLarge.viscera,
                            UserInfoDefin.largeIcon,
                            organ.largeIntestineListData
                        )
                    }

                    4->{
                        refreshOrganHealthView(
                            organ.stomach.model,
                            binding.child.mStomach.viscera,
                            UserInfoDefin.stomachIcon,
                            organ.stomachListData
                        )
                    }

                    5->{
                        refreshOrganHealthView(
                            organ.spleen.model,
                            binding.child.mSpleen.viscera,
                            UserInfoDefin.spleenIcon,
                            organ.spleenListData
                        )
                    }
                    6->{
                        refreshOrganHealthView(
                            organ.heart.model,
                            binding.child.mHeart.viscera,
                            UserInfoDefin.heartIcon,
                            organ.heartListData
                        )
                    }

                    7->{
                        refreshOrganHealthView(
                            organ.smallIntestine.model,
                            binding.child.mSmall.viscera,
                            UserInfoDefin.smallIcon,
                            organ.smallIntestineListData
                        )
                    }
                    8->{
                        refreshOrganHealthView(
                            organ.bladder.model,
                            binding.child.mBladder.viscera,
                            UserInfoDefin.bladderIcon,
                            organ.bladderListData
                        )
                    }
                    9->{
                        refreshOrganHealthView(
                            organ.kidney.model,
                            binding.child.mKidney.viscera,
                            UserInfoDefin.kidneyIcon,
                            organ.kidneyListData
                        )
                    }

                    10->{
                        refreshOrganHealthView(
                            organ.pericardium.model,
                            binding.child.mPericardium.viscera,
                            UserInfoDefin.pericardiumIcon,
                            organ.pericardiumListData
                        )
                    }

                    11->{
                        refreshOrganHealthView(
                            organ.lymph.model,
                            binding.child.mLymph.viscera,
                            UserInfoDefin.lymphIcon,
                            organ.lymphListData
                        )
                    }

                }
            }

        })
        binding.child.clBody.healthBody.setMenuItemIconsAndTexts(organImg,organName)
        refreshOrganHealthView(
            organ.cholecyst.model,
            binding.child.mGallbladder.viscera,
            UserInfoDefin.gallIcon,
            organ.cholecystListData
        )
        /*refreshOrganHealthView(
            organ.heart.model,
            binding.child.mHeart.viscera,
            UserInfoDefin.heartIcon,
            organ.heartListData
        )

        //心脏
        binding.child.mHeart.setOrganStatus(
            this,
            getHealthStatus(organ.heart.model),
            UserInfoDefin.heartIcon
        ) {
            refreshOrganHealthView(
                organ.heart.model,
                binding.child.mHeart.viscera,
                UserInfoDefin.heartIcon,
                organ.heartListData
            )
        }
        binding.child.mStomach.setOrganStatus(
            this,
            getHealthStatus(organ.stomach.model),
            UserInfoDefin.stomachIcon
        ) {
            refreshOrganHealthView(
                organ.stomach.model,
                binding.child.mStomach.viscera,
                UserInfoDefin.stomachIcon,
                organ.stomachListData
            )
        }
        binding.child.mLung.setOrganStatus(
            this,
            getHealthStatus(organ.lungs.model),
            UserInfoDefin.lungIcon
        ) {
            refreshOrganHealthView(
                organ.lungs.model,
                binding.child.mLung.viscera,
                UserInfoDefin.lungIcon,
                organ.lungsListData
            )
        }
        binding.child.mKidney.setOrganStatus(
            this,
            getHealthStatus(organ.kidney.model),
            UserInfoDefin.kidneyIcon
        ) {
            refreshOrganHealthView(
                organ.kidney.model,
                binding.child.mKidney.viscera,
                UserInfoDefin.kidneyIcon,
                organ.kidneyListData
            )
        }
        binding.child.mLiver.setOrganStatus(
            this,
            getHealthStatus(organ.liver.model),
            UserInfoDefin.liverIcon
        ) {
            refreshOrganHealthView(
                organ.liver.model,
                binding.child.mLiver.viscera,
                UserInfoDefin.liverIcon,
                organ.liverListData
            )
        }
        binding.child.mSpleen.setOrganStatus(
            this,
            getHealthStatus(organ.spleen.model),
            UserInfoDefin.spleenIcon
        ) {
            refreshOrganHealthView(
                organ.spleen.model,
                binding.child.mSpleen.viscera,
                UserInfoDefin.spleenIcon,
                organ.spleenListData
            )
        }
        binding.child.mLarge.setOrganStatus(
            this,
            getHealthStatus(organ.largeIntestine.model),
            UserInfoDefin.largeIcon
        ) {
            refreshOrganHealthView(
                organ.largeIntestine.model,
                binding.child.mLarge.viscera,
                UserInfoDefin.largeIcon,
                organ.largeIntestineListData
            )
        }
        binding.child.mSmall.setOrganStatus(
            this,
            getHealthStatus(organ.smallIntestine.model),
            UserInfoDefin.smallIcon
        ) {
            refreshOrganHealthView(
                organ.smallIntestine.model,
                binding.child.mSmall.viscera,
                UserInfoDefin.smallIcon,
                organ.smallIntestineListData
            )
        }
        binding.child.mLymph.setOrganStatus(
            this,
            getHealthStatus(organ.lymph.model),
            UserInfoDefin.lymphIcon
        ) {
            refreshOrganHealthView(
                organ.lymph.model,
                binding.child.mLymph.viscera,
                UserInfoDefin.lymphIcon,
                organ.lymphListData
            )
        }
        binding.child.mGallbladder.setOrganStatus(
            this,
            getHealthStatus(organ.cholecyst.model),
            UserInfoDefin.gallIcon
        ) {
            refreshOrganHealthView(
                organ.cholecyst.model,
                binding.child.mGallbladder.viscera,
                UserInfoDefin.gallIcon,
                organ.cholecystListData
            )
        }
        binding.child.mBladder.setOrganStatus(
            this,
            getHealthStatus(organ.bladder.model),
            UserInfoDefin.bladderIcon
        ) {
            refreshOrganHealthView(
                organ.bladder.model,
                binding.child.mBladder.viscera,
                UserInfoDefin.bladderIcon,
                organ.bladderListData
            )
        }
        binding.child.mPericardium.setOrganStatus(
            this,
            getHealthStatus(organ.pericardium.model),
            UserInfoDefin.pericardiumIcon
        ) {
            refreshOrganHealthView(
                organ.pericardium.model,
                binding.child.mPericardium.viscera,
                UserInfoDefin.pericardiumIcon,
                organ.pericardiumListData
            )
        }*/
    }

    private fun refreshOrganHealthView(
        model: com.xty.network.model.ReportBean.ChildStatus,
        viscera: String,
        organIcon: Array<Int>,
        organListData: List<com.xty.network.model.ReportBean.ChildStatus>
    ) {
        binding.child.mOrganView
            .setInfo(
                getHealthStatus(model), organIcon,
                viscera
            )
        binding.child.mOrganView.setTextStyle(
            17f,
            ContextCompat.getColor(
                this,
                UserInfoDefin.healthCol[getHealthStatus(model)]
            )
        )
        initOrganProgress(organListData)
    }

    //获取健康状态
    private fun getHealthStatus(bean: com.xty.network.model.ReportBean.ChildStatus?): Int {
        return if (bean == null) {
            0
        } else {
            if (bean.sumNoEnough == -1) {
                0
            } else {
                bean.idHealth + 1
            }
        }
    }

    /**
     * 加载器官趋势
     */
    private fun initOrganProgress(list: List<com.xty.network.model.ReportBean.ChildStatus>) {
        val ednIndex = if (index == ReportVm.ReportInfoType.Year) {
            7
        } else {
            10
        }

        binding.child.mOrganStatus.setData(
            list as MutableList<com.xty.network.model.ReportBean.ChildStatus>,
            ednIndex, true
        )
        binding.child.mOrganHealthTime.visibility = if (list.isEmpty()) View.GONE else View.VISIBLE
        showHealthTrendTime(ednIndex, list, organTimeTvArray)
    }

    @SuppressLint("SetTextI18n")
    private fun showHealthTrendTime(
        ednIndex: Int,
        statusList: MutableList<com.xty.network.model.ReportBean.ChildStatus>,
        timeTvArray: java.util.ArrayList<TextView>
    ) {
        for (element in timeTvArray) {
            element.text = ""
        }
        val suffix = if (index == ReportVm.ReportInfoType.Year) "月" else ""
        if (!statusList.isNullOrEmpty()) {
            if (statusList.size > 1) {
                for (s in timeTvArray.indices) {
                    when (s) {
                        0 -> {
                            timeTvArray[0].text =
                                "${statusList[0].createTime.substring(5, ednIndex)}$suffix"
                        }

                        (timeTvArray.size - 1) -> {
                            timeTvArray[timeTvArray.size - 1].text =
                                "${
                                    statusList[statusList.size - 1].createTime.substring(
                                        5,
                                        ednIndex
                                    )
                                }$suffix"
                        }

                        else -> {
                            if (index == ReportVm.ReportInfoType.Week && !isNearMouth) {
                                try {
                                    timeTvArray[s].text =
                                        "${statusList[s].createTime.substring(5, ednIndex)}$suffix"
                                } catch (e: Exception) {
                                    e.printStackTrace()
                                }
                            }
                        }
                    }
                }
            } else {
                timeTvArray[0].text = "${statusList[0].createTime.substring(5, ednIndex)}$suffix"
                timeTvArray[timeTvArray.size - 1].text =
                    "${statusList[0].createTime.substring(5, ednIndex)}$suffix"
            }
        }
    }

    private fun share() {
        user?.let {
            val aesId = AESCrypt.encrypt("${it.id}")
            var shareTitle = ""
            var title = ""
            val time = binding.mTime.text.toString()
            var url = ""

            val times = time.split("至")
            var myTime = ""
            if (times.isNotEmpty() && times.size >= 2) {
                myTime = "${times[0].trim()}/${times[1]}"
            }
            if (isEstimate) {
                if (isNearMouth) {
                    //近30天分享
                    shareTitle = "近30天健康评估分享"
                    title = "${it.name}近30天健康评估"
                    url =
                        "${BuildConfig.image_prefix}/shareApi/reportWeekly/$aesId/$myTime"
                } else {
                    //近七天分享
                    shareTitle = "近7天健康评估分享"
                    title = "${it.name}近7天健康评估"
                    url =
                        "${BuildConfig.image_prefix}/shareApi/reportWeekly/$aesId/$myTime"
                }
            } else {
                when (index) {
                    ReportVm.ReportInfoType.Week -> {
                        shareTitle = "周报分享"
                        title = "${it.name}周健康状态趋势"
                        val times = time.split("至")
                        var myTime = ""
                        if (times.isNotEmpty()) {
                            myTime = "${times[0].trim()}/${times[1]}"
                        }
                        url =
                            "${BuildConfig.image_prefix}/shareApi/reportWeekly/$aesId/$myTime"
                    }

                    ReportVm.ReportInfoType.Month -> {
                        shareTitle = "月报分享"
                        title = "${it.name}月健康状态趋势"
                        url = "${BuildConfig.image_prefix}/shareApi/reportMonthly/$aesId/$time"
                    }

                    ReportVm.ReportInfoType.Year -> {
                        shareTitle = "年报分享"
                        title = "${it.name}本年健康状态趋势"
                        url = "${BuildConfig.image_prefix}/shareApi/reportYear/$aesId/$time"
                    }

                    else -> {}
                }
            }
            Log.e("mTag:aesId=", aesId)
            Log.e("mTag:shareTitle=", shareTitle)
            Log.e("mTag:title=", title)
            Log.e("mTag:url=", url)
            Log.e("mTag:time=", time)
            mapWeek[time]?.let { it1 -> Log.e("mTag:mapWeek[time]=", it1) }
            WxUtils.shareWebPage(shareTitle, title, this, url)
        }
    }

    /**
     * 获取需要选择是周数据时间
     */
    private fun weekMonday() {
        var startWeek = RxTimeTool.string2Milliseconds("2022-05-23 00:00:00")
        var isStart = true
        while (isStart) {
            val endWeek = startWeek + (6 * 24 * 60 * 60 * 1000)  //周一加6天 等于周末
            if (System.currentTimeMillis() < endWeek) {
                isStart = false
            } else {
                mapWeek.put(
                    RxTimeTool.milliseconds2String(
                        startWeek,
                        SimpleDateFormat("yyyy-MM-dd")
                    ), RxTimeTool.milliseconds2String(endWeek, SimpleDateFormat("yyyy-MM-dd"))
                )
                startWeek = endWeek + (24 * 60 * 60 * 1000) //时间点切换到下周一   然后开始下一轮循环
            }
        }
    }

    /**
     * 周数据日期选择器
     */
    private fun selectOption() {
        val list = mutableListOf<String>()
        mapWeek.keys.forEach {
            list.add(it)
        }
        mWeekPickerView = OptionsPickerBuilder(
            this
        ) { options1, _, _, _ -> //返回的分别是三个级别的选中位置
            binding.mTime.text = list[options1]
            mViewModel.getReportInfoNeW(
                index,
                binding.mTime.text.toString(),
                userId,
                isDemonstrate
            )
//            mViewModel.getReportAvgNew(
//                index.reportType,
//                binding.mTime.text.toString(),
//                userId,
//                isDemonstrate
//            )
        }
            .setDecorView(binding.mScroll) //必须是RelativeLayout，不设置setDecorView的话，底部虚拟导航栏会显示在弹出的选择器区域
            .setTitleText("") //标题文字
            .setTitleSize(18) //标题文字大小
            .setTitleColor(resources.getColor(R.color.col_455)) //标题文字颜色
            .setCancelText("取消") //取消按钮文字
            .setCancelColor(
                (ContextCompat.getColor(
                    this,
                    com.xty.common.R.color.col_c64
                ))
            ) //取消按钮文字颜色
            .setSubmitText("确定") //确认按钮文字
            .setSubmitColor(
                ContextCompat.getColor(
                    this,
                    com.xty.common.R.color.start_col
                )
            ) //确定按钮文字颜色
            .setContentTextSize(20) //滚轮文字大小
            .setLineSpacingMultiplier(1.8f) //行间距
            .setSelectOptions(0) //设置选择的值
            .build()
        mWeekPickerView.setPicker(list)
    }
}