package com.xty.common.work

import android.content.Context
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.tamsiree.rxkit.RxTimeTool
import com.xty.common.bracelet.YCBBlueConnectHelper
import com.xty.common.bracelet.YCBManager
import com.xty.common.bracelet.YCBOrder
import com.xty.common.Const
import com.xty.common.LogUtils
import com.xty.common.event.WorkManagerEvent
import com.xty.common.util.CommonUtils
import com.xty.network.ApiInterface
import com.xty.network.MyRetrofit
import kotlinx.coroutines.*
import org.greenrobot.eventbus.EventBus
import org.json.JSONArray
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.*

/**
 * 后台上传
 */
class UploadManager(context: Context, workerParams: WorkerParameters) :
    Worker(context, workerParams) {
    val basvm by lazy { WorkHttp() }

    val handler by lazy {
        CoroutineExceptionHandler { coroutineContext, throwable ->

        }
    }

    override fun doWork(): Result {
        LogUtils.d("worker", "工作开始${RxTimeTool.curTimeString} ")


        //如果蓝牙连接的话 则进行数据的上传 否则不做任何操作
            if (MyWorkManger.isCancel) {
                MyWorkManger.isCancel = false
            }
            if (YCBBlueConnectHelper.getBlueStatus(false)) {
                LogUtils.d("worker", "获取蓝牙信息")
               // getSleepNew()  后台不上传睡眠数据
                getStep()
                getWatchInfo()
            }
        return Result.success()
    }


    /**
     * 全部数据
     */
    fun getWatchInfo() {

        YCBManager.getAllData {
            if (null == it) return@getAllData
            MainScope().launch {
                var array = JSONArray()
                val lists = it["data"] as ArrayList<Any>
                lists.forEach { bean ->
                    var json = JSONObject()
                    var nowData = bean as HashMap<String, *>
                    val iterator = nowData.iterator()
                    while (iterator.hasNext()) {
                        val next = iterator.next()
                        var values =
                            if (next.value is Long) (next.value as Long) / 1000 else next.value
                        when (next.key) {
                            "OOValue" -> json.put("ooValue", values)
                            /* "SBPValue" -> json.put("sbpValue", values)
                             "DBPValue" -> json.put("dbpValue", values)*/


                            "DBPValue" -> {
                                var sbp = nowData["SBPValue"] as Int
                                var dbp = nowData["DBPValue"] as Int
                                //医学上是大值  收缩压
                                //小值
                                json.put("sbpValue", Math.min(sbp, dbp))
                            }
                            "SBPValue" -> {
                                //医学上是小值  舒张压
                                //大值
                                var sbp = nowData["SBPValue"] as Int
                                var dbp = nowData["DBPValue"] as Int
                                json.put("dbpValue", Math.max(sbp, dbp))
                            }
                            else -> json.put(next.key, values)
                        }
                    }
                    if(json.has("startTime")){
                        var times=json.get("startTime").toString().toLong()

                        if(times<0||times>System.currentTimeMillis()/1000){ //错误数据 不使用
                           // 时间戳不能小于0 并且大于当前时间戳
                        }else{
                            array.put(json)
                        }
                    }
                }
                basvm.startHttp {
                    var body = MyRetrofit.get().create(ApiInterface::class.java)
                        .uploadAllInfo(MyRetrofit.get().getRequestBody(array.toString()))
                    if (body.code == 0) {
                        LogUtils.d("worker数据", "全部数据")
                        YCBManager.deleteHistory(YCBOrder.DELETE_ALL) //删除 数据
                        isUploadMain()
                    }
                }

            }
        }
    }

    /**
     * 获取历史步数
     */
    fun getStep() {
        YCBManager.getHistoryInfo(YCBOrder.STEP_DATA) {
            MainScope().launch {
                withContext(Dispatchers.IO) {
               /*     var jsonArray = JSONArray()
                    it.forEach { map ->
                        var info = map as HashMap<*, *>
                        var 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)
                    }
                    */
                    var jsonArray =JSONArray()
                    var arrayOrigin=JSONArray()
                    for(i in 0 until it.size){
                        var  info=it[i] as HashMap<String,Any>
                        var jsonOrigin=JSONObject()
                        for((k,v) in info){
                            jsonOrigin.put(k,v)
                        }
                        arrayOrigin.put(jsonOrigin)
                        var dataDayStr=RxTimeTool.milliseconds2String(System.currentTimeMillis(), SimpleDateFormat("yyyy-MM-dd"))
                        var todayStartTime= RxTimeTool.string2Milliseconds("$dataDayStr 00:00:00")  //今天0点的时间

                        var startTime=(info["sportStartTime"] as Long)
                        if(startTime < todayStartTime){
                            continue
                        }
                        var 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)
                    }

                    basvm.startHttp {
                        var body = MyRetrofit.get().create(ApiInterface::class.java)
                            .uploadStep(MyRetrofit.get().getRequestBody(jsonArray.toString()))
                        if (body.code ==  0) {
                            LogUtils.d("worker数据", "历史步数上传完毕")
                           // YCBManager.deleteHistory(YCBOrder.STEP_HISTORY)
                        }
                    }
                }
            }
        }
    }

    fun getSleepNew() {
            YCBManager.getHistoryInfo(YCBOrder.SLEEP_DATA) {
                MainScope().launch {
                    var arraySleep = JSONArray()
                    var rawdata= sleepOriganData(it)
                    for(i in 0 until it.size){
                        var json = JSONObject()
                        var sleepDetailArray = JSONArray() //详细的睡眠时间
                        var  lastData=  it[i]  as   HashMap<*, *>
                        var  startTime=lastData["startTime"]as Long
                        var  endTime=lastData["endTime"]as Long

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

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

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

                        listSleepData.forEach {
                            var value = it as HashMap<*, *>
                            var jsonValue = JSONObject()
                            jsonValue.put("sleepStartTime", (value["sleepStartTime"] as Long)/1000)
                            jsonValue.put("sleepLen", value["sleepLen"] as Int)
                            jsonValue.put("sleepType", value["sleepType"] as Int)
                            CommonUtils.getMyUserInfo()?.let {
                                jsonValue.put("userId", it.id)
                                jsonValue.put("createBy",it.name)
                            }
                            sleepDetailArray.put(jsonValue)
                        }
                        CommonUtils.getMyUserInfo()?.let {
                            json.put("userId", it.id)
                            json.put("createBy",it.name)
                        }
                        json.put("lightSleepCount", lightSleepCount)  //浅睡次数
                        json.put("deepSleepCount", deepSleepCount)  //深睡次数
                        json.put("hmWatchSleepData", sleepDetailArray)
                        json.put("lightSleepTotal", Math.max(lightAll,deepLightAll))   //潜睡时长
                        json.put("deepSleepTotal", Math.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){
                        basvm.startHttp {
                            var body = MyRetrofit.get().create(ApiInterface::class.java)
                                .uploadSleep(MyRetrofit.get().getRequestBody(arraySleep.toString()))
                            if (body.code ==  0) {
                                LogUtils.d("worker数据", "睡眠上传完毕")
                                YCBManager.deleteHistory(YCBOrder.SLEEP_HISTORY)
                                isUploadMain()
                            }
                        }
                        //mViewModel.uploadSleep(arraySleep)
                    }
                }
            }
    }
    /**
     * 睡眠时间
     */
      fun getSleep() {
        YCBManager.getHistoryInfo(YCBOrder.SLEEP_DATA) {
            MainScope().launch {
                var lightAll = 0
                var deepLightAll = 0
                var startTimeLong = 0L //开始时间
                var allSleepCount = 0 //睡眠清醒次数
                var sleepDetailArray = JSONArray() //详细的睡眠时间
                var arraySleep = JSONArray()
                var json = JSONObject()
                var rawdata = sleepOriganData(it)
                for (i in 0 until it.size) {
                    var lastData = it[i] as HashMap<*, *>
                    var listSleepData = lastData["sleepData"] as ArrayList<*>

                    var currertTimelong = lastData["startTime"] as Long
                    var dataDayStr = RxTimeTool.milliseconds2String(
                        System.currentTimeMillis(),
                        SimpleDateFormat("yyyy-MM-dd")
                    )
                    var yesterday =
                        RxTimeTool.string2Milliseconds("$dataDayStr 00:00:00") - 4 * 60 * 60 * 1000  //每晚8点开始进行数据采集

                    //理论上从昨晚20：00 开始进行采集
                    //所以当时间小于昨天晚上的8点认为是前天的数据 不予使用
                    if (yesterday > formatTime(currertTimelong)) {
                        continue
                    }
                    //赋值 开始时间
                    if (startTimeLong == 0L) {
                        startTimeLong = currertTimelong
                    }

                    ++allSleepCount

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


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

                }
                json.put("hmWatchSleepData", sleepDetailArray)
                json.put("lightSleepTotal", Math.max(lightAll, deepLightAll))   //潜睡时长
                json.put("deepSleepTotal", Math.min(lightAll, deepLightAll))  //深睡时长

                var endData = it[it.size - 1] as HashMap<*, *>
                json.put("startTime", startTimeLong / 1000) //开始时间
                json.put("endTime", (endData["endTime"] as Long) / 1000)  //结束时间
                json.put("soberSleepCount", --allSleepCount) //清醒次数
                json.put("original", rawdata.toString())
                json.put("os", "android")
                arraySleep.put(json)
                basvm.startHttp {
                    var body = MyRetrofit.get().create(ApiInterface::class.java)
                        .uploadSleep(MyRetrofit.get().getRequestBody(arraySleep.toString()))
                    if (body.code ==  0) {
                        LogUtils.d("worker数据", "睡眠上传完毕")
                        YCBManager.deleteHistory(YCBOrder.SLEEP_HISTORY)
                        isUploadMain()
                    }
                }
            }
        }
    }

    private fun isUploadMain() {
        LogUtils.d("worker数据", "任务处理完毕 进入下一个循环等待时间")
        EventBus.getDefault().post(WorkManagerEvent())
    }

    /**
     * 由于SDK问题返回的时间存在秒和毫秒 两种值
     * 这里 返回的类型为毫秒数
     */
    private fun formatTime(time: Long): Long {
        if (time > 9999999999) {
            return time
        }
        return time * 1000
    }

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

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

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

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

            var listSleepData = lastData["sleepData"] as ArrayList<*>
            var sleepArray = JSONArray()
            listSleepData.forEach {
                var value = it as HashMap<*, *>
                var jsonValue = JSONObject()
                jsonValue.put("sleepStartTime", (value["sleepStartTime"] as Long) / 1000)
                jsonValue.put("sleepLen", value["sleepLen"] as Int)
                jsonValue.put("sleepType", value["sleepType"] as Int)
                sleepArray.put(jsonValue)
            }
            json.put("sleepData", sleepArray)
            array.put(json)
        }

        return array

    }

}