package com.xty.common.bracelet

import com.hjq.toast.ToastUtils
import com.xty.common.LogUtils
import com.yucheng.ycbtsdk.AITools
import com.yucheng.ycbtsdk.Constants
import com.yucheng.ycbtsdk.YCBTClient
import com.yucheng.ycbtsdk.response.BleDataResponse
import com.yucheng.ycbtsdk.response.BleRealDataResponse


object YCBManager {

    const val TAG = "YCBManager"



    /**
     * 数据采集配置
     *
     * collectLong  采集时常  秒
     * collectIntLong 采集间隔 分钟
     *0x00: PPG 0x01: 加速度数据 0x02：ECG 0x03：温湿度 0x04：环境光 0x05：体温
     */

    fun settting(type: Int, collectLong: Int, collectIntLong: Int) {
        LogUtils.d(TAG, "settting type:$type;;;collectLong:$collectLong;;;collectIntLong:$collectIntLong")
        YCBTClient.settingDataCollect(
            0x01, type, collectLong, collectIntLong
        ) { code, ratio, resultMap -> LogUtils.d("环境光code=$code") }
    }

    /**
     * 数据采集配置
     *
     * collectLong  采集时常  秒
     * collectIntLong 采集间隔 分钟
     *0x00: PPG 0x01: 加速度数据 0x02：ECG 0x03：温湿度 0x04：环境光 0x05：体温
     */

    fun setttingPpg(collectLong: Int, collectIntLong: Int) {
        LogUtils.d(TAG, "collectLong:$collectLong;;;collectIntLong:$collectIntLong;;;")
        YCBTClient.settingPpgCollect(
            0x01, collectLong, collectIntLong
        ) { code, ratio, resultMap -> LogUtils.d("环境光code=$code") }
    }


    /**
     * 心率监测
     * 传说中设置一个即可
     * collectLong  采集时常  秒
     * collectIntLong 采集间隔 分钟
     *0x00: PPG 0x01: 加速度数据 0x02：ECG 0x03：温湿度 0x04：环境光 0x05：体温
     */

    fun settingHeartMonitor() {
        LogUtils.d(TAG, "settingHeartMonitor")
        YCBTClient.settingHeartMonitor(
            0x01, 10
        ) { code, ratio, resultMap ->  LogUtils.d("环境光code=$code") }
    }






    /**
     * 查询所有数据
     */
    fun getAllData(result: (map: MutableMap<String, Any>?) -> Unit) {
        LogUtils.d(TAG, "getAllData")
        if (!YCBBlueConnectHelper.getBlueStatus(false)) {
            return
        }
        YCBTClient.healthHistoryData(
            YCBOrder.ALL_DATA
        ) { code, ratio, hashMap ->
            if (hashMap != null) {
                result.invoke(hashMap as MutableMap<String, Any>)
            } else {
                // ToastUtils.show("无历史数据")
                result.invoke(null)
            }
        }
    }

    /**
     *  相关历史数据
     */
    fun getHistoryInfo(type: Int, result: (list: ArrayList<Any>) -> Unit) {
        LogUtils.d(TAG, "getHistoryInfo type:$type")
        if (!YCBBlueConnectHelper.getBlueStatus(false)) {
            return
        }
        YCBTClient.healthHistoryData(type) { code, ratio, hashMap ->
            if (hashMap != null) {
                val lists = hashMap["data"]
                if (null != lists){
                    if (lists is ArrayList<*>){
                        result.invoke(lists as ArrayList<Any>)
                    }
                }
            }
        }
    }


    /**
     * 开始心电测量
     */
    fun startEcg(
        ecgInfo: (data: MutableList<Integer>?) -> Unit,
//        hrvInfo: (hrv: String) -> Unit,
        status: (code: Int) -> Unit,
        openStatus: (status: Boolean) -> Unit,
        hertInfo: (mHeart: String, mDBP: String, mSBP: String, mHRV: String) -> Unit,
        audio: () -> Unit


    ) {
        LogUtils.d(TAG, "startEcg")

        if (!YCBBlueConnectHelper.getBlueStatus()) {
            openStatus.invoke(false)
            return
        }
        openStatus.invoke(true)
        AITools.getInstance().init()
        AITools.getInstance().setAIDiagnosisHRVNormResponse {
            /* float heavy_load;//负荷指数 （越大越不好 传出）
                                     float pressure;//压力指数 （越大越不好 传出）
                                     float HRV_norm;//HRV指数 （越大越好 传出）
                                     float body;//身体指数 （越大越好 传出）
                                     int flag = -1;//0正常 -1错误*/
            //System.out.println("chong--------AIDiagnosis");
        }
        YCBTClient.appEcgTestStart(object : BleDataResponse {
            override fun onDataResponse(p0: Int, p1: Float, p2: java.util.HashMap<*, *>?) {
            }
        }, object : BleRealDataResponse {
            override fun onRealDataResponse(i: Int, hashMap: java.util.HashMap<*, *>?) {

                if (hashMap != null) {
                    val dataType = hashMap["dataType"] as Int
                    LogUtils.d("onRealDataResponse $i dataType $dataType")
                    if (i == Constants.DATATYPE.Real_UploadECG) {
                        val data = hashMap["data"] as MutableList<Integer>?
                        ecgInfo.invoke(data)   //ecg 心电信息
                    }/* else if (i == Constants.DATATYPE.Real_UploadECGHrv) {
                        var hrv = hashMap["data"] as Float
                        Log.e("HRV", "$hrv")
                        hrvInfo.invoke("$hrv")
                    } */else if (i == Constants.DATATYPE.Real_UploadECGRR) {
                        /*     mHandler.sendEmptyMessage(22)
                             mHandler.sendEmptyMessage(22)
                             val param = hashMap["data"] as Float
                             Log.e("qob", "RR invo $param")*/
                        audio.invoke()
                    } else if (i == Constants.DATATYPE.Real_UploadBlood) {
                        var mHeart = hashMap?.get("heartValue") as Int //心率
                        var mDBP = hashMap["bloodDBP"] as Int //高压
                        var mSBP = hashMap["bloodSBP"] as Int //低压
                        LogUtils.d("onRealDataResponse:  $mHeart ,$mDBP,$mSBP")
                        var mHRV = 0
                        if (hashMap["hrv"] != null && hashMap["hrv"] as Int != 0) {
                            hashMap["hrv"] as Int
                        }
                        hertInfo.invoke("$mHeart", "$mDBP", "$mSBP", "$mHRV")
                    } else if (i == Constants.DATATYPE.AppECGPPGStatus) {
                        val EcgStatus = hashMap["EcgStatus"] as Int
                        val PPGStatus = hashMap["PPGStatus"] as Int
                        status.invoke(EcgStatus)
                        if (EcgStatus == 0) {
                            LogUtils.d("ecg心电接触良好")
                        } else if (EcgStatus == 1) {
                            LogUtils.d("心电电极脱落")
                        } else if (EcgStatus == 2) {
                            LogUtils.d("点击脱落")
                        }
                    }
                }
            }
        }
        )

    }

    //结束心电测量
    fun ecgMeasureStop(result: () -> Unit) {
        LogUtils.d(TAG, "ecgMeasureStop")
        YCBTClient.appEcgTestEnd { code, ratio, resultMap ->
            println("chong-------code==$code")
            if (code == 0) {
                result.invoke()  //开始执行分析
            }
        }
    }

    //心电 ecg 结束分析
    fun getAiResult(result: (heart: String, type: Int, isisAfib: Boolean) -> Unit) {
        LogUtils.d(TAG, "getAiResult")
        // AIDataBean mAiResult = AIData.a().getAIResult();
        AITools.getInstance().getAIDiagnosisResult { aiDataBean ->
            if (aiDataBean != null) {
                LogUtils.d("getAIDiagnosisResult heart:${aiDataBean.heart} is_atrial_fibrillation:${aiDataBean.is_atrial_fibrillation};;grstype:${aiDataBean.qrstype}")
                val heart = aiDataBean.heart //心率
                when (aiDataBean.qrstype) {
                    1 -> {
                        // 正常
                    }
                    5 -> {
                        //室性早博
                    }
                    9 -> {
                        //房性早博
                    }
                    15 -> {
                        //噪声

                    }

                }

                // 1正常心拍 5室早心拍 9房早心拍  14噪声
                val mDiagnoseType: Int = aiDataBean.qrstype //类型 1正常心拍 5室早心拍 9房早心拍  14噪声


                // 诊断类型  1正常  4 ,5 ,9异常
                //mDiagnoseType = aiDataBean.qrstype //类型 1正常心拍 5室早心拍 9房早心拍  14噪声
                // 是否房颤
                var isAfib = aiDataBean.is_atrial_fibrillation //是否心房颤动
                result.invoke("$heart", aiDataBean.qrstype, isAfib)
            }
        }
    }

    /**
     * 设置左右手佩戴
     * 左手  0x00
     * 右手 0x01
     */
    fun settingHandWear(type: Int, isOk: (ok: Boolean) -> Unit) {
        LogUtils.d(TAG, "settingHandWear type:$type")
        if (!YCBBlueConnectHelper.getBlueStatus()) {
            isOk(false)
            return
        }

        YCBTClient.settingHandWear(type) { code, ratio, hashMap ->
            if (code == Constants.CODE.Code_OK) {
                isOk(true)
                ToastUtils.show("设置成功")
            } else {
                isOk(false)
                ToastUtils.show("设置失败")
            }
        }
    }

    /**
     * 恢复出场设置
     */
    fun settingRestoreFactory(isOk: (ok: Boolean) -> Unit) {
        LogUtils.d(TAG, "settingRestoreFactory")
        if (!YCBBlueConnectHelper.getBlueStatus()) {
            return
        }
        YCBTClient.settingRestoreFactory() { code, ratio, hashMap ->
            if (code == Constants.CODE.Code_OK) {
                ToastUtils.show("设置成功")
                isOk(true)
            }
        }
    }

    /**
     * 亮度设置
     * 0x00:低 0x01:中 0x02:高 0x03:自动 0x04:较低 0x05:较高
     */
    fun settingDisplayBrightness(type: Int, isOk: (ok: Boolean) -> Unit) {
        LogUtils.d(TAG, "settingDisplayBrightness type:$type")
        if (!YCBBlueConnectHelper.getBlueStatus()) {
            isOk(false)
            return
        }
        YCBTClient.settingDisplayBrightness(type) { code, ratio, hashMap ->
            if (code == Constants.CODE.Code_OK) {
                isOk(true)
                ToastUtils.show("设置成功")
            } else {
                isOk(false)
                ToastUtils.show("设置失败")
            }
        }
    }

    /**
     * 设备主界面配置
     */
    fun settingMainTheme(type: Int, isOk: (ok: Boolean) -> Unit) {
        LogUtils.d(TAG, "settingMainTheme type:$type")
        if (!YCBBlueConnectHelper.getBlueStatus()) {
            isOk(false)
            return
        }
        YCBTClient.settingMainTheme(type) { code, ratio, hashMap ->
            if (code == Constants.CODE.Code_OK) {
                isOk(true)
                ToastUtils.show("设置成功")
            } else {
                isOk(false)
                ToastUtils.show("设置失败")
            }
        }
    }

    /**
     * 获取主界面样式配置
     */
    fun getThemeInfo(result: (ok: Boolean, allTheme: Int, current: Int) -> Unit) {
        LogUtils.d(TAG, "getThemeInfo")
        if (!YCBBlueConnectHelper.getBlueStatus()) {
            result(false, 0, 0)
            return
        }
        YCBTClient.getThemeInfo { code, ratio, hashMap ->
            if (code == Constants.CODE.Code_OK) {
                var allTheme = hashMap["themeTotal"] as Int
                var current = hashMap["themeCurrentIndex"] as Int
                LogUtils.d(TAG, "getThemeInfo code:$code;;;allTheme:$allTheme;;;current:$current")
                result(true, allTheme, current)
            } else
                result(false, 0, 0)

        }
    }


    /**
     *  抬腕亮屏开关
     */
    fun settingRaiseScreen(type: Int, isOk: (ok: Boolean) -> Unit) {
        LogUtils.d(TAG, "settingRaiseScreen type:$type")
        if (!YCBBlueConnectHelper.getBlueStatus()) {
            isOk(false)
            return
        }
        YCBTClient.settingRaiseScreen(type) { code, ratio, hashMap ->
            if (code == Constants.CODE.Code_OK) {
                isOk(true)
                ToastUtils.show("设置成功")
            } else {
                isOk(false)
                ToastUtils.show("设置失败")
            }

        }
    }

    /**
     *  勿扰模式设置
     *
     */
    fun settingNotDisturb(
        status: Int,
        startTimeHour: Int, startTimeMin: Int,
        endTimeHour: Int, endTimeMin: Int, isOk: (ok: Boolean) -> Unit
    ) {
        LogUtils.d(TAG, "settingNotDisturb status:$status;;; startTimeHour:$startTimeHour;;; startTimeMin:$startTimeMin;;;endTimeHour:$endTimeHour;;;endTimeMin:$endTimeMin")

        if (!YCBBlueConnectHelper.getBlueStatus()) {
            isOk(false)
            return
        }
        YCBTClient.settingNotDisturb(
            status,
            startTimeHour,
            startTimeMin,
            endTimeHour,
            endTimeMin
        ) { code, ratio, hashMap ->
            if (code == Constants.CODE.Code_OK) {
                isOk(true)
                ToastUtils.show("设置成功")
            } else {
                isOk(false)
                ToastUtils.show("设置失败")
            }

        }
    }


    /**
     * 获取屏幕显示信息
     *
     * 目前没什么卵用获取不到信息
     */
    fun getScreenInfo() {
        LogUtils.d(TAG, "getScreenInfo")
        if (!YCBBlueConnectHelper.getBlueStatus()) {
            return
        }
        YCBTClient.getScreenInfo(object : BleDataResponse {
            override fun onDataResponse(code: Int, p1: Float, hashMap: HashMap<*, *>?) {
                if (code == Constants.CODE.Code_OK) {
                    val currentScreenDisplayLevel =
                        hashMap!!["currentScreenDisplayLevel"] as Int //当前屏幕显示等级
                    val currentScreenOffTime = hashMap["currentScreenOffTime"] as Int //当前屏幕息屏时间
                    val currentLanguageSettings =
                        hashMap["currentLanguageSettings"] as Int //当前语言设置
                    val CurrentWorkingMode = hashMap["CurrentWorkingMode"] as Int //当前工作模式
                    println("")
                }
            }
        })
    }

    /**
     * 删除历史数据
     * 步数 0x0540,睡眠0x0541,心率,0x0542, 血压0x0543, 血氧和温度0x0544, 血氧0x0545, 温湿度0x0546, 体温0x0547,
     */
    fun deleteHistory(type: Int) {
        LogUtils.d(TAG, "deleteHistory type:$type")
        if (type == YCBOrder.DELETE_LocalALL){
            YCBTClient.deleteHealthHistoryData(YCBOrder.STEP_HISTORY){p0, _, _ ->
                if (p0 == 0) {//delete success
                    LogUtils.d("步数 delete success")
                }
            }
            YCBTClient.deleteHealthHistoryData(YCBOrder.SLEEP_HISTORY){p0, _, _ ->
                if (p0 == 0) {//delete success
                    LogUtils.d("睡眠 delete success")
                }
            }
            YCBTClient.deleteHealthHistoryData(YCBOrder.XL_HISTORY){p0, _, _ ->
                if (p0 == 0) {//delete success
                    LogUtils.d("心率 delete success")
                }
            }
            YCBTClient.deleteHealthHistoryData(YCBOrder.XYa_HISTORY){p0, _, _ ->
                if (p0 == 0) {//delete success
                    LogUtils.d("血压 delete success")
                }
            }
            YCBTClient.deleteHealthHistoryData(YCBOrder.XY_HISTORY){p0, _, _ ->
                if (p0 == 0) {//delete success
                    LogUtils.d("血氧 delete success")
                }
            }
            YCBTClient.deleteHealthHistoryData(YCBOrder.TEMP_HISTORY){p0, _, _ ->
                if (p0 == 0) {//delete success
                    LogUtils.d("体温 delete success")
                }
            }
            YCBTClient.deleteHealthHistoryData(YCBOrder.DELETE_ALL){p0, _, _ ->
                if (p0 == 0) {//delete success
                    LogUtils.d("血氧和温度 delete success")
                }
            }
        }else{
            YCBTClient.deleteHealthHistoryData(type) { p0, p1, p2 ->
                if (p0 == 0) {//delete success
                    LogUtils.d("$type delete success")

                }
            }
        }
    }

    /**
     * 血压校准
     *
     * @param sbp 收缩压
     * @param dbp 舒张压
     */
    fun bloodCalibration(sbp: Int, dbp: Int, result: (isOk: Boolean) -> Unit) {
        YCBTClient.appBloodCalibration(
            sbp, dbp
        ) { p0, _, _ ->
            //0x00:校准成功， 0x01:校准失败-参数错误， 0x02:校准失败-设备未正在测试血压或者血压还没有出值
            if (p0 == 0) {
                result.invoke(true)
            } else {
                result.invoke(false)
            }
        }

    }

    /**
     * 删除ECG数据
     */
    fun deleteEcg() {
        LogUtils.d(TAG, "deleteEcg")
        YCBTClient.collectDeleteEcgPpg(
            0x2B0F4121
        ) { i, v, hashMap ->
            if (i == 0) {
                //success
            }
        }
    }

    /**
     * 温度监测
     * 目前为10分钟监测设置
     */
    fun openStartMeasure() {
        LogUtils.d(TAG, "openStartMeasure")
        YCBTClient.settingTemperatureMonitor(true, 10) { p0, _, _ ->
            LogUtils.d("温度监测开启状态：$p0")
        }

    }

    /**
     * 语言设置
     *
     * @param 0x00:英语 0x01: 中文 0x02: 俄语 0x03: 德语 0x04: 法语 0x05: 日语 0x06: 西班牙语 0x07: 意大利语 0x08: 葡萄牙文 0x09: 韩文 0x0A: 波兰文 0x0B: 马来文 0x0C: 繁体中文 0xFF:其它
     *
     */
    fun languageSetting(){
        LogUtils.d(TAG, "languageSetting")
        YCBTClient.settingLanguage(0x01) { p0, _, _ ->
            LogUtils.d("语言设置状态：$p0")
        }
    }

    /**
     * 获取设备信息
     */
    fun getDeviceInfo(ele: (isok: Boolean, value: String) -> Unit) {
        LogUtils.d(TAG, "getDeviceInfo")
        YCBTClient.getDeviceInfo(object : BleDataResponse {
            override fun onDataResponse(code: Int, ratio: Float, hashMap: HashMap<*, *>?) {
                LogUtils.d(TAG, "getDeviceInfo code:$code;;;ratio$ratio")
                if (hashMap != null) {
                    try {
                        //deviceBatteryState 电池状态. 0x00: normal 0x01: low battery 0x02: charging 0x03: full
                        var eleValue =
                            (hashMap["data"] as HashMap<*, *>)["deviceBatteryValue"] as Int
                        LogUtils.d(TAG, "getDeviceInfo eleValue:$eleValue")
                        ele.invoke(true, "电量$eleValue%")
                        return
                    } catch (e: Exception) {
                        LogUtils.e(TAG,"获取设备信息出错$e ")
                        ele.invoke(false, "获取设备信息出错:${e.message}")
                        return
                    }
                }else {
                    LogUtils.e(TAG,"hashMap is null")
                    ele.invoke(false, "获取设备信息出错")
                }
            }
        })
    }


    /**
     * 接收消息
     */
    fun openMsg(type: Int, title: String, content: String) {
        LogUtils.e(TAG,"openMsg type:$type;;; title:$title;;; content:$content")
        YCBTClient.appSengMessageToDevice(type, title, content) { code, ratio, resultMap ->
            if (code == 0) {
                //success sendMessage
            }
        }
    }

    /**
     * 获取历史数据
     */
    fun getHistoryList() {
        LogUtils.e(TAG,"getHistoryList")
        YCBTClient.getHistoryOutline(object : BleDataResponse {
            override fun onDataResponse(
                i: Int,
                v: Float,
                hashMap: java.util.HashMap<*, *>
            ) {
                if (i === 0) {
                    val sleepNum = hashMap["SleepNum"] as Int //睡眠条数
                    val sleepTotalTime = hashMap["SleepTotalTime"] as Int //睡眠总条数
                    val heartNum = hashMap["HeartNum"] as Int //心率条数
                    val sportNum = hashMap["SportNum"] as Int //运动条数
                    val bloodNum = hashMap["BloodNum"] as Int //血压条数
                    val bloodOxygenNum = hashMap["BloodOxygenNum"] as Int //血氧条数
                    val tempHumidNum = hashMap["TempHumidNum"] as Int //温湿度条数
                    val tempNum = hashMap["TempNum"] as Int //体温条数
                    val ambientLightNum = hashMap["AmbientLightNum"] as Int //环境光条数

                    LogUtils.d(
                        TAG, """"
                        |睡眠:$sleepNum 
                        |睡眠总条数:$sleepTotalTime 
                        |心率:$heartNum 
                        |运动:$sportNum 
                        |血压:$bloodNum 
                        |血氧:$bloodOxygenNum 
                        |温湿度:$tempHumidNum 
                        |体温:$tempNum 
                        |环境光:$ambientLightNum 
                    """.trimMargin()
                    )
                }
            }
        })

    }

}