package com.zj365.health.fragment

import android.annotation.SuppressLint
import android.os.Build
import android.text.Html
import android.text.Spannable
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.view.View
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.core.text.isDigitsOnly
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.tamsiree.rxkit.RxTimeTool
import com.xty.base.fragment.BaseVmFrag
import com.xty.base.utils.UserInfoDefin
import com.xty.common.*
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.recycleUtils.RecycleItem
import com.xty.common.util.CommonToastUtils
import com.xty.common.util.CommonUtils
import com.xty.common.weight.CenterImageSpan
import com.zj365.health.R
import com.zj365.health.act.HealthEstimateActivity
import com.zj365.health.act.HealthReportAct
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.FragDayReportBinding
import com.zj365.health.model.MyReportBean
import com.zj365.health.vm.ReportVm
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 org.json.JSONArray
import org.json.JSONObject
import java.math.BigDecimal
import java.text.SimpleDateFormat
import java.util.*

class FragDayReport : BaseVmFrag<ReportVm>() {
//    val popWindow by lazy { PopWindowUserInfo() }

    private var sex = "1"
    private var isX1X2 = false

    private var isfirst: Boolean = true
    private var isDemonstrate: Boolean = false //是否是演示模式
    private var isEstimate: Boolean = false  //是否是评估页面
    val binding by lazy { FragDayReportBinding.inflate(layoutInflater) }
    var user: ReportBean.User? = null
    val mAdapter by lazy { ReportInfoAdapter() }
    val mAdapterSleep by lazy { ReportInfoAdapter() }
    val mAdapterCount by lazy { ReportAnalysisAdapter() }
    private val infoAdapter by lazy { DayReportInfoAdapter() }
    override fun setViewModel() = ReportVm()
    override fun setLayout() = binding.root
    var index = ReportVm.ReportInfoType.Day
    var userId = ""
    var currentTime: String = ""

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

        }
    }

    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_nodata_data)
            }
        }
        HealthDialog(requireContext(), true, title) {
        }
    }

    override fun initData() {
        super.initData()
        try {
            isX1X2 = MMkvHelper.getBoolean(Const.X1_X2_Device, false)
            isDemonstrate = (requireActivity() as HealthReportAct).isDemonstrate
            isEstimate = false
        } catch (e: Exception) {

        }

        try {
            isDemonstrate = (requireActivity() as HealthEstimateActivity).isDemonstrate
            isEstimate = true
            binding.mTvTime.setCompoundDrawablesWithIntrinsicBounds(
                null,  // left
                null,  // top
                null,                           // right (set to null)
                null   // bottom
            )
            binding.mTvTime.isEnabled = false
            binding.llB.visibility = View.GONE
        } catch (e: Exception) {

        }

        index = arguments?.getSerializable("index") as ReportVm.ReportInfoType
        userId = arguments?.getString("id").toString()
//        timSelect.startDate.set(2022, 4, 20)
        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
            }
        )
//        timSelect.endDate.set(
//            calendar[Calendar.YEAR], calendar[Calendar.MONTH],
//            calendar[Calendar.DATE]
//        )
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun initView() {
        super.initView()
        //popWindow.myPopWindow(requireContext(), R.layout.popwindow_my)
//        popWindow.myPopWindow(requireContext(), R.layout.pop_report)
        //  setStatus()
        initRecycle()
        initRecycleSleep()
        initRecycleInfo()
        initRecycleCount()
        currentTime = RxTimeTool.curTimeString
        if (isEstimate) {
            mViewModel.get24HourReportInfo(userId, isDemonstrate)
            mViewModel.getReportAvgNew(
                ReportVm.ReportInfoType.Hour.reportType,
                currentTime,
                userId,
                isDemonstrate
            )
        } else {
            mViewModel.getReportInfoNeW(index, RxTimeTool.curTimeString, userId, isDemonstrate)
            mViewModel.getReportAvgNew(
                ReportVm.ReportInfoType.Day.reportType,
                currentTime,
                userId,
                isDemonstrate
            )
        }
        //mViewModel.getReportInfo(index,userId)
//        binding.mShowMedical.text= Html.fromHtml("<u>"+ binding.mShowMedical.text+"</u>")
//        binding.mShowMedical.setOnClickListener {
//            if (user != null) {
//                var array = JSONArray()
//                user!!.diseaseList.forEach {
//                    var json = JSONObject()
//                    json.put("name", it.name)
//                    json.put("type", it.type)
//                    json.put("time", it.time)
//                    array.put(json)
//                }
//                var 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)
//            }
//        }

        if (isDemonstrate) {
            binding.llB.visibility = View.GONE
        }
        binding.mTvTip.setOnClickListener {
            var 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 {
                var 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
            }
//            calendar[Calendar.DATE]
        )

//        binding.mTime.text = TimeUtils.getDayReportTime()
        text = TimeUtils.getDayReportTime()
        binding.mTvTime.setOnClickListener {
            timSelect.selectTime(it, "yyyy-MM-dd")
        }
    }

    var text = ""

    private fun setStatus() {
        //健康状态   数据不足 0： 健康 1：   亚健康 2： 疾病 3：    建模中-1:
        var statusInt =
            if (mViewModel.infoLive.value!!.data!!.healthy == null) 0 else mViewModel.infoLive.value!!.data!!.healthy!!.result
        var bodyImgResId = if (statusInt == 2) {
            if (mViewModel.infoLive.value!!.data!!.user!!.sex == "1") R.mipmap.ic_male_body_warning else R.mipmap.ic_female_body_warning
        } else if (statusInt == 3) {
            if (mViewModel.infoLive.value!!.data!!.user!!.sex == "1") R.mipmap.ic_male_body_disease else R.mipmap.ic_female_body_disease
        } else if (statusInt == 1) {
            if (mViewModel.infoLive.value!!.data!!.user!!.sex == "1") R.mipmap.ic_male_body_health else R.mipmap.ic_female_body_health
        } else {
            if (mViewModel.infoLive.value!!.data!!.user!!.sex == "1") R.mipmap.ic_male_body_none_data else R.mipmap.ic_female_body_none_data
        }

        binding.mBody.setImageResource(bodyImgResId)

        val organ = mViewModel.infoLive.value!!.data.organ
        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
            }
        }
    }


    override fun observer() {

        mViewModel.exceptionUricAcidData.observe(this) {

            var mData1 = arrayListOf<String>()
            var mTime1 = arrayListOf<String>()

            it.data?.high?.forEach {
                mData1.add(it.data.toString())
                mTime1.add(it.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

            var 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()) {
                var mecid = sbMedical.toString()
                binding.mTvDis.text = mecid.substring(0, mecid.length - 1)
            }
            addClickableText(binding.mTvDis)

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

            binding.mImage.setImageUser(requireContext(), it.data.user.avatarUrl)
            binding.mName.text = it.data.user.name
            setStatus()
//            var sexHtml = String.format(
//                getString(R.string.info_msg),
//                "性别",
//                UserInfoDefin.getSexArray(requireContext())[it.data.user.sex.toInt() - 1]
//            )
            val sexim =
                String.format(UserInfoDefin.getSexArray(requireContext())[it.data.user.sex.toInt() - 1])
            if ("男".equals(sexim)) {
                binding.icMale.setImageResource(R.mipmap.ic_male_1)
                sex = "1"
            } else {
                binding.icMale.setImageResource(R.mipmap.ic_female_1)
                sex = "2"
            }

//            binding.mSex.text = Html.fromHtml(sexHtml)
            var ageHtml = String.format(getString(R.string.info_msg), "年龄", it.data.user.age)
            binding.mAge.text = Html.fromHtml(ageHtml + "岁")
            var heightHtml =
                String.format(
                    getString(R.string.info_msg),
                    "身高",
                    "${String.format("%.1f", it.data.user.height)}cm"
                )
            binding.mHeight.text = Html.fromHtml(heightHtml)
            var 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} 11:00 至 ${
//                                it.data.healthy.createTime.substring(
//                                    5,
//                                    10
//                                )
//                            } 11:00"
                            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)

            var list = mutableListOf<MyReportBean>()

            list.add(setAnaList(it.data.analysis.TcmAnalysis!!, "中医分析"))
            list.add(setAnaList(it.data.analysis.tcm!!, "中医养生指导"))
            list.add(setAnaList(it.data.analysis.WmAnalysis!!, "西医分析"))
            if (!it.data.analysis.WmAnalysis.isNullOrEmpty()) {
                list.add(setAnaList(it.data.analysis.wm!!, "西医指导"))
            }
            list.add(setAnaList(it.data.analysis.diet!!, "饮食指导"))
            list.add(setAnaList(it.data.analysis.exercise!!, "运动指导"))
            if (!it.data.analysis.sleep.isNullOrEmpty()) {
                list.add(setAnaList(it.data.analysis.sleep!!, "睡眠方案建议"))
            } else {
                list.add(setAnaList(arrayListOf(), "睡眠方案建议"))
            }
//            list.add(  setAnaList(mutableListOf(), "睡眠监测",-1)) //单独的数据 放置睡眠数据
            list.add(setAnaList(it.data.analysis.nutrition!!, "营养处方建议"))

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

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

            var listInfo = mutableListOf<ReportBean.HrInfo>()
            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 (!isX1X2 || 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
                )
            )
            listInfo.add(
                ReportBean.HrInfo(
                    "血压",
                    bsseInfo.dbp.avg,
                    bsseInfo.dbp.min,
                    bsseInfo.dbp.max,
                    bsseInfo.dbp.count,
                    "",
                    R.mipmap.xya_small
                )
            )
            listInfo.add(
                ReportBean.HrInfo(
                    "血糖",
                    bsseInfo.bloodSugar.avg,
                    bsseInfo.bloodSugar.min,
                    bsseInfo.bloodSugar.max,
                    bsseInfo.bloodSugar.count,
                    "",
                    R.mipmap.xt_small
                )
            )

            if (bsseInfo.uricAcid == null) {  //如果服务端没有返回数据，也就是演示模式，我们自己新增一些假数据用于展示
                listInfo.add(
                    com.xty.network.model.ReportBean.HrInfo(
                        "尿酸",
                        "0",
                        "0",
                        "0",
                        "0",
                        "",
                        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.avgLive.observe(this) {
            val list = mutableListOf<com.xty.common.model.ReportBean>()
            var 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("心动过速")
            }
            list.add(hr)

            var 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("低血氧")
            }
            list.add(soMean)

            var 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("呼吸过速")
            }
            list.add(respiratoryMean)

            if (!isX1X2 || isDemonstrate) {
                var 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("超高热")
                }
                list.add(tempMean)
            }

            var 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("三级高血压")
            }
            list.add(dbMean)

            if (it.data.bloodsugar.count != 0) {
                var 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("血糖过低")
                }
                list.add(bloodsugar)
            } else {
                var 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("血糖过低")
                }
                list.add(bloodsugar)
            }

            val uricAcid = if (it.data.uricAcid == null) {  //服务端没有返回数据
                com.xty.common.model.ReportBean().apply {
                    title = "尿酸"
                    count = 0
                    listNum.add(0)
                    listNum.add(0)

                    listName.add("正常")
                    listName.add("高尿酸")
                }
            } 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("高尿酸")
                }
            }
            list.add(uricAcid)


//            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) {
                            try {
                                (requireActivity() as HealthReportAct).dialogBind.show()
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                            try {
                                (requireActivity() as HealthEstimateActivity).dialogBind.show()
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                            return@setOnItemChildClickListener
                        }
                        mViewModel.getWatchAbnormalDataUricAcid(
                            userId,
                            "1",
                            RxTimeTool.curTimeString,
                            "9"
                        )
                    }

                    else -> {}
                }
            }
        }
    }

    /**
     * 设置综合分析内容
     */
    @SuppressLint("SetTextI18n", "UseCompatLoadingForDrawables")
    private fun setAnalysisInfo(it: RespBody<com.xty.network.model.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 (isX1X2) {
            binding.analysisTv4.visibility = View.GONE
        } else {
            binding.analysisTv4.text =
                "平均体温: " + CommonUtils.stringToDoubleOne(it.data.signData.temp.avg) + "°C"
        }

        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"
        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, 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}分"
        }
    }

    fun goExceptionActivity(exceptionType: Int) {
        if (isDemonstrate) {
            try {
                (requireActivity() as HealthReportAct).dialogBind.show()
            } catch (e: Exception) {

            }
            try {
                (requireActivity() as HealthEstimateActivity).dialogBind.show()
            } catch (e: Exception) {

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

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

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

    private fun addClickableText(textView: TextView) {
        val originalText = textView.text.toString() + "  "
        val clickableText = "点击查看"
        val textColor = ContextCompat.getColor(requireContext(), R.color.col_02c)
        val spannableString = SpannableString("$originalText$clickableText")
        // 设置点击事件
        val clickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                if (isDemonstrate) {
                    try {
                        (requireActivity() as HealthReportAct).dialogBind.show()
                    } catch (e: Exception) {

                    }
                    try {
                        (requireActivity() as HealthEstimateActivity).dialogBind.show()
                    } catch (e: Exception) {

                    }
                    return
                }
                // 在这里实现点击事件的逻辑
                // 例如打开一个新的界面或执行某些操作
                if (user != null) {
                    var array = JSONArray()
                    user!!.diseaseList.forEach {
                        var json = JSONObject()
                        json.put("name", it.name)
                        json.put("type", it.type)
                        json.put("time", it.time)
                        array.put(json)
                    }
                    var 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 setHealthStatuAndStarInfo(it: RespBody<ReportBean>) {
        binding.mTvcValue.apply {
            var statusInt = if (it.data.healthy == null) 0 else it.data.healthy.result
            var star = if (it.data.star.isNullOrEmpty()) 0 else Integer.valueOf(it.data.star)

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

            append("\t\t")

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

            var 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")
                var span =
                    (if (star >= i) selectStarImage else unSelectStarImage)?.let { starDrawable ->
                        CenterImageSpan(starDrawable)
                    }
                spanStr.setSpan(span, 0, spanStr.length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
                append(spanStr)
            }

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

    /**
     * 组装 数据
     */
    private fun setAnaList(
        data: List<ReportBean.Content>,
        name: String,
        type: Int = 0
    ): MyReportBean {
        var bean = MyReportBean()
        var sb = StringBuilder()
        bean.name = name
        if (type == -1) {
            bean.type = -1
            return bean
        }
        if (data.isEmpty()) {
            bean.content = "身体健康，请继续保持"
        } else {
            if (bean.name == "西医分析") {
                data?.forEachIndexed { index, bean ->
                    if (bean.dictName == "考虑症状") {
                        if (bean.dictName == "考虑症状") {
                            sb.append(
                                String.format(
                                    getString(R.string.analysis_agree),
                                    "${bean.dictName}${bean.name}？"
                                )
                            ).append("\n")
                            sb.append(bean.content).append("\n")
                        }
                    } else {
                        sb.append(
                            String.format(
                                getString(R.string.analysis_desc),
                                bean.dictName,
                                bean.name
                            )
                        ).append("\n")
                        sb.append(String.format(getString(R.string.analysis_name), bean.name))
                            .append("\n")
                        sb.append(bean.content).append("\n")
                    }
                }
                bean.content = sb.toString().trim()
            } else if (bean.name == "中医分析") {
                data?.forEach {
                    sb.append(it.dictName).append("\n")
                    sb.append(it.content).append("\n")
                }
                bean.content = sb.toString().trim()
            } else if (bean.name == "中医养生指导") {
                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
    }

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

    /**
     * 报告适配器
     */
    private fun initRecycle() {
        binding.mRecycle.adapter = mAdapter
        binding.mRecycle.addItemDecoration(RecycleItem(requireContext(), 30))
        binding.mRecycle.layoutManager = LinearLayoutManager(requireContext())
        mAdapter.addChildClickViewIds(R.id.mExpans)

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

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

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

    /**
     * 基本嘻嘻展示
     */
    private fun initRecycleInfo() {
        binding.mRecycleInfo.adapter = infoAdapter
//        var itemHeight=RecycleItem(requireContext(),1,0)
//        itemHeight.setSpace(30,30)
//        binding.mRecycleInfo.addItemDecoration(itemHeight)
        binding.mRecycleInfo.layoutManager = GridLayoutManager(requireContext(), 2)
        binding.mRecycleInfo.addItemDecoration(GridDividerItemDecoration(0, 2))
    }

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

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