package com.fs.watch.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.his.domain.FsHealthTongue;
import com.fs.his.utils.PhoneUtil;
import com.fs.watch.domain.*;
import com.fs.watch.domain.vo.*;
import com.fs.watch.mapper.*;
import com.fs.watch.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service("WatchDataService")
public class WatchDataServiceImpl implements WatchDataService {
    @Autowired
    private WatchBloodGlucoseDataService watchBloodGlucoseDataService;
    @Autowired
    private WatchBloodPressureDataService watchBloodPressureDataService;
    @Autowired
    private WatchHeartRateDataService watchHeartRateDataService;
    @Autowired
    private WatchRriDataService watchRriDataService;
    @Autowired
    private WatchTemperatureDataService watchTemperatureDataService;
    @Autowired
    private WatchThirdUaDataService watchThirdUaDataService;
    @Autowired
    private WatchThirdBkDataService watchThirdBkDataService;
    @Autowired
    private WatchSleepDataService watchSleepDataService;
    @Autowired
    private WatchUserService userService;
    @Autowired
    private WatchDeviceDataMapper watchDeviceDataMapper;
    @Autowired
    private WatchDeviceInfoService deviceInfoService;
    @Autowired
    private DeviceSetUpService deviceSetUpService;
    @Autowired
    private WatchDeviceSetupService watchDeviceSetupService;
    @Autowired
    private WatchMonitorDataTypeService watchMonitorDataTypeService;
    @Autowired
    private WatchContinuousSpo2DataService watchContinuousSpo2DataService;
    @Autowired
    private WatchEcgDataServiceImpl watchEcgDataServiceImpl;

    @Autowired
    private WatchUserService watchUserService;

    @Autowired
    private WatchThirdBpDataMapper watchThirdBpDataMapper;
    @Autowired
    private WatchHeartRateDataMapper watchHeartRateDataMapper;
    @Autowired
    private WatchContinuousSpo2DataMapper watchContinuousSpo2DataMapper;
    @Autowired
    private WatchSleepDataMapper watchSleepDataMapper;
    @Autowired
    private WatchBloodGlucoseDataMapper watchBloodGlucoseDataMapper;

    @Override
    public List<FsMonitorDataVo> queryIndexWatchData(List<String> types, String deviceId) {
        //返回对象
        List<FsMonitorDataVo> vos = new ArrayList<>();
        for (String typeStr : types) {
            //获取数据类型信息(由腕表平台配置)
            FsMonitorDataType fsMonitorDataType = watchMonitorDataTypeService.selectFsMonitorDataTypeById(typeStr);
            if (fsMonitorDataType == null) {
                continue;
            }
            FsMonitorDataVo vo = new FsMonitorDataVo();
            vo.setType(fsMonitorDataType);

            int type = Integer.parseInt(typeStr);
            switch (type) {
                case 1:  //血糖
                    WatchBloodGlucoseData bgData = watchBloodGlucoseDataService.getLatest(deviceId);
                    if (bgData != null) {
//                        vo.setDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,bgData.getCreateTime()));
                        vo.setDate(bgData.getCreateTime());
                        vo.setData(bgData.getBloodGlucose().toString());
                    } else {
                        vo.setData("");
                    }
                    vos.add(vo);
                    break;
                case 2:  //血压
                    WatchThirdBpData bpData = watchBloodPressureDataService.getLatest(deviceId);
                    if (bpData != null) {
//                        vo.setDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,bpData.getCreateTime()));
                        vo.setDate(bpData.getCreateTime());
                        vo.setData(bpData.getDbp() + "/" + bpData.getSbp().toString());
                    } else {
                        vo.setData("");
                    }
                    vos.add(vo);
                    break;
                case 3:  //心率
                    WatchHeartRateData hrData = watchHeartRateDataService.getLatest(deviceId);
                    if (hrData != null) {
//                        vo.setDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,hrData.getCreateTime()));
                        vo.setDate(hrData.getCreateTime());
                        vo.setData(hrData.getAvgBpm().toString());
                    } else {
                        vo.setData("");
                    }
                    vos.add(vo);
                    break;
                case 4:  //血氧
                    WatchContinuousSpo2Data continuousSpo2Data = watchContinuousSpo2DataService.getLastByDeviceId(deviceId);
                    if (continuousSpo2Data != null) {
//                        vo.setDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,continuousSpo2Data.getCreateTime()));
                        vo.setDate(continuousSpo2Data.getCreateTime());
//                        List<Integer> spo2 = ListConverterUtils.convertStringToIntegerList(
//                                continuousSpo2Data.getJsonDataSpo2());
                        List<Integer> spo2 = continuousSpo2Data.getSpo2();
//                        List<Integer> touch = ListConverterUtils.convertStringToIntegerList(
//                                continuousSpo2Data.getJsonDataTouch());
                        List<Integer> touch = continuousSpo2Data.getTouch();
                        if (spo2.size() == touch.size() && !spo2.isEmpty()) {
                            int count = 0;
                            int sum = 0;
                            for (int i = 0; i < touch.size(); i++) {
                                if (touch.get(i) != 0) {
                                    count++;
                                    sum += spo2.get(i);
                                }
                            }
                            double avg = (double) sum / count;
                            vo.setData(String.format("%.1f", avg));
                        } else {
                            vo.setData("");
                        }
                    } else {
                        vo.setData("");
                    }
                    vos.add(vo);
                    break;
                case 5:  //体温
                    WatchTemperatureData temperatureData = watchTemperatureDataService.getLatest(deviceId);
                    if (temperatureData != null) {
//                        vo.setDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,temperatureData.getCreateTime()));
                        vo.setDate(temperatureData.getCreateTime());
                        vo.setData(temperatureData.getEstTemp().toString());
                    } else {
                        vo.setData("");
                    }
                    vos.add(vo);
                    break;
                case 6:  //呼吸 todo
                    vo.setDate(DateUtils.dateTimeNow());
                    vo.setData(120 + "");
                    vos.add(vo);
                    break;
                case 7:  //血脂 todo
                    vo.setData("");
                    vos.add(vo);
                    break;
                case 8:  //尿酸
                    WatchThirdUaData uaData = watchThirdUaDataService.getLatest(deviceId);
                    if (uaData != null) {
//                        vo.setDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,uaData.getCreateTime()));
                        vo.setDate(uaData.getCreateTime());
//                        list.add(uaData.getVal().toString());
                        Integer status = uaData.getStatus();
                        vo.setData(watchThirdUaDataService.getStatusStr(status));
                    } else {
                        vo.setData("");
                    }
                    vos.add(vo);
                    break;
                case 9:  //血管硬化 todo
                    vo.setData("");
                    vos.add(vo);
                    break;
                case 10:  //血酮
                    WatchThirdBkData bkData = watchThirdBkDataService.getLatest(deviceId);
                    if (bkData != null) {
//                        vo.setDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,bkData.getCreateTime()));
                        vo.setDate(bkData.getCreateTime());
//                        list.add(bkData.getVal().toString());
                        Integer status = bkData.getStatus();
                        vo.setData(status == 0 ? "正常" : "异常");
                    } else {
                        vo.setData("");
                    }
                    vos.add(vo);
                    break;
                case 11:  //睡眠 todo 未确定返回数据
                    //查询最新日期
                    WatchSleepData data = watchSleepDataService.getLast(deviceId);
                    if (data != null) {
                        String date = data.getCreateTime().split(" ")[0];
                        WatchSleepDataVo sleepSection = watchSleepDataService.getSleepSection(date, deviceId);
                        if (sleepSection != null) {
                            vo.setDate(date);
                            Integer score = sleepSection.getScore();
                            vo.setData(score==null?"":score.toString());
                            vos.add(vo);
                            break;
                        }
                    }
                    vo.setData("");
                    vos.add(vo);
                    break;
                case 12:  //房颤 todo 未确定返回数据
                    vo.setData("");
                    vos.add(vo);
                    break;
                case 13:  //舌诊
                    FsHealthTongue tongue = watchUserService.getLastTongueByDeviceId(deviceId);
                    if (tongue != null){
                        vo.setDate(tongue.getCreateTime().toString());
                        vo.setData(tongue.getTypeName());
                    } else {
                        vo.setData("");
                    }
                    vos.add(vo);
                    break;
                default:
                    break;
            }
        }
        return vos;
    }

    @Override
    public List<AppInfoVo> getUserByDeviceId(String deviceIds, Boolean isFamily) {
        List<String> list = Arrays.asList(deviceIds.split(","));
        if (list != null && list.size() > 0) {
            //设备绑定用户名
            WatchFsUser user = userService.selectWatchFsUserByDeviceId(list.get(0));
            if (user != null) {
                //处理电话
                String phone = user.getPhone();
                if (StringUtils.isNotBlank(phone)) {
                    if (phone.length() != 11 && !phone.startsWith("1")) {
                        user.setPhone(PhoneUtil.decryptPhone(phone));
                    }
                }
            }

            if (!isFamily && user == null) {
                return null;
            }
            List<AppInfoVo> vos = new ArrayList<>();
            for (String deviceId : list) {
                AppInfoVo appInfoVo = new AppInfoVo();
                appInfoVo.setUser(user);
                //设备型号
                WatchDeviceData data = watchDeviceDataMapper.getByDeviceId(deviceId);
                if (data != null) {
                    appInfoVo.setBle(data.getBle());
                } else {
                    appInfoVo.setBle("H102C");
                }
                //获取设备状态
                Map<String, Object> statusData = deviceInfoService.getInfo(deviceId);
                if (statusData == null) {
                    appInfoVo.setStatus(3);
                } else if (statusData.get("status") != null) {
                    appInfoVo.setStatus(Integer.parseInt(statusData.get("status").toString()));
                }
                vos.add(appInfoVo);


            }
            return vos;
        } else {
            return null;
        }

    }

    @Override
    public Boolean power(String deviceId, Boolean isLcdgesture, Boolean isLocation, Boolean isPower, Boolean isHeartHealth) {
        Boolean afFlag = null;
        //1.24小时心脏健康
        if (isHeartHealth != null) {
            if (isHeartHealth) {
                afFlag = deviceSetUpService.autoaf(deviceId, isHeartHealth, 60, false);
            } else {
                afFlag = deviceSetUpService.autoaf(deviceId, isHeartHealth, 60, true);
            }
        }
        //2.自动定位 默认10分钟定位一次,耗电低
        Boolean auFlag = null;
        if (isLocation != null) {
            if (isLocation) {
                auFlag = deviceSetUpService.autolocate(deviceId, isLocation, 10, 2);
            } else {
                auFlag = deviceSetUpService.autolocate(deviceId, isLocation, 10, 3);
            }
        }


        //3.放置省电 设备数据上传间隔设置
        Boolean daFlag = null;
        if (isPower != null) {
            daFlag = deviceSetUpService.datafreq(deviceId, isPower, 10, 2);
        }
        //4.翻腕亮屏
        Boolean lcFlag = null;
        if (isLcdgesture != null) {
            lcFlag = deviceSetUpService.lcdgesture(deviceId, isLcdgesture, 0, 23);
        }

        WatchDeviceSetup deviceSetup = watchDeviceSetupService.selectDeviceSetupByDeviceId(deviceId);
        if (deviceSetup != null) {
            //原设置
            String oldPowerStr = deviceSetup.getPower();
            DevicePower oldPower = JSON.parseObject(oldPowerStr, DevicePower.class);
            DevicePower devicePower = new DevicePower();
            devicePower.setIsLcdgesture((lcFlag != null && lcFlag) ? isLcdgesture : oldPower.getIsLcdgesture());
            devicePower.setIsLocation((auFlag != null && auFlag) ? isLocation : oldPower.getIsLocation());
            devicePower.setIsPower((daFlag != null && daFlag) ? isPower : oldPower.getIsPower());
            devicePower.setIsHeartHealth((afFlag != null && afFlag) ? isHeartHealth : oldPower.getIsHeartHealth());
            deviceSetup.setPower(JSONUtil.toJsonStr(devicePower));
            //关联手表模式
            //原设置
            String mode = deviceSetup.getMode();
            DeviceMode deviceMode = JSONObject.parseObject(mode, DeviceMode.class);
            deviceMode.setIsLocation((auFlag != null && auFlag) ? isLocation : deviceMode.getIsLocation());
            deviceMode.setIsPower((daFlag != null && daFlag) ? isPower : deviceMode.getIsPower());
            deviceSetup.setMode(JSONUtil.toJsonStr(deviceMode));
            //关联翻腕亮屏
            String lcdGesture = deviceSetup.getLcdgesture();
            DeviceLcdgesture deviceLcdgesture = JSONObject.parseObject(lcdGesture, DeviceLcdgesture.class);
            deviceLcdgesture.setOpen((lcFlag != null && lcFlag) ? isLcdgesture : deviceLcdgesture.getOpen());
            //关联心脏健康
            Integer heartHealth = deviceSetup.getHeartHealth();
            deviceSetup.setHeartHealth((afFlag != null && afFlag) ? (isHeartHealth ? 1 : 0) : heartHealth);

            watchDeviceSetupService.updateDeviceSetup(deviceSetup);
        }
        return (afFlag == null || afFlag) && (auFlag == null || auFlag) && (daFlag == null || daFlag) && (lcFlag == null || lcFlag);
//        return true;
    }

    @Override
    public Boolean setDeviceTime(String deviceId, Integer itime, Integer iDate) {
        Boolean tFlag = deviceSetUpService.timeFormat(deviceId, itime);
        Boolean dFlag = deviceSetUpService.dateFormat(deviceId, iDate);
        WatchDeviceSetup deviceSetup = watchDeviceSetupService.selectDeviceSetupByDeviceId(deviceId);
        if (deviceSetup != null) {
            //原设置
            String timeStr = deviceSetup.getTime();
            DeviceTime oldTime = JSON.parseObject(timeStr, DeviceTime.class);
            DeviceTime deviceTime = new DeviceTime();
            deviceTime.setItime(tFlag ? itime : oldTime.getItime());
            deviceTime.setIDate(dFlag ? iDate : oldTime.getIDate());
            deviceSetup.setTime(JSONUtil.toJsonStr(deviceTime));
            watchDeviceSetupService.updateDeviceSetup(deviceSetup);
            return tFlag && dFlag;
        }
        return false;
    }

    @Override
    public Boolean setDeviceUnit(String deviceId, Integer measure, Integer temperature) {
        Boolean mFlag = deviceSetUpService.distanceUnit(deviceId, measure);
        Boolean tFlag = deviceSetUpService.temperatureUnit(deviceId, temperature);
        WatchDeviceSetup deviceSetup = watchDeviceSetupService.selectDeviceSetupByDeviceId(deviceId);
        if (deviceSetup != null) {
            //原设置
            String oldUnitStr = deviceSetup.getUnit();
            DeviceUnit oldUnit = JSON.parseObject(oldUnitStr, DeviceUnit.class);
            DeviceUnit deviceUnit = new DeviceUnit();
            deviceUnit.setMeasure(mFlag ? measure : oldUnit.getMeasure());
            deviceUnit.setTemperature(tFlag ? temperature : oldUnit.getTemperature());
            deviceSetup.setUnit(JSONUtil.toJsonStr(deviceUnit));
            watchDeviceSetupService.updateDeviceSetup(deviceSetup);
            return mFlag && tFlag;
        }
        return false;
    }

    /**
     * 1 - low耗电;手表放置和进入睡眠的时候会关闭4G模块，无法上传数据，无法接听呼入电话
     * 2 - mid耗电;手表放置的时候不会关闭4G模块，可以上传数据，接听呼入电话；手表进入睡眠的时候会关闭4G模块，无法上传数据，无法接听呼入电话
     * 3 - high耗电;手表放置和进入睡眠的时候，都不会关闭4G模块，数据上传和电话呼入呼出不受影响
     *
     * @param deviceId
     * @param isLocation
     * @param interval
     * @param isPower
     * @return
     */
    @Override
    public Boolean setDeviceMode(String deviceId, Boolean isLocation, Integer interval, Boolean isPower) {

        //1.自动定位 默认10分钟定位一次,耗电低
        Boolean auFlag = true;
        if (isLocation) {
            auFlag = deviceSetUpService.autolocate(deviceId, isLocation, 10, 2);
        } else {
            auFlag = deviceSetUpService.autolocate(deviceId, isLocation, 10, 3);
        }
        //2.定位数据传输间隔
        Boolean gpFlag = true;
        if (interval != null && interval > 0) {
            gpFlag = deviceSetUpService.gpsLocate(deviceId, isLocation, interval, true);
        } else {
            gpFlag = deviceSetUpService.gpsLocate(deviceId, isLocation, 10, false);
        }
        //3.放置省电 设备数据上传间隔设置
        Boolean daFlag = deviceSetUpService.datafreq(deviceId, isPower, 10, 2);

        WatchDeviceSetup deviceSetup = watchDeviceSetupService.selectDeviceSetupByDeviceId(deviceId);
        if (deviceSetup != null) {
            //原设置
            String oldModeStr = deviceSetup.getMode();
            DeviceMode oldMode = JSON.parseObject(oldModeStr, DeviceMode.class);
            DeviceMode deviceMode = new DeviceMode();
            deviceMode.setIsLocation(auFlag ? isLocation : oldMode.getIsLocation());
            deviceMode.setInterval(interval);
            deviceMode.setIsPower(daFlag ? isPower : oldMode.getIsPower());
            deviceSetup.setMode(JSONUtil.toJsonStr(deviceMode));
            //关联省电
            //原设置
            String power = deviceSetup.getPower();
            DevicePower devicePower = JSONObject.parseObject(power, DevicePower.class);
            devicePower.setIsLocation(auFlag ? isLocation : devicePower.getIsLocation());
            devicePower.setIsPower(daFlag ? isPower : devicePower.getIsPower());
            deviceSetup.setPower(JSONUtil.toJsonStr(devicePower));

            watchDeviceSetupService.updateDeviceSetup(deviceSetup);
        }
        return auFlag && gpFlag && daFlag;
    }

    @Override
    public QueryPageMonthVo queryMonthByDeviceId(String deviceId, Integer pageSize, Integer pageNum) {
        if (StringUtils.isBlank(deviceId)) {
            return null;
        }
        //从watch_device_data有数据开始
        WatchDeviceData lastByDeviceId = watchDeviceDataMapper.getByDeviceId(deviceId);
        if (lastByDeviceId == null) {
            return null;
        }

        List<String> monthList = null;
        // 获取设备创建时间
        Date createTime = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",lastByDeviceId.getCreateTime());

        // 获取当前时间
        Calendar current = Calendar.getInstance();


        // 存储月份的列表
        monthList = new ArrayList<>();

        // 初始化一个 Calendar 对象为创建时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(createTime);
        // 定义日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
        // 循环直到当前时间
        while (calendar.before(current) || calendar.equals(current)) {
            String monthStr = new SimpleDateFormat("yyyyMM").format(calendar.getTime());

            //有数据才添加
            //
            Boolean flag = isHavingData(deviceId, monthStr);
            if (flag){
                // 获取当前日期并格式化为yyyy-MM，并存入列表
                monthList.add(dateFormat.format(calendar.getTime()));
            }
            // 将日期加一个月
            calendar.add(Calendar.MONTH, 1);
        }
        QueryPageMonthVo vo = new QueryPageMonthVo();
        vo.setTotal(monthList == null ? 0 : monthList.size());
        int start = (pageNum - 1) * pageSize;
        int end = start + pageSize;
        if (end > monthList.size()) {
            end = monthList.size();
        }
        vo.setMonth(monthList == null ? null : monthList.subList(start, end));
        return vo;
    }

    private  Boolean isHavingData(String deviceId, String monthStr) {
        boolean flag = false;
        List<WatchThirdBpData> bpList = watchThirdBpDataMapper.queryByMonth(deviceId, monthStr);
        if (bpList != null && !bpList.isEmpty()) {
            flag = true;
            return flag;
        }
        //血氧
        List<WatchContinuousSpo2Data> spo2DataList = watchContinuousSpo2DataMapper.queryByMonth(deviceId, monthStr);
        if (spo2DataList != null && !spo2DataList.isEmpty()) {
            flag = true;
            return flag;
        }
        //心率
        List<WatchHeartRateData> hrList = watchHeartRateDataMapper.queryByMonth(deviceId, monthStr);
        if (hrList != null && !hrList.isEmpty()) {
            flag = true;
            return flag;
        }
        //睡眠
        List<WatchSleepData> sleepList = watchSleepDataMapper.queryByMonth(deviceId, monthStr);
        if (sleepList != null && !sleepList.isEmpty()) {
            flag = true;
            return flag;
        }
        //血糖
        List<WatchBloodGlucoseData> bgList = watchBloodGlucoseDataMapper.queryByMonth(deviceId, monthStr);
        if (bgList != null && !bgList.isEmpty()) {
            flag = true;
            return flag;
        }
        return flag;
    }

    @Override
    public List<WatchLastHealthDataVo> queryLastWatchData(String deviceId) {
        //返回对象
        List<WatchLastHealthDataVo> vos = new ArrayList<>();
        //1.血糖
        WatchLastHealthDataVo vo1 = new WatchLastHealthDataVo();
        vo1.setType("血糖");
        WatchBloodGlucoseData bgData = watchBloodGlucoseDataService.getLatest(deviceId);
        if (bgData != null) {
            vo1.setDate(bgData.getCreateTime());
            vo1.setData(bgData.getBloodGlucose().toString());
            //1:高风险 2:不良 3:一般 4:良好 5:正常
            Integer status = bgData.getStatus();
            switch (status) {
                case 1:
                    vo1.setStatus("高风险");
                    break;
                case 2:
                    vo1.setStatus("不良");
                    break;
                case 3:
                    vo1.setStatus("一般");
                    break;
                case 4:
                    vo1.setStatus("良好");
                    break;
                case 5:
                    vo1.setStatus("正常");
                    break;
            }
        } else {
            vo1.setDate("");
            vo1.setData("");
            vo1.setStatus("");
        }
        vos.add(vo1);
        //2.血压
        WatchLastHealthDataVo vo2 = new WatchLastHealthDataVo();
        vo2.setType("血压");
        WatchThirdBpData bpData = watchBloodPressureDataService.getLatest(deviceId);
        if (bpData != null) {
            vo2.setDate(bpData.getCreateTime());
            vo2.setData(bpData.getDbp() + "/" + bpData.getSbp().toString());
            Integer bpDataStatus = bpData.getStatus();
            switch (bpDataStatus) {
                case 1:
                    vo2.setStatus("重度");
                    break;
                case 2:
                    vo2.setStatus("中度");
                    break;
                case 3:
                    vo2.setStatus("轻度");
                    break;
                case 4:
                    vo2.setStatus("正常高值");
                    break;
                case 5:
                    vo2.setStatus("偏低");
                    break;
                case 6:
                    vo2.setStatus("正常");
                    break;
            }
        } else {
            vo2.setDate("");
            vo2.setData("");
            vo2.setStatus("");
        }
        vos.add(vo2);
        //3.心率
        WatchLastHealthDataVo vo3 = new WatchLastHealthDataVo();
        vo3.setType("心率");
        WatchHeartRateData hrData = watchHeartRateDataService.getLatest(deviceId);
        if (hrData != null) {
            vo3.setDate(hrData.getCreateTime());
            vo3.setData(hrData.getAvgBpm().toString());
            Integer hrStatus = hrData.getStatus();
            switch (hrStatus){
                case 0:
                    vo3.setStatus("正常");
                    break;
                case 1:
                    vo3.setStatus("偏低");
                    break;
                case 2:
                    vo3.setStatus("偏高");
                    break;
            }
        } else {
            vo3.setDate("");
            vo3.setData("");
            vo3.setStatus("");
        }
        vos.add(vo3);
        //4.血氧
        WatchLastHealthDataVo vo4 = new WatchLastHealthDataVo();
        vo4.setType("血氧");
        WatchContinuousSpo2Data continuousSpo2Data = watchContinuousSpo2DataService.getLastByDeviceId(deviceId);
        if (continuousSpo2Data != null) {
            vo4.setDate(continuousSpo2Data.getCreateTime());
            List<Integer> spo2 = continuousSpo2Data.getSpo2();
            List<Integer> touch = continuousSpo2Data.getTouch();
            if (spo2.size() == touch.size() && !spo2.isEmpty()) {
                int count = 0;
                int sum = 0;
                for (int i = 0; i < touch.size(); i++) {
                    if (touch.get(i) != 0) {
                        count++;
                        sum += spo2.get(i);
                    }
                }
                double avg = (double) sum / count;
                vo4.setData(String.format("%.1f", avg));
                if (avg>99){
                    vo4.setStatus("偏高");
                } else if (avg>=95){
                    vo4.setStatus("正常");
                } else {
                    vo4.setStatus("偏低");
                }
            } else {
                vo4.setDate("");
                vo4.setData("");
                vo4.setStatus("");
            }
        } else {
            vo4.setDate("");
            vo4.setData("");
            vo4.setStatus("");
        }
        vos.add(vo4);
         //5.体温
        WatchLastHealthDataVo vo5 = new WatchLastHealthDataVo();
        vo5.setType("体温");
        WatchTemperatureData temperatureData = watchTemperatureDataService.getLatest(deviceId);
        if (temperatureData != null) {
            vo5.setDate(temperatureData.getCreateTime());
            Double estTemp = temperatureData.getEstTemp();
            vo5.setData(estTemp.toString());
            if (estTemp>38){
                vo5.setStatus("偏高");
            } else if (estTemp>35){
                vo5.setStatus("正常");
            } else {
                vo5.setStatus("偏低");
            }
        } else {
            vo5.setDate("");
            vo5.setData("");
            vo5.setStatus("");
        }
        vos.add(vo5);
        //6.尿酸
        WatchLastHealthDataVo vo6 = new WatchLastHealthDataVo();
        vo6.setType("尿酸");
        WatchThirdUaData uaData = watchThirdUaDataService.getLatest(deviceId);
        if (uaData != null) {
            vo6.setDate(uaData.getCreateTime());
            Integer status = uaData.getStatus();
            vo6.setData(uaData.getVal().toString());
            vo6.setStatus(watchThirdUaDataService.getStatusStr(status));
        } else {
            vo6.setDate("");
            vo6.setData("");
            vo6.setStatus("");
        }
        vos.add(vo6);
        //7.血酮
        WatchLastHealthDataVo vo7 = new WatchLastHealthDataVo();
        vo7.setType("血酮");
        WatchThirdBkData bkData = watchThirdBkDataService.getLatest(deviceId);
        if (bkData != null) {
            vo7.setDate(bkData.getCreateTime());
            Integer status = bkData.getStatus();
            vo7.setData(bkData.getVal().toString());
            vo7.setStatus(status == 0 ? "正常" : "异常");
        } else {
            vo7.setDate("");
            vo7.setData("");
            vo7.setStatus("");
        }
        vos.add(vo7);
        //8.睡眠
        WatchLastHealthDataVo vo8 = new WatchLastHealthDataVo();
        vo8.setType("睡眠");
        String date = DateUtils.dateTimeNow("yyyy-MM-dd");
        WatchSleepDataVo sleepSection = watchSleepDataService.getSleepSection(date, deviceId);
        if (sleepSection != null) {
            vo8.setData("睡眠时长:" + (sleepSection.getSleepTime()==null?(0+""):(sleepSection.getSleepTime())) + "分钟");
            vo8.setDate(date);
            vo8.setStatus("得分:" + (sleepSection.getScore()==null?(0+""):(sleepSection.getScore()+"")));
        } else {
            vo8.setDate("");
            vo8.setData("");
            vo8.setStatus("");
        }
        vos.add(vo8);
        //9.房颤
        WatchLastHealthDataVo vo9 = new WatchLastHealthDataVo();
        vo9.setType("房颤");
        Map<String, Object> map = watchRriDataService.queryLastByDateAndDeviceId(deviceId);
        if (map != null){
            vo9.setData("");
            vo9.setDate(map.get("date").toString());
            vo9.setStatus(map.get("mes").toString());
        }else {
            vo9.setDate("");
            vo9.setData("");
            vo9.setStatus("");
        }
        vos.add(vo9);
        return vos;
    }

    @Override
    public List<PhoneBookObject> querySos(String deviceId) {
        DeviceSetupVo vo = watchDeviceSetupService.getSetUpInfoByDeviceId(deviceId);
        if (vo != null) {
            DevicePhonebooks phonebooks = vo.getPhonebooks();
            if (phonebooks != null) {
                List<PhoneBookObject> phoneList = phonebooks.getPhoneList();
                if (phoneList != null && !phoneList.isEmpty()) {
                    return phoneList.stream().filter(phoneBookObject -> phoneBookObject.isSos()).collect(Collectors.toList());
                }
            }
        }
        return null;
    }
}
