package com.zj365.health.act

import android.annotation.SuppressLint
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.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.text.isDigitsOnly
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.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.MMkvHelper
import com.xty.common.TimeSelect
import com.xty.common.TimeUtils
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.setImageUser
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.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.ActHealthSkyHourReportBinding
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.xty.network.model.ReportBean
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.Locale

/**
 * 24小时健康评估
 */
@SuppressLint("SimpleDateFormat")
@Route(path = ARouterUrl.HEALTH_SKY_HOUR_REPORT)
class HealthSkyHourReportAct : BaseVmAct<ReportVm>() {

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

    //tab列表
    private val mTitles = arrayOf(
        "用户信息", "器官功能分析", "睡眠监测", "中医分析", "中医养生指导", "西医分析", "西医指导",
        "饮食指导", "运动指导", "睡眠方案建议", "营养处方建议", "统计分析", "综合分析"
    )
    private val mTitless = mutableListOf<String>()

    private var isDemonstrate: Boolean = false //是否是演示模式
    private var isEstimate: Boolean = false  //是否是评估页面
    private var userId = ""
    private var titleName = ""
    private var index = ReportVm.ReportInfoType.Day
    private var currentTime: String = ""
    private var text = ""
    private var sex = "1"
    private var user: ReportBean.User? = null
    private var isfirst: Boolean = true
    private var isX1X2 = false

    private var isSelectTable = false
    private var isScrollTable = false

    private var launch: Job? = null

    private val listInfo = mutableListOf<ReportBean.HrInfo>()
    private val xiyiList = mutableListOf<MyReportBean>()

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

    /**
     * 综合分析列表
     */
    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 dialogBind by lazy {
        DialogTip(this, "需绑定中健三六五健康手表，才能查看", "去绑定") {
            RouteManager.goAct(ARouterUrl.DEVICE_CHOICE)
        }
    }

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

    private val timSelect by lazy {
        TimeSelect(this) {
            val time = binding.mTvTime.text.toString()
            val nowTime = RxTimeTool.milliseconds2String(
                System.currentTimeMillis(),
                SimpleDateFormat("yyyy-MM-dd")
            )
            if (nowTime == time) {
                currentTime = RxTimeTool.curTimeString
                mViewModel.getReportInfoNeW(index, RxTimeTool.curTimeString, userId, isDemonstrate)
//                mViewModel.getReportAvgNew(
//                    index.reportType,
//                    currentTime,
//                    userId,
//                    isDemonstrate
//                )
            } else {
                currentTime = "$time 12:00:00"
                mViewModel.getReportInfoNeW(index, "$time 12:00:00", userId, isDemonstrate)
//                mViewModel.getReportAvgNew(
//                    index.reportType,
//                    currentTime,
//                    userId,
//                    isDemonstrate
//                )
            }

        }
    }

    private val tipDialog by lazy {
        //-1 建模中 0数据不足 1健康 2亚健康 3疾病
        val title = when (mViewModel.infoLive.value!!.data.healthy.result) {
            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) {
        }
    }

    override fun initData() {
        super.initData()
        isX1X2 = MMkvHelper.getBoolean(Const.X1_X2_Device, false)
        isEstimate = intent.getBooleanExtra("isEstimate", false)

        if(intent.extras!!.containsKey("functionList")){
            functionList = intent.extras!!.getParcelableArrayList<DeviceFunctionBean>("functionList")!!
        }
        if (isEstimate) {
            binding.mTvTime.setCompoundDrawablesWithIntrinsicBounds(
                null,  // left
                null,  // top
                null,
                // right (set to null)
                null   // bottom
            )
            binding.mTvTime.isEnabled = false
        }
        binding.llB.visibility = View.GONE

        userId = intent.getStringExtra("id").toString()
        titleName = intent.getStringExtra("titleName").toString()
        try {
            index = intent.getSerializableExtra("index") as ReportVm.ReportInfoType
        } catch (e: Exception) {

        }
        isDemonstrate = intent.getBooleanExtra("isDemonstrate", false)

        val calendar = Calendar.getInstance()
        timSelect.endDate.set(
            calendar[Calendar.YEAR], calendar[Calendar.MONTH],
            if (calendar[Calendar.HOUR_OF_DAY] >= 11) {
                calendar[Calendar.DATE]
            } else {
                calendar[Calendar.DATE] - 1
            }
        )
    }

    @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 (index.reportType == ReportVm.ReportInfoType.Hour.reportType) {
                View.GONE
            } else {
                View.VISIBLE
            }
            this.setImageResource(R.mipmap.icon_share)
            this.setOnClickListener {
                if (isDemonstrate) {
                    shareDialogBind.show()
                    return@setOnClickListener
                }
                if (index.reportType == ReportVm.ReportInfoType.Hour.reportType) {
                    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.mRecycle.size > 0) {
                        val top = binding.mRecycle.top
                        val itemTop = binding.mRecycle[rvPosition].top
                        when (mTitless[tab.position]) {
                            "用户信息" -> {
                                binding.scrollView.smoothScrollTo(
                                    0,
                                    binding.clUserMessageTitle.top
                                )
                            }

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

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

//                            "睡眠监测" -> {
//                                binding.scrollView.smoothScrollTo(
//                                    0,
//                                    binding.mRecycleSleep.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.mRecycle.top) {
                            if (binding.mRecycle.size - 1 > 0 &&
                                scrollY >= binding.mRecycle.top + binding.mRecycle[binding.mRecycle.size - 1].top
                            ) {
                                if (selectedTabPosition != getTabPosition(binding.mRecycle.size - 1)) {
                                    binding.xTablayout.getTabAt(getTabPosition(binding.mRecycle.size - 1))
                                        ?.select()
                                }
                            } else if (binding.mRecycle.size - 2 > 0 &&
                                scrollY >= binding.mRecycle.top + binding.mRecycle[binding.mRecycle.size - 2].top
                            ) {
                                if (selectedTabPosition != getTabPosition(binding.mRecycle.size - 2)) {
                                    binding.xTablayout.getTabAt(getTabPosition(binding.mRecycle.size - 2))
                                        ?.select()
                                }
                            } else if (binding.mRecycle.size - 3 > 0 &&
                                scrollY >= binding.mRecycle.top + binding.mRecycle[binding.mRecycle.size - 3].top
                            ) {
                                if (selectedTabPosition != getTabPosition(binding.mRecycle.size - 3)) {
                                    binding.xTablayout.getTabAt(getTabPosition(binding.mRecycle.size - 3))
                                        ?.select()
                                }
                            } else if (binding.mRecycle.size - 4 > 0 &&
                                scrollY >= binding.mRecycle.top + binding.mRecycle[binding.mRecycle.size - 4].top
                            ) {
                                if (selectedTabPosition != getTabPosition(binding.mRecycle.size - 4)) {
                                    binding.xTablayout.getTabAt(getTabPosition(binding.mRecycle.size - 4))
                                        ?.select()
                                }
                            } else if (binding.mRecycle.size - 5 > 0 && getListPosition(binding.mRecycle.size - 5) != "西医指导" &&
                                scrollY >= binding.mRecycle.top + binding.mRecycle[binding.mRecycle.size - 5].top
                            ) {
                                if (selectedTabPosition != getTabPosition(binding.mRecycle.size - 5)) {
                                    binding.xTablayout.getTabAt(getTabPosition(binding.mRecycle.size - 5))
                                        ?.select()
                                }
                            } else if (binding.mRecycle.size - 5 > 0 && getListPosition(binding.mRecycle.size - 5) == "西医指导" &&
                                scrollY >= binding.mRecycle.top + binding.mRecycle[binding.mRecycle.size - 5].top
                            ) {
                                if (selectedTabPosition != getTabPosition(binding.mRecycle.size - 6)) {
                                    binding.xTablayout.getTabAt(getTabPosition(binding.mRecycle.size - 6))
                                        ?.select()
                                }
                            } else if (binding.mRecycle.size - 6 > 0 && getListPosition(binding.mRecycle.size - 6) != "中医养生指导" &&
                                scrollY >= binding.mRecycle.top + binding.mRecycle[binding.mRecycle.size - 6].top
                            ) {
                                if (selectedTabPosition != getTabPosition(binding.mRecycle.size - 6)) {
                                    binding.xTablayout.getTabAt(getTabPosition(binding.mRecycle.size - 6))
                                        ?.select()
                                }
                            } else if (binding.mRecycle.size - 6 > 0 && getListPosition(binding.mRecycle.size - 6) == "中医养生指导" &&
                                scrollY >= binding.mRecycle.top + binding.mRecycle[binding.mRecycle.size - 6].top
                            ) {
                                if (selectedTabPosition != getTabPosition(binding.mRecycle.size - 7)) {
                                    binding.xTablayout.getTabAt(getTabPosition(binding.mRecycle.size - 7))
                                        ?.select()
                                }
                            } else if (binding.mRecycle.size - 7 > 0 && getListPosition(binding.mRecycle.size - 7) != "中医养生指导" &&
                                scrollY >= binding.mRecycle.top + binding.mRecycle[binding.mRecycle.size - 7].top
                            ) {
                                if (selectedTabPosition != getTabPosition(binding.mRecycle.size - 7)) {
                                    binding.xTablayout.getTabAt(getTabPosition(binding.mRecycle.size - 7))
                                        ?.select()
                                }
                            } else if (binding.mRecycle.size - 7 > 0 && getListPosition(binding.mRecycle.size - 7) == "中医养生指导" &&
                                scrollY >= binding.mRecycle.top + binding.mRecycle[binding.mRecycle.size - 7].top
                            ) {
                                if (selectedTabPosition != getTabPosition(binding.mRecycle.size - 8)) {
                                    binding.xTablayout.getTabAt(getTabPosition(binding.mRecycle.size - 8))
                                        ?.select()
                                }
                            } else if (binding.mRecycle.size - 8 > 0 &&
                                scrollY >= binding.mRecycle.top + binding.mRecycle[binding.mRecycle.size - 8].top
                            ) {
                                if (selectedTabPosition != getTabPosition(binding.mRecycle.size - 8)) {
                                    binding.xTablayout.getTabAt(getTabPosition(binding.mRecycle.size - 8))
                                        ?.select()
                                }
                            } else {
                                if (selectedTabPosition != getTabPosition(0)) {
                                    binding.xTablayout.getTabAt(getTabPosition(0))?.select()
                                }
                            }
                        } else if (scrollY >= binding.mRecycleSleep.top) {
                            if (selectedTabPosition != 0) {
                                binding.xTablayout.getTabAt(0)?.select()
                            }
                        } else if (scrollY >= binding.clApparatusTitle.top) {
                            if (selectedTabPosition != 0) {
                                binding.xTablayout.getTabAt(0)?.select()
                            }
                        } else {
                            if (selectedTabPosition != 0) {
                                binding.xTablayout.getTabAt(0)?.select()
                                binding.xTablayout.setScrollPosition(0, 0F, true)
                            }
                        }
                        isScrollTable = false
                    }
                }
            })

        initRecycle()
        initRecycleSleep()
        initRecycleInfo()
        initRecycleCount()
        currentTime = RxTimeTool.curTimeString
        if (isEstimate) {
            mViewModel.get24HourReportInfo(userId, isDemonstrate)
        } else {
            mViewModel.getReportInfoNeW(index, RxTimeTool.curTimeString, userId, isDemonstrate)
        }

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

        binding.mTvTip.setOnClickListener {
            val webUrl = BuildConfig.image_prefix + "/static/app/dataSource.html"
            bundle.clear()
            bundle.putString("title", "数据来源")
            bundle.putString("url", webUrl)
            RouteManager.goAct(ARouterUrl.WEB_ACT, bundle)
            binding.mTvTip1.setOnClickListener {
//                val webUrl = BuildConfig.image_prefix + "/static/app/dataSource.html"
                bundle.clear()
                bundle.putString("title", "数据来源")
                bundle.putString("url", webUrl)
                RouteManager.goAct(ARouterUrl.WEB_ACT, bundle)
            }

        }
        val calendar = Calendar.getInstance()
        timSelect.endDate.set(
            calendar[Calendar.YEAR], calendar[Calendar.MONTH],
            if (calendar[Calendar.HOUR_OF_DAY] >= 11) {
                calendar[Calendar.DATE]
            } else {
                calendar[Calendar.DATE] - 1
            }
        )
        text = TimeUtils.getDayReportTime()
        binding.mTvTime.setOnClickListener {
            timSelect.selectTime(it, "yyyy-MM-dd")
        }

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

    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 initRecycle() {
        binding.mRecycle.adapter = mAdapter
//        binding.mRecycle.addItemDecoration(RecycleItem(this, 35))
        binding.mRecycle.layoutManager = LinearLayoutManager(this)
        mAdapter.addChildClickViewIds(R.id.mExpans)

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

    /**
     * 睡眠
     */
    private fun initRecycleSleep() {
        binding.mRecycleSleep.adapter = mAdapterSleep
//        binding.mRecycleSleep.addItemDecoration(RecycleItem(this, 30))
        binding.mRecycleSleep.layoutManager = LinearLayoutManager(this)
        mAdapterSleep.addChildClickViewIds(R.id.mExpans)

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

    /**
     * 基本嘻嘻展示
     */
    private fun initRecycleInfo() {
        binding.mRecycleInfo.adapter = infoAdapter
        binding.mRecycleInfo.layoutManager = GridLayoutManager(this, 2)
        binding.mRecycleInfo.addItemDecoration(GridDividerItemDecoration(0, 2))
    }

    /**
     * 底部圆形分析
     */
    private fun initRecycleCount() {
        binding.mRecycleCount.adapter = mAdapterCount
        binding.mRecycleCount.layoutManager = LinearLayoutManager(this)
    }

    @SuppressLint("SetTextI18n")
    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

            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)

            val notifyMsg = it.data.notifyMsg
            if (notifyMsg.isNullOrEmpty()) {
                binding.mTvNotifyMsg.visibility = View.GONE
            } else {
                binding.mTvNotifyMsg.text = notifyMsg
                binding.mTvNotifyMsg.visibility = View.VISIBLE
            }
            if (isDemonstrate) {
                binding.mTvNotifyMsg.visibility = View.GONE
            }

            binding.mImage.setImageUser(this, it.data.user.avatarUrl, it.data.user.sex)
            binding.mName.text = it.data.user.name
            setStatus()
            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"
            }

            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)

            if (isEstimate) {
                binding.mTvTime.text = CommonUtils.getSpaceTimeOneDay()
            } else {
                if (!it.data.healthy.createTime.isNullOrEmpty()) {
                    val timeMill = RxTimeTool.string2Milliseconds(
                        "${
                            it.data.healthy.createTime.substring(
                                0,
                                10
                            )
                        } 00:00:00"
                    )
                    val yestDay = RxTimeTool.milliseconds2String(
                        timeMill - (24 * 60 * 60 * 1000),
                        SimpleDateFormat("MM-dd")
                    )
                    if (isDemonstrate) {
                        if (isfirst) {
                            binding.mTvTime.text = yestDay
                        } else {
                            binding.mTvTime.text = timSelect.selectTime
                        }
                        isfirst = false
                    } else {
                        binding.mTvTime.text = "$yestDay 11:00 至 ${
                            it.data.healthy.createTime.substring(
                                5,
                                10
                            )
                        } 11:00"
                    }
                }
            }

            binding.mAll.setAllData(it.data.adorn.wearCount)
            binding.mActive.setOtherData(it.data.adorn.wearCount, it.data.adorn.activeWear)
            binding.mOther.setOtherData(it.data.adorn.wearCount, it.data.adorn.dormancy)

            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("睡眠方案建议")
            }
//            list.add(  setAnaList(mutableListOf(), "睡眠监测",-1)) //单独的数据 放置睡眠数据
            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)
            }

            mAdapter.sleepBean = it.data.sleep
            mAdapter.setNewInstance(xiyiList)

            val listSleep = mutableListOf<MyReportBean>()
            listSleep.add(setAnaList(mutableListOf(), "睡眠监测", -1)) //单独的数据 放置睡眠数据
            mAdapterSleep.sleepBean = it.data.sleep
            mAdapterSleep.setNewInstance(listSleep)
            //基础信息
            val bsseInfo = it.data.signData

            listInfo.clear()
            listInfo.add(
                ReportBean.HrInfo(
                    "心率",
                    bsseInfo.hr.avg,
                    bsseInfo.hr.min,
                    bsseInfo.hr.max,
                    bsseInfo.hr.count,
                    "",
                    R.mipmap.xl_small
                )
            )
            listInfo.add(
                ReportBean.HrInfo(
                    "血氧",
                    bsseInfo.so.avg,
                    bsseInfo.so.min,
                    bsseInfo.so.max,
                    bsseInfo.so.count,
                    "",
                    R.mipmap.xy_small
                )
            )
            listInfo.add(
                ReportBean.HrInfo(
                    "呼吸率",
                    string2IntStr(bsseInfo.respiratory.avg),
                    string2IntStr(bsseInfo.respiratory.min),
                    string2IntStr(bsseInfo.respiratory.max),
                    string2IntStr(bsseInfo.respiratory.count),
                    "",
                    R.mipmap.hxl_small
                )
            )

            // x1和x2没有体温
            if (DeviceFunctionUtils.hasFunction(functionList,"temp")|| isDemonstrate) {
                listInfo.add(
                    ReportBean.HrInfo(
                        "体温",
                        setavq(bsseInfo.temp.avg),
                        bsseInfo.temp.min,
                        bsseInfo.temp.max,
                        bsseInfo.temp.count,
                        "",
                        R.mipmap.tw_small
                    )
                )
            }

            listInfo.add(
                ReportBean.HrInfo(
                    "运动",
                    bsseInfo.stepData.avg,
                    bsseInfo.stepData.min,
                    bsseInfo.stepData.max,
                    bsseInfo.stepData.count,
                    bsseInfo.step.step,
                    R.mipmap.step_small
                )
            )
            listInfo.add(
                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(
                ReportBean.HrInfo(
                    "血压",
                    bsseInfo.dbp.avg,
                    bsseInfo.dbp.min,
                    bsseInfo.dbp.max,
                    bsseInfo.dbp.count,
                    "",
                    R.mipmap.xya_small
                )
            )
            listInfo.add(
                ReportBean.HrInfo(
                    "血糖",
                    setavq(bsseInfo.bloodSugar.avg),
                    setavq(bsseInfo.bloodSugar.min),
                    setavq(bsseInfo.bloodSugar.max),
                    setavq(bsseInfo.bloodSugar.count),
                    "",
                    R.mipmap.xt_small
                )
            )

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

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

            if (bsseInfo.uricAcid == null) {  //如果服务端没有返回数据，也就是演示模式，我们自己新增一些假数据用于展示
                listInfo.add(
                    ReportBean.HrInfo(
                        "尿酸",
                        "36",
                        "21",
                        "46",
                        "1",
                        "",
                        R.mipmap.ic_uric_acid_small
                    )
                )

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

            infoAdapter.setNewInstance(listInfo)

            setAnalysisInfo(it)

            mViewModel.getReportAvgNew(
                index.reportType,
                currentTime,
                userId,
                isDemonstrate
            )
        }

        //换图数据
        mViewModel.avgLive.observe(this) {
            val list = mutableListOf<com.xty.common.model.ReportBean>()
            val hr = com.xty.common.model.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 = com.xty.common.model.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 = com.xty.common.model.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 = com.xty.common.model.ReportBean().apply {
                    title = "体温"
                    count = it.data.tempMean.count
                    listNum.add(it.data.tempMean.normal)
                    listNum.add(it.data.tempMean.low)
                    listNum.add(it.data.tempMean.centre)
                    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 = com.xty.common.model.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 = com.xty.common.model.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 = com.xty.common.model.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) {  //服务端没有返回数据
                com.xty.common.model.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 {
                com.xty.common.model.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) {  //服务端没有返回数据
                com.xty.common.model.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 {
                com.xty.common.model.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 = com.xty.common.model.ReportBean().apply {
                title = "运动"
                if (listInfo.size > 0) {
                    listInfo.forEach { synthesize ->
                        if (synthesize.name == "运动") {
                            synthesizeList = synthesize
                        }
                    }
                }
                isShow = false
            }
            list.add(yundong)

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


//            if (list.size == 1) {
//                binding.clStatistics.visibility = View.GONE
//            }

            mAdapterCount.setNewInstance(list)

            mAdapterCount.addChildClickViewIds(R.id.tvInto)
            mAdapterCount.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
                        }
                        mViewModel.getWatchAbnormalDataUricAcid(
                            userId,
                            "1",
                            RxTimeTool.curTimeString,
                            "9"
                        )
                    }

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

                    else -> {}
                }
            }
        }

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

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

    private fun goExceptionActivity(exceptionType: Int) {
        if (isDemonstrate) {
            dialogBind.show()
            return
        }

        bundle.clear()
        bundle.putString("id", userId)
        if (isEstimate) {
            bundle.putInt("timeType", ReportVm.ReportInfoType.Hour.reportType)
        } else {
            bundle.putInt("timeType", index.reportType)
        }

        bundle.putString("time", getTimeRange())
        bundle.putInt("exceptionType", exceptionType)
        bundle.putString("currentTime", currentTime)
        RouteManager.goAct(ARouterUrl.ALL_EXCEPTION_DATA_ACT, bundle)
    }

    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()
    }

    private fun getTimeRange(): String {
        // 解析输入的日期范围
        val inputRange = binding.mTvTime.text
        val parts = inputRange.split("至")

        // 获取当前年份
        val currentYear = Calendar.getInstance().get(Calendar.YEAR)

        // 使用 SimpleDateFormat 解析日期，并设置年份为当前年份
        val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
        val startDate = Calendar.getInstance()
        startDate.time = dateFormat.parse("$currentYear-${parts[0]}")!!
        val endDate = Calendar.getInstance()
        endDate.time = dateFormat.parse("$currentYear-${parts[1]}")!!

        // 修改格式并处理跨年情况
        return if (startDate.get(Calendar.YEAR) == endDate.get(Calendar.YEAR)) {
            "${
                SimpleDateFormat(
                    "yyyy-MM-dd HH:mm",
                    Locale.getDefault()
                ).format(startDate.time)
            }至${SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(endDate.time)}"
        } else {
            "${
                SimpleDateFormat(
                    "yyyy-MM-dd HH:mm",
                    Locale.getDefault()
                ).format(startDate.time)
            }至${currentYear + 1}-${
                SimpleDateFormat("MM-dd HH:mm", Locale.getDefault()).format(
                    endDate.time
                )
            }"
        }
    }

    /**
     * 组装 数据
     */
    private fun setAnaList(
        data: List<ReportBean.Content>,
        name: String,
        type: Int = 0
    ): MyReportBean {
        val bean = MyReportBean()
        val sb = StringBuilder()
        bean.name = name
        if (type == -1) {
            bean.type = -1
            return bean
        }
        if (data.isEmpty()) {
            bean.content = "身体健康，请继续保持"
        } else {
            when (bean.name) {
                "西医分析" -> {
                    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")
                        } else {
                            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")
                        }
                    }
                    bean.content = sb.toString().trim()
                }

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

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

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

        }

        return bean
    }

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

    private fun setStatus() {
        //健康状态   数据不足 0： 健康 1：   亚健康 2： 疾病 3：    建模中-1:
        val statusInt = if (mViewModel.infoLive.value!!.data!!.healthy == null) {
            0
        } else {
            mViewModel.infoLive.value!!.data.healthy.result
        }
        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.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.clBody.healthBody.setMenuItemIconsAndTexts(organImg,organName)

        binding.mHeart.setInfo(getHealthStatus(organ.heart.model), UserInfoDefin.heartIcon)
        binding.mStomach.setInfo(getHealthStatus(organ.stomach.model), UserInfoDefin.stomachIcon)
        binding.mLung.setInfo(getHealthStatus(organ.lungs.model), UserInfoDefin.lungIcon)
        binding.mKidney.setInfo(getHealthStatus(organ.kidney.model), UserInfoDefin.kidneyIcon)
        binding.mLiver.setInfo(getHealthStatus(organ.liver.model), UserInfoDefin.liverIcon)
        binding.mSpleen.setInfo(getHealthStatus(organ.spleen.model), UserInfoDefin.spleenIcon)

        binding.mLarge.setInfo(getHealthStatus(organ.largeIntestine.model), UserInfoDefin.largeIcon)
        binding.mSmall.setInfo(getHealthStatus(organ.smallIntestine.model), UserInfoDefin.smallIcon)
        binding.mLymph.setInfo(getHealthStatus(organ.lymph.model), UserInfoDefin.lymphIcon)
        binding.mGallbladder.setInfo(getHealthStatus(organ.cholecyst.model), UserInfoDefin.gallIcon)
        binding.mBladder.setInfo(getHealthStatus(organ.bladder.model), UserInfoDefin.bladderIcon)
        binding.mPericardium.setInfo(
            getHealthStatus(organ.pericardium.model),
            UserInfoDefin.pericardiumIcon
        )
    }

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

    private fun setavq(str: String): String {
        var num = BigDecimal(str)
        num = num.setScale(1, BigDecimal.ROUND_HALF_UP)
        return num.toString()
    }

    /**
     * 设置健康状态以及星级评价
     */
    @SuppressLint("UseCompatLoadingForDrawables")
    private fun setHealthStatuAndStarInfo(it: RespBody<ReportBean>) {
        binding.mTvcValue.apply {
            val statusInt = if (it.data.healthy == null) {
                0
            } else {
                it.data.healthy.result
            }
            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<ReportBean>) {
       /* binding.analysisTv1.text = "平均心率：" + it.data.signData.hr.avg + "次/分"
        binding.analysisTv2.text = "平均血氧：" + it.data.signData.so.avg + "%"
        binding.analysisTv3.text = "平均呼吸率：" + it.data.signData.respiratory.avg + "次/分"
        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.signData.stepData.avg + "步"
        binding.analysisTv6.text =
            "平均睡眠：${minutesToHours(it.data.signData.sleep.avgTime)}"
        binding.analysisTv7.text = "平均血压：" + it.data.signData.dbp.avg + "mmHg"*/

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

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

        }*/

        val signData = it.data.signData
        if (signData != null) {
            val list = mutableListOf<String>()
            val hrAvg = signData.hr.avg.toInt()
            list.add(
                "平均心率：${
                    if (hrAvg > 0) {
                        hrAvg
                    } else {
                        "--"
                    }
                }次/分"
            )
            val soAvg = signData.so.avg.toFloat()
            list.add(
                "平均血氧：${
                    if (soAvg > 0) {
                        soAvg
                    } else {
                        "--"
                    }
                }%"
            )
            val respiratoryAvg = signData.respiratory.avg.toInt()
            list.add(
                "平均呼吸率：${
                    if (respiratoryAvg > 0) {
                        respiratoryAvg
                    } else {
                        "--"
                    }
                }次/分"
            )
            if (DeviceFunctionUtils.hasFunction(functionList, "temp")) {
                val tempAvg = signData.temp.avg
                val stringToDoubleOne = CommonUtils.stringToDoubleOne(tempAvg).toFloat()
                list.add(
                    "平均体温：${
                        if (stringToDoubleOne > 0) {
                            stringToDoubleOne
                        } else {
                            "--"
                        }
                    }°C"
                )
            }
            val stepDataAvg = signData.stepData.avg.toInt()
            list.add(
                "平均步数：${
                    if (stepDataAvg > 0) {
                        stepDataAvg
                    } else {
                        "--"
                    }
                }步"
            )
            val avgTime = signData.sleep.avgTime!!.toInt()
            val sleepAvgTime = minutesToHours(avgTime.toString())
            list.add(
                "平均睡眠时间：${
                    if (avgTime > 0) {
                        sleepAvgTime
                    } else {
                        "--小时"
                    }
                }"
            )
            val dbpAvg = signData.dbp.avg
            val split = dbpAvg.split("/")
            val s = split[0].toInt()
            val s1 = split[1].toInt()
            list.add(
                "平均血压：${
                    if (s > 0) {
                        s
                    } else {
                        "--"
                    }
                }/${
                    if (s1 > 0) {
                        s1
                    } else {
                        "--"
                    }
                }mmHg"
            )
            val bloodSugarAvg = signData.bloodSugar.avg.toFloat()
            list.add(
                "平均血糖：${
                    if (bloodSugarAvg > 0) {
                        bloodSugarAvg
                    } else {
                        "--"
                    }
                }mmol/L"
            )
            val uricAcidAvg = signData.uricAcid.avg.toFloat()
            list.add(
                "平均尿酸：${
                    if (uricAcidAvg > 0) {
                        uricAcidAvg
                    } else {
                        "--"
                    }
                }μmol/L"
            )
            if (signData.bloodFat != null) {
                val tcAvg = signData.bloodFat.tcAvg.toFloat()
                list.add(
                    "平均总胆固醇：${
                        if (tcAvg > 0) {
                            tcAvg
                        } else {
                            "--"
                        }
                    }mmol/L"
                )
                val tgAvg = signData.bloodFat.tgAvg.toFloat()
                list.add(
                    "平均甘油三酯：${
                        if (tgAvg > 0) {
                            tgAvg
                        } else {
                            "--"
                        }
                    }mmol/L"
                )
                val hdlAvg = signData.bloodFat.hdlAvg.toFloat()
                list.add(
                    "平均高密度脂蛋白：${
                        if (hdlAvg > 0) {
                            hdlAvg
                        } else {
                            "--"
                        }
                    }mmol/L"
                )
                val ldlAvg = signData.bloodFat.ldlAvg.toFloat()
                list.add(
                    "平均低密度脂蛋白：${
                        if (ldlAvg > 0) {
                            ldlAvg
                        } else {
                            "--"
                        }
                    }mmol/L"
                )
            } else {
                list.add("平均总胆固醇：3.11mmol/L")
                list.add("平均甘油三酯：2.22mmol/L")
                list.add("平均高密度脂蛋白：1.22mmol/L")
                list.add("平均低密度脂蛋白：3.33mmol/L")
            }
            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.state.apply {
                val statusInt = it.data.healthy.result
                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 minutesToHours(minutes: String?): String {
        if (minutes.isNullOrEmpty() || !minutes.isDigitsOnly()) {
            return minutes ?: ""
        }
        val hours = minutes.toInt() / 60
        val minutesLeft = minutes.toInt() % 60
        return if (minutesLeft == 0) {
            "${hours}小时"
        } else {
            "${hours}小时${minutesLeft}分"
        }
    }

    private fun share() {
        val showTime = text
        val nowTime = RxTimeTool.milliseconds2String(
            System.currentTimeMillis(),
            SimpleDateFormat("yyyy-MM-dd")
        )
        val time = if (nowTime == showTime) {
            RxTimeTool.curTimeString
        } else {
            "$showTime 12:00:00"
        }

        if (isEstimate) {
            user?.let {
                val aesId = AESCrypt.encrypt("${it.id}")
                val subtitle = "${it.name}的24小时健康评估"
                val url = "${BuildConfig.image_prefix}/shareApi/reportDaily/$aesId/${time}"
                WxUtils.shareWebPage("24小时健康评估", subtitle, this, url)
            }
        } else {
            user?.let {
                val aesId = AESCrypt.encrypt("${it.id}")
                val subtitle = "${it.name}的日报数据"
                val url = "${BuildConfig.image_prefix}/shareApi/reportDaily/$aesId/${time}"
                WxUtils.shareWebPage("日报分享", subtitle, this, url)
            }
        }
    }
}