package com.zj365.dc.fragment

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Build
import android.provider.Settings
import android.text.Spannable
import android.text.SpannableString
import android.text.TextUtils
import android.text.method.KeyListener
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.lifecycle.MutableLiveData
import cn.jpush.android.api.JPushInterface
import com.tamsiree.rxkit.RxTimeTool
import com.xty.base.fragment.BaseVmFrag
import com.xty.base.utils.UserInfoDefin
import com.xty.common.Const
import com.xty.common.LogUtils
import com.xty.common.MMkvHelper
import com.xty.common.UmengEventId
import com.xty.common.aMapUtils.AmapInit
import com.xty.common.app.MyApp
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.bracelet.YCBBlueConnectHelper
import com.xty.common.bracelet.YCBManager
import com.xty.common.bracelet.YCBOrder
import com.xty.common.bracelet.checkBlueConnectPermission
import com.xty.common.bracelet.getBluePermission
import com.xty.common.bracelet.isGpsOpen
import com.xty.common.event.AddSuccessEvent
import com.xty.common.event.BindDevEvent
import com.xty.common.event.BlueToothConnectEvent
import com.xty.common.event.ChangeFamilyEvent
import com.xty.common.event.FamilyEvent
import com.xty.common.event.Health24HourStatusEvent
import com.xty.common.event.LoginOrRegisterEvent
import com.xty.common.event.LoginOutEvent
import com.xty.common.event.MyInfoEvent
import com.xty.common.event.WorkManagerEvent
import com.xty.common.marqueen.SimpleMF
import com.xty.common.onEventObject
import com.xty.common.setImageUser
import com.xty.common.util.CommonToastUtils
import com.xty.common.util.CommonUtils
import com.xty.common.weight.CenterImageSpan
import com.xty.common.work.MyWorkManger
import com.xty.network.MyRetrofit
import com.xty.network.model.DeviceFunctionBean
import com.xty.network.model.HealthMonitoringListBean
import com.xty.network.model.MessageBean
import com.xty.network.model.ReportBean
import com.zj365.dc.BuildConfig
import com.zj365.dc.R
import com.zj365.dc.adapter.HealthMonitoringAdapter
import com.zj365.dc.databinding.FragDynamicManagementBinding
import com.zj365.dc.vm.DynamicManagementVm
import com.zj365.health.vm.ReportVm
import com.zj365.health.weight.DialogTip
import com.zj365.mime.weight.NoticeSettingDialog
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONArray
import org.json.JSONObject
import pub.devrel.easypermissions.EasyPermissions
import java.text.SimpleDateFormat
import java.util.concurrent.TimeUnit
import kotlin.math.max
import kotlin.math.min

/**
 * 动态管理页面
 */
class DynamicManagementFrag : BaseVmFrag<DynamicManagementVm>() , EasyPermissions.PermissionCallbacks{

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

    //家人列表适配器
//    private val mFamilyAdapter by lazy { FamilyAdapter() }

    private val dialogInfoUn by lazy {
        DialogTip(requireContext(), "请完善基本信息") {
            RouteManager.goAct(ARouterUrl.BASE_INFO_CHANGE)
        }
    }
    private val reqGpsPermissionDialog by lazy {
        NoticeSettingDialog(requireContext(), "请打开GPS权限", {
        }) {
            // 转到手机设置界面，用户设置GPS
            val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
            startActivityForResult(intent, 1001) // 设置完成后返回到原来的界面
        }
    }
    private val dialogBind by lazy {
        DialogTip(requireContext(), "需绑定中健三六五健康手表，才能查看", "去绑定") {
            RouteManager.goAct(ARouterUrl.DEVICE_CHOICE)
        }
    }

    //健康监测按钮数据集合
    private var healthMonitoringList: MutableList<HealthMonitoringListBean> =
        mutableListOf()//(小于等于9)
    private var healthMonitoringListExceed: MutableList<HealthMonitoringListBean> =
        mutableListOf()//(大于9)

    private val mHealthAdapter by lazy { HealthMonitoringAdapter(requireContext()) }
    //    private val mHealthAdapter by lazy { HealthAdapter(requireContext()) }//老版健康监测适配器

    private var showIdInfo = "" //需要显示的信息的id
    private var sex = "" //性别
    private var notifyStatus: Int? = -1
    private var isRefresh = true
    private var isDemonstrate: Boolean = false
    private var reportBean: ReportBean? = null//24小时日报数据
    private var canGoto24Healthresult: Boolean = true
    private var getDeviceInfoJob: Job? = null
    private val getDeviceInfoLive by lazy { MutableLiveData<String>() }
    private var tenJob: Job? = null
    private val tenLive by lazy { MutableLiveData<String>() }
    private var isShrinkage = false//记录是否收缩
    private var functionList= ArrayList<DeviceFunctionBean>()
    private var isJob = false

    /**
     * -1：步数 0:心率 1：血氧 2：呼吸率 3：体温 4：睡眠 5：血压 6：血糖 7:心电|血脂
     * 0.心率、1.血氧、2.呼吸率、3.体温、4.步数、5.睡眠、6.血压、7.血糖、8.心电、9.尿酸、10.血脂。
     */
    private val pageIndexs = arrayOf(
        0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
    )
    private val pageNames = arrayOf(
        "心率", "血氧", "呼吸率", "体温", "步数", "睡眠", "血压", "血糖", "心电", "尿酸", "血脂"
    )

    private var getHealthInfoJob: Job? = null

    @SuppressLint("ResourceType")
    override fun initView() {
        super.initView()
      //  statusBar(binding.statusBar)

        isShrinkage =
            MMkvHelper.getBoolean(Const.Health_Monitoring_Shrinkage + MMkvHelper.getLong(Const.USER_ID))
        if(arguments?.containsKey("id") == true){
            showIdInfo =  arguments?.getString("id").toString()
        }else{
            showIdInfo =if (MMkvHelper.getLong(Const.USER_ID).toString() == "0") {
                ""
            } else {
                MMkvHelper.getLong(Const.USER_ID).toString()
            }


        }


        //点击事件
        setOnClickListener()
        if(!TextUtils.isEmpty(showIdInfo)){
            request()
        }

        //刷新注册
        refresh()

        binding.mGriddingList.mGridView.adapter = mHealthAdapter
        binding.mGriddingList.mGridView.setOnItemClickListener { _, _, position, _ ->
            val index = mHealthAdapter.getItem(position).type
            val functionType = mHealthAdapter.getItem(position).functionType
            onEventObject(requireContext(), UmengEventId.HealthMonitor, mHealthAdapter.getItem(position).buttonName)
            when (functionType) {
                //（   ）0.心率、1.血氧、2.呼吸率、3.体温、4.步数、5.睡眠、6.血压、7.血糖、8.心电、9.尿酸、10.血脂。
                //（U32）0.心率、1.血氧、2.呼吸率、3.体温、     、4.睡眠、5.血压、6.血糖、7.尿酸、8.心电,9血脂
                //（A3 ）0.心率、1.血氧、2.呼吸率、3.体温、     、4.睡眠、5.血压、6.血糖、7.尿酸，8.血脂
                //（x1 ）0.心率、1.血氧、2.呼吸率、            、3.睡眠、4.血压、5.血糖、6.尿酸，7.血脂
                "hr", "so", "resp", "temp" -> {
                    goPage(index,functionType)
                }

                "step" -> {//步数
                    if (isDemonstrate) {
                        return@setOnItemClickListener
                    }
                    mViewModel.allData.value?.apply {
                        bundle.clear()
                        bundle.putInt("status", data.adorn.health + 1)
                        bundle.putInt("type", 1)
                        if (showIdInfo.isEmpty()) {
                            bundle.putString("userId", MMkvHelper.getLong(Const.USER_ID).toString())
                        } else showIdInfo.let {
                            bundle.putString("userId", it)
                        }
                        RouteManager.goAct(ARouterUrl.RANK_LIST, bundle)
                    }
                }

                "sleep" -> {
                    goPage(index - 1,functionType)

                }

                "dbp" -> {
                    goPage(index - 1,functionType)
                }

                "uric" -> { //心电隐藏的前提下，尿酸为8 否则为9
                    goPage(7,functionType)
                }

                "sugar" -> { //血糖
                    goPage(index - 1,functionType)

                }

                "bloodFat" -> {  //  //心电隐藏的前提下血脂为9 否则为10
                    goPage(index - 1,functionType)
                //    CommonToastUtils.showToast("尊敬的用户您好，血脂功能暂未开放，敬请期待哦~")
                }
                "ecg" ->{ //心电 暂时隐藏
                    CommonToastUtils.showToast("尊敬的用户您好，心电功能暂未开放，敬请期待哦~")
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
       // mViewModel.getWarningMsg()
    }

    //点击事件
    private fun setOnClickListener() {
        binding.mMsgLayout.setOnClickListener(onClickListener)
        binding.mMsg.setOnClickListener(onClickListener)
        binding.mHeader.mCard.setOnClickListener(onClickListener)
        binding.mHeader.mBtnBind.setOnClickListener(onClickListener)
        binding.mGriddingList.mSub.setOnClickListener(onClickListener)
        binding.mGriddingList.llCompare.setOnClickListener(onClickListener)
        binding.mHealthReport.mDailyReports.setOnClickListener(onClickListener)
        binding.mHealthReport.mWeeklyReports.setOnClickListener(onClickListener)
        binding.mHealthReport.mMonthlyReports.setOnClickListener(onClickListener)
        binding.mHealthReport.mAnnualReports.setOnClickListener(onClickListener)
        binding.mGriddingList.mShrinkageButton.setOnClickListener(onClickListener)
        binding.mHealthReport.llSkyHourReport.setOnClickListener(onClickListener)
        binding.mHealthReport.llHebdomadReport.setOnClickListener(onClickListener)
        binding.mHealthReport.llThirtyDaysReport.setOnClickListener(onClickListener)
        binding.mHeader.mHealthRecords.setOnClickListener(onClickListener)
    }

    //点击事件响应
    private var onClickListener = View.OnClickListener {
        when (it.id) {
            //消息
            R.id.mMsg, R.id.mMsgLayout -> {
                RouteManager.goAct(ARouterUrl.WARNING_MSG)
            }
            //健康档案
            R.id.mHealthRecords -> {

                RouteManager.goAct(ARouterUrl.FAMILY_RECORD_ACT)
                /*CommonToastUtils.showToast("敬请期待")
                return@OnClickListener
*/
            }
            //评估
            R.id.mCard -> {
                bundle.clear()
                bundle.putSerializable("index", ReportVm.ReportInfoType.Hour)
                bundle.putString("id", showIdInfo)
                bundle.putString("titleName", "24小时健康评估")
                bundle.putBoolean("isDemonstrate", isDemonstrate)
                bundle.putBoolean("isEstimate", true)
                RouteManager.goAct(ARouterUrl.HEALTH_SKY_HOUR_REPORT, bundle)
            }
            //绑定
            R.id.mBtnBind -> {
                RouteManager.goAct(ARouterUrl.DEVICE_CHOICE)
            }
            //健康监测
            R.id.mSub -> {
                goPage(0,"")
            }
            //健康对比
            R.id.ll_compare -> {
                if (isDemonstrate) {
                    dialogBind.show()
                    return@OnClickListener
                }
                goComparePage()
            }
            //点击健康监测按钮收缩
            R.id.mShrinkageButton -> {
                if (isShrinkage) {
                    isShrinkage = false
                    binding.mGriddingList.mIvShrinkage.setImageResource(R.mipmap.ic_zhankai)
                    binding.mGriddingList.mTvShrinkage.text = "点击展开"
                } else {
                    isShrinkage = true
                    binding.mGriddingList.mIvShrinkage.setImageResource(R.mipmap.ic_shouqi)
                    binding.mGriddingList.mTvShrinkage.text = "点击收起"
                }
                MMkvHelper.put(
                    Const.Health_Monitoring_Shrinkage + MMkvHelper.getLong(Const.USER_ID),
                    isShrinkage
                )
                if (healthMonitoringListExceed.isNotEmpty() && healthMonitoringList.isNotEmpty()) {
                    if (isShrinkage && healthMonitoringListExceed.size > 9) {
                        mHealthAdapter.mainBean = healthMonitoringListExceed
                    } else {
                        mHealthAdapter.mainBean = healthMonitoringList
                    }
                    mHealthAdapter.notifyDataSetChanged()
                } else {
//                    showToast("数据为空")
                }
            }
            //日报
            R.id.mDailyReports -> {
                onEventObject(requireContext(), UmengEventId.HealthReport, "动态管理")
                bundle.clear()
                bundle.putString("id", showIdInfo)
                bundle.putSerializable("index", ReportVm.ReportInfoType.Day)
                bundle.putBoolean("isDemonstrate", isDemonstrate)
                bundle.putInt("pageType", 0)
                bundle.putString("titleName", "日报")
                bundle.putParcelableArrayList("functionList",functionList)

                RouteManager.goAct(ARouterUrl.HEALTH_SKY_HOUR_REPORT, bundle)
            }
            //周报
            R.id.mWeeklyReports -> {
                onEventObject(requireContext(), UmengEventId.HealthReport, "动态管理")
                bundle.clear()
                bundle.putString("id", showIdInfo)
                bundle.putSerializable("index", ReportVm.ReportInfoType.Week)
                bundle.putBoolean("isDemonstrate", isDemonstrate)
                bundle.putString("titleName", "周报")
                bundle.putParcelableArrayList("functionList",functionList)

                RouteManager.goAct(ARouterUrl.HEALTH_WEEK_MONTH_HOUR_REPORT, bundle)
            }
            //月报
            R.id.mMonthlyReports -> {
                onEventObject(requireContext(), UmengEventId.HealthReport, "动态管理")
                bundle.clear()
                bundle.putString("id", showIdInfo)
                bundle.putSerializable("index", ReportVm.ReportInfoType.Month)
                bundle.putBoolean("isDemonstrate", isDemonstrate)
                bundle.putString("titleName", "月报")
                bundle.putParcelableArrayList("functionList",functionList)

                RouteManager.goAct(ARouterUrl.HEALTH_WEEK_MONTH_HOUR_REPORT, bundle)
            }
            //年报
            R.id.mAnnualReports -> {
                onEventObject(requireContext(), UmengEventId.HealthReport, "动态管理")
                bundle.clear()
                bundle.putString("id", showIdInfo)
                bundle.putSerializable("index", ReportVm.ReportInfoType.Year)
                bundle.putBoolean("isDemonstrate", isDemonstrate)
                bundle.putString("titleName", "年报")
                bundle.putParcelableArrayList("functionList",functionList)

                RouteManager.goAct(ARouterUrl.HEALTH_WEEK_MONTH_HOUR_REPORT, bundle)
            }
            //24小时健康评估
            R.id.llSkyHourReport -> {
                bundle.clear()
                bundle.putSerializable("index", ReportVm.ReportInfoType.Hour)
                bundle.putString("id", showIdInfo)
                bundle.putString("titleName", "24小时健康评估")
                bundle.putBoolean("isDemonstrate", isDemonstrate)
                bundle.putBoolean("isEstimate", true)
                bundle.putParcelableArrayList("functionList",functionList)
                RouteManager.goAct(ARouterUrl.HEALTH_SKY_HOUR_REPORT, bundle)
            }
            //近7天健康评估
            R.id.llHebdomadReport -> {
                bundle.clear()
                bundle.putSerializable("index", ReportVm.ReportInfoType.Week)
                bundle.putString("id", showIdInfo)
                bundle.putBoolean("isDemonstrate", isDemonstrate)
                bundle.putString("titleName", "近7天健康评估")
                bundle.putBoolean("isNearMouth", false)
                bundle.putBoolean("isEstimate", true)
                bundle.putParcelableArrayList("functionList",functionList)
                RouteManager.goAct(ARouterUrl.HEALTH_WEEK_MONTH_HOUR_REPORT, bundle)
            }
            //近30天健康评估
            R.id.llThirtyDaysReport -> {
                bundle.clear()
                bundle.putSerializable("index", ReportVm.ReportInfoType.Week)
                bundle.putString("id", showIdInfo)
                bundle.putBoolean("isDemonstrate", isDemonstrate)
                bundle.putString("titleName", "近30天健康评估")
                bundle.putBoolean("isNearMouth", true)
                bundle.putBoolean("isEstimate", true)
                bundle.putParcelableArrayList("functionList",functionList)
                RouteManager.goAct(ARouterUrl.HEALTH_WEEK_MONTH_HOUR_REPORT, bundle)
            }
        }
    }

    //界面跳转
    private fun goPage(page: Int,functionType:String) {
        if (isBind()) {
            bundle.clear()
            bundle.putInt("page", page)
            bundle.putBoolean("isDemonstrate", isDemonstrate)
            if(functionList.size > 0){
                bundle.putParcelableArrayList("functionList",functionList)
            }
            bundle.putString("functionType",functionType)
            if (!TextUtils.isEmpty(showIdInfo)) {
                bundle.putString("id", showIdInfo)
                bundle.putString("sex", sex)
            } else {
                val id = if (MMkvHelper.getLong(Const.USER_ID).toString() == "0") {
                    ""
                } else {
                    MMkvHelper.getLong(Const.USER_ID).toString()
                }
                bundle.putString("id", id)
                bundle.putString("sex", CommonUtils.getMyUserInfo()?.sex.toString())
            }
            RouteManager.goAct(ARouterUrl.HEALTHMAIN, bundle)
        } else {
            CommonToastUtils.showToast(R.string.please_bind_device)
        }
    }

    private fun goComparePage() {
        bundle.clear()
        bundle.putString("id", showIdInfo)
        RouteManager.goAct(ARouterUrl.COMPARE_PAGE_DATA_ACT, bundle)
    }

    /**
     * 是否绑定了设备
     */
    private fun isBind(): Boolean {
//           Const.mainLiveData?.value?.let {
//               if(!it.user.bluetooth.isNullOrEmpty()){
//                   return true
//               }
//           }
//           return false
        return true
    }

    // 刷新注册
    private fun refresh() {
        refresh.setRefresh(binding.mRefresh) {
            isJob = false
            getXtInfo(showIdInfo)
         //   get24HourReportInfo(showIdInfo)
            request()
            uploadWhatchData()
        }
    }

    private fun request() {
        mViewModel.getAllInfo(showIdInfo, false)
   //     mViewModel.getMySetting()
        mViewModel.getTips()
        mViewModel.getRank(2)


        if(MMkvHelper.contains(Const.LATITUDE) && MMkvHelper.contains(Const.LONGITUDE)){
            mViewModel.getWeather()
        }else{
            if (showIdInfo == ""){

            }else{

                if(EasyPermissions.hasPermissions(requireContext(),  Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION)){
                    AmapInit.startLocation(requireContext()) {
                        LogUtils.e("DynamicManagementFrag","${it.city}")
                        MMkvHelper.put(Const.LONGITUDE,it.longitude)
                        MMkvHelper.put(Const.LATITUDE,it.latitude)
                        MMkvHelper.put(Const.PROVINCE,it.province)
                        MMkvHelper.put(Const.CITY,it.city)
                        MMkvHelper.put(Const.DISTRICT,it.district)
                        mViewModel.getWeather()

                    }
                }else{

                    EasyPermissions.requestPermissions(this,"获取天气信息需要申请定位权限",
                        0x00022,
                        Manifest.permission.ACCESS_COARSE_LOCATION,  Manifest.permission.ACCESS_FINE_LOCATION);
                }

            }

        }


    }

    /**
     * 手表信息上传
     */
    private fun uploadWhatchData() {
        LogUtils.d("手表数据是否上传：$isRefresh")
        if (isRefresh) {//避免重复多次上传导致服务器负载过高，五秒钟之内不允许重复上传。蓝牙断开重连也可以上传
            LogUtils.d("手表数据开始上传...")
            refreshTime()
            getStep()
            getSleepNew()
            getAllData()
        }
    }

    /**
     *15秒钟之内只能上传一次睡眠数据 避免重复上传
     */
    private fun refreshTime() {
        if (isRefresh) {
            isRefresh = false
            mainScope.launch {
                delay(15 * 1000)
                isRefresh = true
            }
        }
    }

    /**
     * 获取历史步数
     */
    @SuppressLint("SimpleDateFormat")
    private fun getStep() {
        YCBManager.getHistoryInfo(YCBOrder.STEP_DATA) {
            mainScope.launch {
                LogUtils.d("getStep Info!")
                val jsonArray = JSONArray()
                val arrayOrigin = JSONArray()
                for (i in 0 until it.size) {
                    val info = it[i] as HashMap<String, Any>
                    val jsonOrigin = JSONObject()
                    for ((k, v) in info) {
                        jsonOrigin.put(k, v)
                    }
                    arrayOrigin.put(jsonOrigin)
                    val dataDayStr = RxTimeTool.milliseconds2String(
                        System.currentTimeMillis(),
                        SimpleDateFormat("yyyy-MM-dd")
                    )
                    val todayStartTime =
                        RxTimeTool.string2Milliseconds("$dataDayStr 00:00:00")  //今天0点的时间

                    val startTime = (info["sportStartTime"] as Long)
                    if (startTime < todayStartTime) {
                        continue
                    }

                    val json = JSONObject()
                    json.put("startTime", (info["sportStartTime"] as Long) / 1000)
                    json.put("endTime", (info["sportEndTime"] as Long) / 1000)
                    json.put("step", info["sportStep"])
                    json.put("calories", info["sportCalorie"])
                    json.put("distance", info["sportDistance"])
                    jsonArray.put(json)
                }
                mViewModel.uploadStep(jsonArray)
            }
        }
    }

    /**
     * 新 睡眠时间上传
     * 限制睡眠在一定时间内请求的次数
     */
    private fun getSleepNew() {
        YCBManager.getHistoryInfo(YCBOrder.SLEEP_DATA) {
            LogUtils.d("getSleep Info!")
            mainScope.launch {
                if (it.isEmpty()) {
                    return@launch
                }

                CommonUtils.getMyUserInfo()?.apply {
                    try {
                        val arraySleep = JSONArray()
                        val rawdata = sleepOriganData(it)
                        for (i in 0 until it.size) {
                            val json = JSONObject()
                            val sleepDetailArray = JSONArray() //详细的睡眠时间
                            val lastData = it[i] as HashMap<*, *>
                            val startTime = lastData["startTime"] as Long
                            val endTime = lastData["endTime"] as Long

                            val lightAll = lastData["lightSleepTotal"] as Int  //潜睡时长
                            val deepLightAll = lastData["deepSleepTotal"] as Int  //深睡时长

                            val deepSleepCount = lastData["deepSleepCount"] as Int //深睡次数
                            val lightSleepCount = lastData["lightSleepCount"] as Int //浅睡次数

                            val listSleepData = lastData["sleepData"] as ArrayList<*>

                            listSleepData.forEach {
                                val value = it as HashMap<*, *>
                                val jsonValue = JSONObject()
                                jsonValue.put(
                                    "sleepStartTime",
                                    (value["sleepStartTime"] as Long) / 1000
                                )
                                jsonValue.put("sleepLen", value["sleepLen"] as Int)
                                jsonValue.put("sleepType", value["sleepType"] as Int)
                                jsonValue.put("userId", id)
                                jsonValue.put("createBy", name)
                                sleepDetailArray.put(jsonValue)
                            }

                            json.put("userId", id)
                            json.put("createBy", name)
                            json.put("lightSleepCount", lightSleepCount)  //浅睡次数
                            json.put("deepSleepCount", deepSleepCount)  //深睡次数
                            json.put("hmWatchSleepData", sleepDetailArray)
                            json.put("lightSleepTotal", max(lightAll, deepLightAll))   //潜睡时长
                            json.put("deepSleepTotal", min(lightAll, deepLightAll))  //深睡时长
                            json.put("startTime", startTime / 1000) //开始时间
                            json.put("endTime", endTime / 1000)  //结束时间
                            json.put("os", "android")
                            if (i == it.size - 1) {
                                json.put("original", rawdata.toString())
                            } else {
                                json.put("original", "---")
                            }
                            arraySleep.put(json)
                        }
                        if (arraySleep.length() > 0) {
                            mViewModel.uploadSleep(arraySleep)
                        }
                    } catch (e: Exception) {
                        LogUtils.e("睡眠数据上传错误:$e")
                    }
                }
            }
        }
    }

    /**
     * 获取所有信息
     */
    private fun getAllData() {
        YCBManager.getAllData {
            mainScope.launch {
                mViewModel.allDataInfo.postValue(it)
            }
        }
    }

    /**
     * 睡眠的原始数据
     */
    private fun sleepOriganData(list: ArrayList<Any>): JSONArray {
        var array = JSONArray()
        list.forEach {
            try {
                val json = JSONObject()
                val lastData = it as HashMap<*, *>

                val startTime = lastData["startTime"] as Long
                val endTIme = lastData["endTime"] as Long

                val l = lastData["lightSleepTotal"] as Int  //潜睡时长
                val d = lastData["deepSleepTotal"] as Int  //深睡时长

                json.put("startTime", startTime)
                json.put("endTime", endTIme)
                json.put("lightSleepTotal", l)
                json.put("deepSleepTotal", d)

                val listSleepData = lastData["sleepData"] as ArrayList<*>
                val sleepArray = JSONArray()
                listSleepData.forEach {
                    val value = it as HashMap<*, *>
                    val jsonValue = JSONObject()
                    jsonValue.put("sleepStartTime", (value["sleepStartTime"] as Long))
                    jsonValue.put("sleepLen", value["sleepLen"] as Int)
                    jsonValue.put("sleepType", value["sleepType"] as Int)
                    sleepArray.put(jsonValue)
                }
                json.put("sleepData", sleepArray)
                array.put(json)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return array
    }

    override fun observer() {
        //预警消息
        mViewModel.warningMsgLive.observe(this) {
            updateBadgeNum(it.data.noReadNum)
            val systemMessage = it.data.systemMessage
            if (systemMessage !=null && systemMessage.isNotEmpty()) {
                val sysMsg = systemMessage[0]
                updateWarningInfo(sysMsg)
            } else {
                updateWarningInfo(null)
            }
        }

        mViewModel.weatherLiveDate.observe(this){
            if(it.data == null){
                binding.mHeader.tvWeather.visibility = View.GONE

            }else{
                binding.mHeader.tvWeather.text = "${it.data.text} ${it.data.temp}℃"
            }
        }

        mViewModel.functionLiveData.observe(this){
            LogUtils.e("DynamicManagementFrag","functionList:${it.data.size}")
            functionList.clear()
            functionList.addAll(it.data)
            if (showIdInfo ==MMkvHelper.getLong(Const.USER_ID).toString()) {
                Const.functionListDate.value = functionList
            }

            startUpdateHealthInfoLive()
        }

        //获取首页所有信息返回
        mViewModel.allData.observe(this) {
            it.data.let { bean ->
                if (bean.user.name.isNullOrEmpty()||bean.user.age.isNullOrEmpty()) {
                    dialogInfoUn.show()
                }
                isDemonstrate = bean.demonstrate == 1 //1 演示模式，0 普通模式

                Const.isDemonstrate = bean.demonstrate == 1
            //    (requireActivity() as MainActivity).isDemonstrate = isDemonstrate
                if (isDemonstrate) {
                    binding.mHeader.mWearInfo.visibility = View.INVISIBLE
                } else {
                    binding.mHeader.mWearInfo.visibility = View.VISIBLE
                }


                if (showIdInfo ==MMkvHelper.getLong(Const.USER_ID).toString()) {  //自己
                    Const.otherLiveData.value = bean
                    binding.mHeader.mHealthRecords.visibility = View.VISIBLE
                }
                Const.battery = bean.power
                Const.watchType = bean.watchType
                MMkvHelper.put(Const.Watch_Device_Type, bean.watchType)

                binding.mHeader.tvNowTime.text = bean.nowDay
                binding.mHeader.tvLanuDate.text = bean.chinaDay

                sex  =  bean.user.sex.toString()
                //设置用户头像
                setUserImage(bean.user.id.toString(), bean.user.image, bean.user.sex.toString())
                binding.mHeader.tvUserName.text = bean.user.name

                bean.bmiInfo?.let {
                    binding.mHeader.mBMI.text = "BMI  ${it.bmi}"
                    binding.mHeader.mBMIStatus.text = "${it.levelName}"
                }?:{
                    binding.mHeader.mBMI.text = "BMI  --"
                    binding.mHeader.mBMIStatus.text = "--"
                  }


                binding.mHeader.tvWarningNum.text ="预警次数：${if (bean.warningCount == 0) "--" else bean.warningCount}次"
                binding.mHeader.tvMonitorNum.text ="监测次数：${if (bean.healthCount == 0) "--" else bean.healthCount}次"

                /*if (bean.watchType == -1) {  //没有绑定设备




                } else if (Const.Companion.WatchDevice.LightA3.ordinal == bean.watchType) {//如果是4G设备，设置连接状态与电量信息

                } else {*/
                    if (showIdInfo == MMkvHelper.getLong(Const.USER_ID).toString()) {  //自己
                        val localBlueMac = MMkvHelper.getString(Const.Blue_Tooth)
                        /*if (YCBBlueConnectHelper.getBleNowStatus() == YCBBlueConnectHelper.BLEConnectState.DisConnect) {//如果本地有蓝牙信息且属于未连接状态，则直接连接
                            LogUtils.d("startConnect::${localBlueMac}")
                            if (localBlueMac.isNullOrEmpty()) {
                                mainUIUpdate(YCBBlueConnectHelper.BLEConnectState.DisConnect)//刷新蓝牙连接状态
                            } else {
                                mainUIUpdate(YCBBlueConnectHelper.BLEConnectState.Connecting)//刷新蓝牙连接状态
                                connect(localBlueMac)
                            }
                        } else if (YCBBlueConnectHelper.getBleNowStatus() == YCBBlueConnectHelper.BLEConnectState.Connected) {
                            getConnectStatus()
                        }*/
                    } else {

                    }
            //    }

                if(!isJob){
                    get24HourReportInfo(showIdInfo)// 这里调用一次接口，防止首次进入App不会刷新评估状态
                }
                //设置健康监测按钮列表数据
                healthMonitoringList.clear()
                healthMonitoringListExceed.clear()
                mHealthAdapter.mainBean.clear()


                val healthMonitoringListData = mViewModel.setHealthMonitoringListData(
                    requireContext(),
                    bean,
                    mViewModel.functionLiveData.value?.data
                )
                val deviceType = bean.deviceType
                if (TextUtils.isEmpty(deviceType)) {
                    MMkvHelper.remove(Const.DEVICE_TYPE)
                } else {
                    MMkvHelper.put(Const.DEVICE_TYPE, deviceType)
                }

                requestByDeviceModel()
                if (healthMonitoringListData.size > 9) {
                    for ((index, healthMonitoringListBean) in healthMonitoringListData.withIndex()) {
                        if (index < 9) {
                            healthMonitoringList.add(healthMonitoringListBean)
                        }
                    }
                    healthMonitoringListExceed = healthMonitoringListData
                    if (isShrinkage) {
                        mHealthAdapter.mainBean = healthMonitoringListExceed

                        binding.mGriddingList.mIvShrinkage.setImageResource(R.mipmap.ic_shouqi)
                        binding.mGriddingList.mTvShrinkage.text = "点击收起"
                    } else {
                        mHealthAdapter.mainBean = healthMonitoringList

                        binding.mGriddingList.mIvShrinkage.setImageResource(R.mipmap.ic_zhankai)
                        binding.mGriddingList.mTvShrinkage.text = "点击展开"
                    }
                    binding.mGriddingList.mShrinkageButton.isVisible = true
                } else {
                    healthMonitoringList = healthMonitoringListData
                    mHealthAdapter.mainBean = healthMonitoringList
                    binding.mGriddingList.mShrinkageButton.isVisible = false
                }
                mHealthAdapter.notifyDataSetChanged()

                //总佩戴 活跃 休眠
                binding.mHeader.mWearInfo.text = getString(
                    R.string.wear_info,
                    bean.adorn?.wearCount?.toString(),
                    bean.adorn?.activeWear?.toString(),
                    bean.adorn.dormancy?.toString()
                )
//                setBindDeviceInfo(bean.deviceTotal)
            }
        }



        //24小时健康报告返回信息
        mViewModel.infoLive.observe(this) {
            if (null == it.data) {
                LogUtils.e("返回数据为空！")
                return@observe
            }

            if (null == it.data.healthy) {
                LogUtils.e("健康信息数据为空！")
                return@observe
            }


            reportBean = it.data

            var healthResult = it.data.healthy.result
            if (Const.watchType != -1) {  //绑定了手表显示状态
                binding.mHeader.mBtnBind.visibility = View.GONE
                binding.mHeader.mLayoutResult.visibility = View.VISIBLE
            } else { //没有绑定手表
                if (/*mFamilyAdapter.position == 0 &&*/ it.data.user?.id.toString() == MMkvHelper.getLong(Const.USER_ID).toString()) { //是自己，显示绑定手表
                    binding.mHeader.mBtnBind.visibility = View.VISIBLE
                    binding.mHeader.mLayoutResult.visibility = View.GONE
                } else {  //不是自己隐藏数据
                    binding.mHeader.mBtnBind.visibility = View.GONE
                    binding.mHeader.mLayoutResult.visibility = View.GONE
                }
            }
            updateHealthDesc(healthResult)
            //健康状态
            binding.mHeader.mHealthStatus.setImageResource(UserInfoDefin.healthIcon[healthResult + 1])
            updateStarInfo(
                healthResult,
                if (it.data.star.isNullOrEmpty()) 0 else it.data.star.toInt()
            )
        }

        //个人设置信息获取
        mViewModel.settingLive.observe(this) {
            it.data.let { settingBean ->

                if (BuildConfig.isRelease) {//设置极光推送别名
                    JPushInterface.setAlias(
                        requireContext(),
                        settingBean.user.id.toInt(),
                        "user_release_${settingBean.user.id}"
                    )
                }

                Const.mainLiveData.value = settingBean
             //   mViewModel.getWelcomeInfo(settingBean.user.id)
             //   mViewModel.getWarningMsg()//获取预警消息

                requestByDeviceModel()
                // 激活过才能开启定是我任务
                //Log.e("worker", "定时任务开启")

                /*if (mFamilyAdapter.data.isNotEmpty() && mFamilyAdapter.data.size > 0) {
                    mFamilyAdapter.data[0].avatarUrl =
                        if (settingBean.user.avatarUrl.isEmpty()) "" else settingBean.user.avatarUrl
                }*/



                if (settingBean.user.bluetooth.isNullOrEmpty()) {  //没有mac地址表示未绑定
//                    binding.mContent.visibility = View.VISIBLE
                    binding.mHeader.mLayoutResult.visibility = View.GONE
                    binding.mHeader.mBtnBind.visibility = View.VISIBLE
//                    if (!(activity as MainActivity).isDialogShow) {
//                        dialogBind.show()
//                    }
                } else {
                    MyRetrofit.get().BLUETOOTH_MAC = settingBean.user.bluetooth
                    binding.mHeader.mLayoutResult.visibility = View.VISIBLE
                    binding.mHeader.mBtnBind.visibility = View.GONE
                    //重新签名提示
                    val signTime = settingBean.user.esignatureDate
                    if (!signTime.isNullOrEmpty()) {
                        val againTime = RxTimeTool.string2Milliseconds("2022-07-01 21:00:00")
                        val signTime = RxTimeTool.string2Milliseconds(signTime)
                        if (signTime < againTime) {
                            //signDialog.show()
                        }
                    }
               /*     if (CommonUtils.isBlueTooth(MMkvHelper.getInt(Const.Watch_Device_Type))) {//如果是蓝牙设备
                        startGetDeviceInfoLive()
                        if (settingBean.user.bluetooth != MMkvHelper.getString(Const.Blue_Tooth)) {//如果不是同一设备
                            YCBBlueConnectHelper.disconnect()//断开蓝牙，断开后收到BlueToothConnectEvent会自动连接
                            YCBBlueConnectHelper.cancelTimer()
                        } else {
                            LogUtils.d("startConnect::${settingBean.user.bluetooth}")
                            mainUIUpdate(YCBBlueConnectHelper.BLEConnectState.Connecting)//刷新蓝牙连接状态
                            connect(settingBean.user.bluetooth)
                        }
                    }*/
                }

                if (Const.Companion.WatchDevice.LightA3.ordinal == Const.watchType) {//如果是4G设备，设置连接状态与电量信息

                    get24HourReportInfo(showIdInfo)// 这里调用一次接口，防止首次进入App不会刷新评估状态
                }

                MMkvHelper.put(Const.Blue_Tooth, settingBean.user.bluetooth)
                if (!settingBean.user.deviceId.isNullOrEmpty()) {
                    Const.DeviceIdNum = settingBean.user.deviceId
                } else {
                    Const.DeviceIdNum = ""
                }
//                MMkvHelper.saveAccountConfig(requireContext(),settingBean.user.phone,Const.DEVICE_TYPE, settingBean.user.deviceId)
            }
            //个人信息拿到之后再去获取mqtt信息
//            mViewModel.getMqttInfo()
        }

        //定时上报任务
        tenLive.observe(this) {
            LogUtils.d("整十分钟定时任务开启：${RxTimeTool.curTimeString}")
            //开启下一个整10分的休眠
            getNowTime()
            //上传数据
            uploadWhatchData()
        }

        //15秒钟更新一次蓝牙设备信息
        getDeviceInfoLive.observe(this) {
            LogUtils.d("定时更新一次蓝牙设备信息：${RxTimeTool.curTimeString}")
            startGetDeviceInfoLive()

            if (!MMkvHelper.contains(Const.Watch_Device_Type)) {//没有手表型号
                LogUtils.d("没有获取到手表型号")
                return@observe
            }

            if (!CommonUtils.isBlueTooth(MMkvHelper.getInt(Const.Watch_Device_Type))) {//不是蓝牙设备
                LogUtils.d("不是蓝牙设备！")
                return@observe
            }

            if (!YCBBlueConnectHelper.getBlueStatus(false)) {//蓝牙未连接
                LogUtils.d("蓝牙设备未连接！")
                return@observe
            }

            if ((!showIdInfo.isNullOrEmpty() && showIdInfo !=MMkvHelper.getLong(Const.USER_ID).toString())) {//不是当前用户
                LogUtils.d("当前用户与showIdInfo不匹配！")
                return@observe
            }

            LogUtils.d("定时获取一次 DeviceInfo!")
            //连接之后 直接进行数据的同步
            YCBManager.getDeviceInfo { isok, value ->
                mainScope.launch {
                    LogUtils.d("getDeviceInfo isOk:$isok;;; value=$value")
                    if (isok) {//获取到设备信息，设备准备就绪上传手表数据
                    }
                }
            }
        }

        //小贴士
        mViewModel.tipsLive.observe(this) {
            LogUtils.d("TipsData:${it.data.size}")
            var list = mutableListOf<String>()
            it.data.forEach { tipsBean ->
                list.add("${tipsBean.title}${tipsBean.content}")
            }
            setTips(list)
        }

        //步数上传
        mViewModel.uploadStep.observe(this) {
            //步数上传成功
            //YCBManager.deleteHistory(YCBOrder.STEP_HISTORY)
            LogUtils.d("step upload success ")
            mViewModel.getAllInfo(showIdInfo, false)
        }

        //手表信息组装上传
        mViewModel.allDataInfo.observe(this) {
            if (null == it || it["data"] == null || it["data"] !is ArrayList<*>) {
                LogUtils.d("手表数据：暂时无数据...")
                getXtInfo(showIdInfo)//如果手表没数据也需要获取获取血糖信息
                get24HourReportInfo(showIdInfo)//如果手表没数据也需要获取24小时日报
                return@observe
            }

            LogUtils.d("手表数据：全部信息开始上传...")
            //是否为错误数据
            var existError = false

            val lists = it["data"] as ArrayList<Any>
            val array = JSONArray()
            lists.forEach { bean ->

                val json = JSONObject()
                val nowData = bean as java.util.HashMap<String, *>
                val iterator = nowData.iterator()
                while (iterator.hasNext()) {
                    val next = iterator.next()
                    val values = if (next.value is Long) (next.value as Long) / 1000 else next.value
                    when (next.key) {
                        "OOValue" -> json.put("ooValue", values)

                        "DBPValue" -> {
                            val sbp = nowData["SBPValue"] as Int
                            val dbp = nowData["DBPValue"] as Int
                            //医学上是大值  收缩压
                            //小值
                            json.put("sbpValue", min(sbp, dbp))
                        }
                        "SBPValue" -> {
                            //医学上是小值  舒张压
                            //大值
                            val sbp = nowData["SBPValue"] as Int
                            val dbp = nowData["DBPValue"] as Int
                            json.put("dbpValue", max(sbp, dbp))
                        }

                        else -> json.put(next.key, values)
                    }
                }
                if (json.has("startTime")) {
                    val times = json.get("startTime").toString().toLong()

                    if (times < 0 || times > System.currentTimeMillis() / 1000) { //错误数据 不使用
                        existError = true
                    } else {
                        array.put(json)
                    }
                }
            }
//            //错误数据保存到本地日志
//            if (existError) {
//                  saveFile(it.toString()) //存到本地日志
//            }

            LogUtils.d("手表数据：array Length:${array.length()}")
            if (array.length() > 0) {
//                var lastJson = array[array.length() - 1] as JSONObject
//                lastJson.put("original", it.toString())
                mViewModel.uploadAllInfo(array)
            }
        }

        //手表数据上传
        mViewModel.uploadMultiple.observe(this) {
            CommonToastUtils.showSucceedToast(R.string.upload_data_success)
//            showSucceedToast(requireContext().getString(R.string.upload_data_success))
            LogUtils.d("all data upload success ")
            get24HourReportInfo(showIdInfo)//数据上传成功后获取24小时日报
            getXtInfo(showIdInfo)//数据上传成功后获取血糖信息
            YCBManager.deleteHistory(YCBOrder.DELETE_ALL) //删除 数据
            mainScope.launch {
                delay(500)
                mViewModel.getAllInfo(showIdInfo, false)
            }
        }
    }

    private fun setTips(datas: List<String>) {
        val marqueeFactory: SimpleMF<String?> = SimpleMF(context)
        marqueeFactory.data = datas
        binding.mHeader.simpleMarqueeView.setMarqueeFactory(marqueeFactory)
        binding.mHeader.simpleMarqueeView.setDrawable(
            getDrawable(R.mipmap.ic_tips_new),
            null,
            null,
            null
        )
        if (binding.mHeader.simpleMarqueeView.isFlipping) {
            binding.mHeader.simpleMarqueeView.stopFlipping()
        }
//        binding.mCom.simpleMarqueeView.flipInterval = 3 * 1000//轮播间隔时间
        binding.mHeader.simpleMarqueeView.startFlipping()
    }

    /**
     * 通过设备型号来处理不同业务逻辑
     */
    private fun requestByDeviceModel() {
        when (MMkvHelper.getInt(Const.Watch_Device_Type)) {//如果是4GA3设备，则隐藏心电板块
            Const.Companion.WatchDevice.LightA3.ordinal -> {
                getXtInfo(showIdInfo, false)//获取血糖信息
            }

            else -> {
                if (!YCBBlueConnectHelper.isBlueExits()) {//检查蓝牙设备，如未发现蓝牙设备则获取用户上次的血糖信息和24小时信息
                    LogUtils.d("未发现蓝牙设备...")
                    getXtInfo(showIdInfo)//如果手表没数据也需要获取获取血糖信息
//                    get24HourReportInfo(showIdInfo)//如果手表没数据也需要获取24小时日报
                }
                if (tenJob == null) {
                    getNowTime() // 整十分钟数据上报休眠开始
                } else {
                    tenJob!!.cancel()
                    getNowTime() // 整十分钟数据上报休眠开始
                }
            }
        }
    }

    /**
     * 计算要休眠的时间
     */
    private fun getNowTime() {
        val tenTimes = 11 * 60 * 1000  //整十分钟对应的毫秒数
        val time = RxTimeTool.getCurTimeString(SimpleDateFormat("mm")).toInt()
        val sPrefix = time / 10  //当前时间对应的整分钟数
        val nowTimeStr =
            RxTimeTool.getCurTimeString(SimpleDateFormat("yyyy-MM-dd HH")) + ":${sPrefix * 10}:00" //整点时间
        val nowTimeMill = RxTimeTool.string2Milliseconds(nowTimeStr)//整分钟数对应的毫秒数

        val nextTimeMill = nowTimeMill + tenTimes //下个整十分钟数对应的毫秒数
        val sleepSec = nextTimeMill - System.currentTimeMillis() //距离下个时间要休眠的毫秒数

        startTenLive(sleepSec)
    }

    /**
     * 十分钟休眠开始
     * times  需要休眠的毫秒数
     */
    private fun startTenLive(times: Long) {
        LogUtils.d("休眠开始时间：${RxTimeTool.curTimeString}")
        LogUtils.d("休眠时长：${times}")
        tenJob = mainScope.launch(Dispatchers.IO) {
            delay(times)
            LogUtils.d("休眠结束：${RxTimeTool.curTimeString}")
            tenLive.postValue("")
        }
    }

    /**
     * 15秒钟一次更新
     */
    private fun startGetDeviceInfoLive() {
        getDeviceInfoJob = mainScope.launch(Dispatchers.IO) {
            delay(1000 * 15)
            LogUtils.d("休眠结束：${RxTimeTool.curTimeString}")
            getDeviceInfoLive.postValue("")
        }
    }


    private var mDisposable: Disposable? = null
    fun startUpdateHealthInfoLive(){
        LogUtils.e("DynamicManagementFrag","刷新数据")
        getHealthInfoJob  = mainScope.launch (Dispatchers.IO){
            if(mDisposable == null){
                Observable.interval(1000 * 60,60*1000,TimeUnit.MILLISECONDS)
                    .observeOn(AndroidSchedulers.mainThread()).subscribe(object : Observer<Long>{
                        override fun onSubscribe(d: Disposable) {
                            mDisposable = d
                        }

                        override fun onError(e: Throwable) {
                            cancelTimer()
                        }

                        override fun onComplete() {
                            cancelTimer()
                        }

                        override fun onNext(t: Long) {
                            LogUtils.e("DynamicManagementFrag","刷新数据${t}s")
                            isJob = true
                            mViewModel.getAllInfo(showIdInfo, false,true)
                        }

                    })
            }

        }

    }

    fun cancelTimer(){
        getHealthInfoJob?.cancel()
        mDisposable?.let {
            if(it.isDisposed){
                LogUtils.e("DynamicManagementFrag","取消定时")
                it.dispose()
            }

        }
    }

    override fun onDestroyView() {
        cancelTimer()
        super.onDestroyView()
    }

    private fun mainUIUpdate(connectState: YCBBlueConnectHelper.BLEConnectState) {
        mainScope.launch(Dispatchers.Main) {
            when (connectState) {
                YCBBlueConnectHelper.BLEConnectState.Connecting -> {

                }

                YCBBlueConnectHelper.BLEConnectState.Connected -> {
                    getConnectStatus()
                }

                YCBBlueConnectHelper.BLEConnectState.DisConnect -> {
                    //断开连接重置状态 为了重新连接自后可以进行睡眠上传
                    initBlueToothStatu()
                }
            }
        }
    }

    private fun updateStarInfo(status: Int, star: Int) {
        mViewModel.allData.value?.apply {
            if (data.adorn.wearCount <= 3) {
                binding.mHeader.mDescInfo.text =
                    getString(R.string.model_day, "" + (4 - data.adorn.wearCount))
                return
            }
        }

        binding.mHeader.mDescInfo.apply {
            text = ""

            append(getString(R.string.health_star_mark))

            var selectStarImage = UserInfoDefin.getStarImage(context, status)
            selectStarImage.setBounds(
                0,
                0,
                (selectStarImage.minimumWidth / 1.4).toInt(),
                (selectStarImage.minimumHeight / 1.4).toInt()
            )

            var unSelectStarImage = context.getDrawable(com.zj365.health.R.mipmap.icon_insufficient)
            unSelectStarImage?.setBounds(
                0,
                0,
                (unSelectStarImage.minimumWidth / 1.4).toInt(),
                (unSelectStarImage.minimumHeight / 1.4).toInt()
            )

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

    }

    /**
     * 蓝牙链接
     */
    private fun connect(mac: String) {
        if (!CommonUtils.isBlueTooth(MMkvHelper.getInt(Const.Watch_Device_Type))) {//如果不是蓝牙设备，不进行连接
            return
        }

        if (mac.isEmpty()) {
            initBlueToothStatu()
            return
        }

        if (!checkBlueConnectPermission(requireContext())) {
            CommonToastUtils.showToast("请开启App蓝牙搜索权限！")
            getBluePermission(requireContext()) {
                if (it) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !isGpsOpen(requireContext())) {
                        requestGPSPermission()
                    }
                }
            }
            return
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !isGpsOpen(requireContext())) {
            CommonToastUtils.showToast("请打开GPS权限！")
            requestGPSPermission()
            return
        }

        mainScope.launch(Dispatchers.IO) {
            LogUtils.d("HealthFrag Connect!!!")
            YCBBlueConnectHelper.connectionBlueTooth(mac, true) {
                mainUIUpdate(it)
            }
        }
    }

    //蓝牙连接状态之后 数据上传
    private fun getConnectStatus() {
        LogUtils.d("getConnectStatus!")
        if (YCBBlueConnectHelper.getBlueStatus(false)) {
            LogUtils.d("start get DeviceInfo!")

            //连接之后 直接进行数据的同步
            YCBManager.getDeviceInfo { isok, value ->
                mainScope.launch {
                    LogUtils.d("getDeviceInfo isOk:$isok;;; value=$value")
                    if (isok) {//获取到设备信息，设备准备就绪上传手表数据

                        uploadWhatchData()

                        mViewModel.settingLive.value?.let {
                            MyWorkManger.setMyWork(
                                MyApp.instance!!,
                                it.data.user.bluetooth
                            )  //开启后台定时上传任务
                        }

                    } else {//如果获取手表信息失败，断开连接以后让用户手动连接
                        YCBBlueConnectHelper.disconnect()
                        initBlueToothStatu()
                    }
                }
            }
        } else {
            //断开连接重置状态 为了重新连接自后可以进行睡眠上传
            initBlueToothStatu()
        }
    }

    /**
     * 更新健康状态
     */
    private fun updateHealthDesc(healthStatus: Int) {
        canGoto24Healthresult = healthStatus != 0 && healthStatus != -1
        binding.mHeader.mDesc.apply {
            text = UserInfoDefin.getHealthArray(requireContext())[healthStatus + 1]
            //todo 数据不足 不允许进入健康管理
            setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    UserInfoDefin.healthCol[healthStatus + 1]
                )
            )
        }
    }


    private fun initBlueToothStatu() {

    }

    private fun requestGPSPermission() {
        reqGpsPermissionDialog.show()
    }

    private fun updateBadgeNum(num: Int) {
        if (num > 0) {
            val badgeText = if (num > 99) "99+" else "$num"
            binding.mBadge.text = badgeText
            binding.mBadge.post {
                val layoutParams = binding.mBadge.layoutParams as ViewGroup.LayoutParams
                val text = binding.mBadge.text.toString()
                binding.mBadgeCard.radius = binding.mBadge.height / 2f
                val textWidth = binding.mBadge.paint.measureText(text)
                if (binding.mBadge.height >= textWidth) {   //等宽高的圆形
                    layoutParams.width = binding.mBadge.height

                } else {  //宽高不等 将宽度两边加10
                    layoutParams.width = textWidth.toInt() + 20
                }
                binding.mBadge.layoutParams = layoutParams
            }
            binding.mBadgeCard.visibility = View.VISIBLE
        } else {
            binding.mBadgeCard.visibility = View.GONE
        }
    }

    private fun updateWarningInfo(sysMsg: MessageBean.SysMsg?) {
       /* if (sysMsg == null || mFamilyAdapter.position > 0) {  //如果不是自己，不显示预警消息
            binding.mHeader.llWarning.visibility = View.GONE
            return
        } else if (mFamilyAdapter.position == 0 || mFamilyAdapter.position == -1) {
            binding.mHeader.llWarning.visibility = View.VISIBLE
        }*/
        notifyStatus = sysMsg?.notifyStatus
        if (notifyStatus == 0) {
            //未读  显示预警消息
            binding.mHeader.llWarning.visibility = View.VISIBLE
        } else {
            //已读 显示预警消息
            binding.mHeader.llWarning.visibility = View.GONE
        }
        binding.mHeader.tvWarning.isSelected = true
        binding.mHeader.tvWarning.text = sysMsg?.notifyContent
    }

    /**
     * 设置用户头像
     */
    private fun setUserImage(userId: String, headerImage: String?, sex: String) {
        binding.mHeader.mHeaderImage.apply {
            tag = userId
            setImageUser(requireContext(), headerImage, sex)
            setOnClickListener {
                if (tag.toString().isEmpty() || tag.toString() == "0" ||
                    Const.mainLiveData.value?.user?.id.toString() == userId.toString()
                ) {
                    RouteManager.goAct(ARouterUrl.BASE_INFO_CHANGE, bundle)
                }
            }
        }
    }

    /**
     * 获取血糖信息
     */
    private fun getXtInfo(userId: String, isShowLoading: Boolean = false) {
        mViewModel.getXtInfo(userId, isShowLoading)
    }

    /**
     * 获取24小时健康报告
     */
    private fun get24HourReportInfo(userId: String, isShowLoading: Boolean = false) {
        mViewModel.get24HourReportInfo(userId, isShowLoading)
    }


    private fun blueTooth(): Boolean {
        return CommonUtils.isBlueTooth(MMkvHelper.getInt(Const.Watch_Device_Type))
    }

    //家人信息改变 刷新
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun familyChange(event: FamilyEvent) {
  //      mViewModel.getMyFamilyList()
    }

    /**
     * 24小时健康状态更新事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun health24HourStatusUpdate(event: Health24HourStatusEvent) {
        if (-2 != event.healthStatus) {
            updateHealthDesc(event.healthStatus)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun refresh(event: MyInfoEvent) {
        if (dialogBind.isShowing) {
            dialogBind.dismiss()
        }
        request()
    }

    //绑定状态下的蓝牙连接状态
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun blueToothStatus(event: BlueToothConnectEvent) {
        LogUtils.d("blueToothStatus change!!")
        CommonUtils.getBlueToothMac()?.let {
            connect(it)
        }
    }

    //workmanager 后台上传任务
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun workManagerSuccess(event: WorkManagerEvent) {
        //上传成功回传刷新
        LogUtils.d("work is ok")
        mViewModel.getAllInfo(showIdInfo, false)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateHealthInfo(event:ChangeFamilyEvent){
        isJob= false
        mViewModel.getAllInfo(event.showUserId, false)
        getXtInfo(event.showUserId)
        get24HourReportInfo(event.showUserId)
    }

    override fun onDestroy() {
        super.onDestroy()
        tenJob?.cancel()
        cancelTimer()
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun loginOutChange(event: LoginOutEvent){
        LogUtils.e("DynamicManagementFrag","loginOutChange")
        isJob = false
       cancelTimer()

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun addSuccess(event: AddSuccessEvent){
        request()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLoginOrRegisterSuccess(event: LoginOrRegisterEvent){
        showIdInfo =if (MMkvHelper.getLong(Const.USER_ID).toString() == "0") {
            ""
        } else {
            MMkvHelper.getLong(Const.USER_ID).toString()
        }

        if(!TextUtils.isEmpty(showIdInfo)){
            //  if (BuildConfig.isRelease) {//设置极光推送别名
            JPushInterface.setAlias(
                requireContext(),
                MMkvHelper.getLong(Const.USER_ID).toInt(),
                "user_release_${MMkvHelper.getLong(Const.USER_ID)}"
            )
            //     }
        }

        getXtInfo(showIdInfo)
        isJob = false
        get24HourReportInfo(showIdInfo)
        request()
        uploadWhatchData()

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun bindDevSuccess(event: BindDevEvent){
        getXtInfo(showIdInfo)
        isJob = false
        get24HourReportInfo(showIdInfo)
        request()
        uploadWhatchData()
    }

    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
        AmapInit.startLocation(requireContext()) {
            MMkvHelper.put(Const.LONGITUDE,it.longitude)
            MMkvHelper.put(Const.LATITUDE,it.latitude)
            mViewModel.getWeather()

        }
    }

    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
    }
}