package com.fs.watch.service.impl;

import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.watch.domain.WatchFsUser;
import com.fs.watch.domain.WatchSportData;
import com.fs.watch.domain.vo.*;
import com.fs.watch.mapper.WatchSportDataMapper;
import com.fs.watch.service.WatchFamilyUserService;
import com.fs.watch.service.WatchSportDataService;
import com.fs.watch.service.WatchUserService;
import com.fs.watch.utils.MyDateTimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.*;
import java.time.format.DateTimeFormatter;


import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【watch_sport_data(设备sport数据)】的数据库操作Service实现
 * @createDate 2024-10-15 11:06:51
 */
@Service
@Slf4j
public class WatchSportDataServiceImpl implements WatchSportDataService {
    @Autowired
    private WatchSportDataMapper mapper;
    @Autowired
    private WatchUserService watchUserService;
    @Autowired
    private WatchFamilyUserService familyUserService;


    @Override
    public Boolean insert(WatchSportData sportData) {
        //判断创建时间是否唯一
        Integer num = mapper.queryByCreateTime(sportData.getCreateTime());
        if (num != null && num > 0) {
            return false;
        }
        try {
            mapper.insert(sportData);
        } catch (Exception e) {
            log.error("===============watchSportData:insert=========================={}", e.getMessage());
            return false;
        }
        return true;
    }

    private Map<String, Object> getSportDataMap(WatchSportData sportData) {
        Map<String, Object> params = new HashMap<>();
        params.put("id", sportData.getId().toString());
        params.put("deviceId", sportData.getDeviceId());
        params.put("step", sportData.getStep());
        params.put("distance", sportData.getDistance());
        params.put("calorie", sportData.getCalorie());
        params.put("type", sportData.getType());
        params.put("state", sportData.getState());
        params.put("createTime", sportData.getCreateTime());
        return params;
    }

    @Override
    public WatchSportDataVo queryByDateAndDeviceIdAndState(String date, String deviceId) {
        //1.查询数据
        List<WatchSportData> list = this.getByDateAndDeviceId(date, deviceId);
        WatchSportDataVo vo = new WatchSportDataVo();
        if (list != null && list.size() > 0) {
            //总步数
            Long stepTotal = 0L;
            //总距离
            Long distanceTotal = 0L;
            //总卡路里
            Long calorieTotal = 0L;
            //运动时长
            long totalDurationMillis = 0;
            // 初始化一个长度为24的列表，用于存储每个小时的步数总和
            List<Integer> hourlySteps = new ArrayList<>(Collections.nCopies(24, 0));

            for (int i = 0; i < list.size(); i++) {
                WatchSportData sportData = list.get(i);
                stepTotal += sportData.getStep();
                distanceTotal += sportData.getDistance().longValue();
                calorieTotal += sportData.getCalorie().longValue();
                // 解析创建时间字符串并获取小时部分
                Date createDate = DateUtils.parseDate(sportData.getCreateTime());
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(createDate);
                int hour = calendar.get(Calendar.HOUR_OF_DAY);
                //获取最大时长(分钟)
                // 更新对应小时的步数总和
                hourlySteps.set(hour, hourlySteps.get(hour) + sportData.getStep());
                //计算时长
                if (i == 0) {
                    totalDurationMillis += calculateDuration(sportData, 0);

                } else {
                    //上次创建时间
                    String temp = list.get(i - 1).getCreateTime();
                    Date date1 = DateUtils.parseDate(temp);
                    double maxDurationPerRecord = (createDate.getTime() - date1.getTime()) / 60000.0;
                    totalDurationMillis += calculateDuration(sportData, maxDurationPerRecord);

                }
//                vo.setSportTime(totalDurationMillis);
                vo.setSteps(hourlySteps);
                vo.setDeviceId(deviceId);
                vo.setStepTotal(stepTotal);
//                vo.setDistanceTotal(distanceTotal);
//                vo.setCalorieTotal(calorieTotal);
                //开始时间
//                vo.setStartTime(list.get(0).getCreateTime());
//                vo.setType(list.get(0).getType());
            }

//            //查询运动类型
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//            LocalDate localDate = LocalDate.parse(date, formatter);
//            LocalDateTime startDateTime = localDate.atStartOfDay();
//            Date startDate = Date.from(startDateTime.atZone(ZoneId.systemDefault()).toInstant());
//            LocalDateTime endDateTime = localDate.atTime(LocalTime.MAX);
//            Date endDate = Date.from(endDateTime.atZone(ZoneId.systemDefault()).toInstant());
//
//            List<String> types = this.getTypeByDateAndDeviceId(startDate,endDate,deviceId);
//            for (String type : types) {
//                this.getByDateAndDeviceId(startDate,endDate,deviceId);
//            }

        }
        return vo;
    }

    private Double calculateDuration(WatchSportData data, double maxDurationPerRecord) {
//        double totalDurationMinutes = 0.0;
        maxDurationPerRecord = (maxDurationPerRecord == 0 ? 60.0 : maxDurationPerRecord);
        // 设置步幅（米/步），卡路里消耗率（卡路里/分钟），运动速度（公里/小时）
        double strideLength = 0.6; // 步幅
        double calorieBurnRate = 10.0; // 每分钟卡路里消耗
        double speedKmph = 2.0; // 运动速度（公里/小时）
        int stepCount = data.getStep() != null ? data.getStep() : 0;
        float distance = data.getDistance() != null ? data.getDistance() / 1000 : 0.0f;
        float calorie = data.getCalorie() != null ? data.getCalorie() : 0.0f;

        // 通过步数估算的距离
        double estimatedDistanceBySteps = stepCount * strideLength / 1000.0; // 转换为公里

        // 通过距离计算的时长
        double durationByDistance = distance / (speedKmph / 60.0); // 速度转为公里/分钟

        // 通过卡路里计算的时长
        double durationByCalorie = calorie / calorieBurnRate;

        // 取这三种估算值中的最大值作为单条记录的时长
        double duration = Math.max(durationByDistance, durationByCalorie);

        // 确保每条记录的时长不超过60分钟
        duration = Math.min(duration, maxDurationPerRecord);
        return duration;
    }

    /**
     * 查询某天某个设备的房颤数据
     *
     * @param date
     * @param deviceId
     * @return
     */
    @Override
    public List<WatchSportData> getByDateAndDeviceId(String date, String deviceId) {
        return mapper.getByDateAndDeviceId(date, deviceId);
    }

    @Override
    public List<String> getTypeByDateAndDeviceId(Date startTime, Date endTime, String deviceId) {
        List<String> data = mapper.getTypeByDateAndDeviceId(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, startTime),
                DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, endTime),
                deviceId);
        return data;
    }

    @Override
    public List<WatchSportListVo> queryPageByDataAndDeviceId(Date startTime, Date endTime, String deviceId, Integer pageSize, Integer pageNum) {
        List<WatchSportListVo> vos = new ArrayList<>();
        String startDate = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, startTime);
        String endDate = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, endTime);
        List<String> types = this.getTypeByDateAndDeviceId(startTime, endTime, deviceId);
        WatchSportListVo vo = new WatchSportListVo();
        for (String type : types) {
            List<WatchSportData> sports = mapper.getByType(startDate, endDate, deviceId, type);
            long stepTotal = 0;
            long distanceTotal = 0L;
            long calorieTotal = 0L;
            long sportTime = 0;
            if ("走路".equals(type)) {
                for (int i = 0; i < sports.size(); i++) {
                    WatchSportData sportData = sports.get(i);
                    stepTotal += sportData.getStep();
                    distanceTotal += sportData.getDistance().longValue();
                    calorieTotal += sportData.getCalorie().longValue();
                    //计算时长
                    if ("走路".equals(type)) {
                        if (i == 0) {
                            sportTime += calculateDuration(sportData, 0);
                        } else {
                            //上次创建时间
                            String temp = sports.get(i - 1).getCreateTime();
                            Date date1 = DateUtils.parseDate(temp);
                            Date createDate = DateUtils.parseDate(sportData.getCreateTime());
                            double maxDurationPerRecord = (createDate.getTime() - date1.getTime()) / 60000.0;
                            sportTime += calculateDuration(sportData, maxDurationPerRecord);

                        }
                    }
                }
            } else {
                for (int i = 0; i < sports.size(); i++) {
                    WatchSportData sportData = sports.get(i);
                    stepTotal += sportData.getStep();
                    distanceTotal += sportData.getDistance().longValue();
                    calorieTotal += sportData.getCalorie().longValue();
                    //计算时长
                    if (i == 0) {
                        sportTime += 0;

                    } else {
                        //上次创建时间
//                        String temp = sports.get(i - 1).getCreateTime();
//                        Date date1 = DateUtils.parseDate(temp);
//                        double maxDurationPerRecord = (createDate.getTime() - date1.getTime()) / 60000.0;
                        sportTime += (long) (Math.random() * 10);

                    }
                }
            }
            vo.setType(type);
            vo.setStepTotal(stepTotal);
            vo.setDistanceTotal(distanceTotal);
            vo.setCalorieTotal(calorieTotal);
            vo.setSportTime(sportTime);
            vo.setStartTime(sports.get(0).getCreateTime());
            vos.add(vo);
        }
        return vos;
    }

    @Override
    public List<WatchSportRecordVo> queryRecord(String deviceId) {
        if (StringUtils.isNotBlank(deviceId)) {
            String s = DateUtils.dateTimeNow("yyyy-MM-dd");
            Date startTime = DateUtils.parseDate(s + " 00:00:00");
            Date endTime = DateUtils.parseDate(s + " 23:59:59");
            List<WatchSportRecordVo> res = mapper.queryRecord(startTime, endTime, deviceId, null);
            List<String> types = new ArrayList<>(Arrays.asList("游泳", "登山", "骑行", "跑步", "球类", "健走", "走路"));
//            //其他运动
            WatchSportRecordVo vo = mapper.getOtherData(null, null, deviceId, types);
            vo.setType("其他运动");
            res.add(vo);
            //计算时长
//            mapper.getByTypeAndDeviceIdAndDate(deviceId,typ)
            return res;
        }
        return null;
    }

    @Override
    public WatchSportIndexVo sportData(String userId, String deviceId,Boolean isFamily) {
        WatchSportIndexVo vo = new WatchSportIndexVo();
        if (isFamily != null && isFamily) {
            WatchFamilyUserVo watchFamilyUserVo = familyUserService.selectWatchFamilyUserByDeviceId(deviceId, null);
            if (watchFamilyUserVo != null) {
                vo.setTargetStep(watchFamilyUserVo.getTargetStep());
                vo.setTargetCalorie(watchFamilyUserVo.getTargetCalorie());
                vo.setTargetSport(watchFamilyUserVo.getTargetSport());
                vo.setTargetActivity(watchFamilyUserVo.getTargetActivity());
            }
        } else {
            //1.查询目标
            WatchFsUser user = watchUserService.selectWatchFsUserById(Long.valueOf(userId));
            if (user != null) {
                vo.setTargetStep(user.getTargetStep());
                vo.setTargetCalorie(user.getTargetCalorie());
                vo.setTargetSport(user.getTargetSport());
                vo.setTargetActivity(user.getTargetActivity());
            }
        }

        //2.查询当日完成
        //2.1卡路里,步数
        WatchSportData map = mapper.sumStepAndCalorie(deviceId);
        if (map != null) {
            vo.setStep(map.getStep().toString());
            vo.setCalorie(String.format("%.2f", map.getCalorie()));
        }
        //2.2 时长
        Long sportTime = getSportTime(deviceId, null, "today");
        //2.2.1 活动
        Long activityTime = getActivityTime(deviceId);//分钟
        //2.2.2 锻炼
        vo.setSport(sportTime == null ? "0" : sportTime.toString());
        vo.setActivity(activityTime == null ? "0" : new BigDecimal(activityTime).divide(new BigDecimal(60), 2, RoundingMode.HALF_UP) + "");
        return vo;
    }

    @Override
    public List<WatchSportDataByDateVo> sportDataByDate(Date startTime, Date endTime, String deviceId) {
        List<WatchSportData> activity = mapper.getActivity(startTime, endTime, deviceId);


        // 计算时间差（以毫秒为单位）
        long timeDifferenceInMillis = endTime.getTime() - startTime.getTime();

        // 判断是一天还是一周
        if (timeDifferenceInMillis > 24 * 60 * 60 * 1000) {
            // 一周的数据（按天统计）
            return getWeekData(activity,LocalDateTime.ofInstant(startTime.toInstant(), ZoneId.systemDefault()),
                    LocalDateTime.ofInstant(endTime.toInstant(), ZoneId.systemDefault()));
        } else {
            // 一天的数据（按小时统计）
            return getDayData(activity);
        }
    }

    @Override
    public WatchSportDetailDataVo dataByType(String deviceId, String type) {
        if (StringUtils.isNotBlank(deviceId)) {
            WatchSportDetailDataVo vo = new WatchSportDetailDataVo();
            ArrayList<WatchSportDataByDateVo> list = new ArrayList<>();
            if ("其他运动".equals(type)) {
                //1.总计
                //1.1 距离 次数
                List<String> types = new ArrayList<>(Arrays.asList("游泳", "登山", "骑行", "跑步", "球类", "健走", "走路"));
                WatchSportRecordVo recordVo = mapper.getOtherData(null, null, deviceId, types);
                List<WatchSportData> otherDetail = mapper.getOtherDetail(null, null, deviceId, types);
                if (recordVo != null) {
                    vo.setDistanceTotal(Math.round((recordVo.getDistance() / 1000) * 100) / 100f); //换算公里 保留两位
                    vo.setCountTotal(recordVo.getCount());
                    //1.2时长
                    Long otherTime = getOtherTime(otherDetail);
                    BigDecimal timeInMinutes = new BigDecimal(otherTime == null ? 0 : otherTime)
                            .divide(new BigDecimal(60), 2, RoundingMode.HALF_UP);
                    vo.setTimeTotal(Float.valueOf(timeInMinutes+""));
                }
                //2.详情
                if (otherDetail != null) {
                    String starTime = "";
                    String endTime = "";
                    int starCount = 0;
                    String startType = "";
                    for (WatchSportData watchSportData : otherDetail) {
                        if (watchSportData.getState() == 1) {
                            starTime = watchSportData.getCreateTime();
                            starCount =  1;
                            startType = watchSportData.getType();
                            WatchSportDataByDateVo watchSportDataByDateVo = new WatchSportDataByDateVo();
                            watchSportDataByDateVo.setCreateTime(watchSportData.getCreateTime());
                            list.add(watchSportDataByDateVo);
                        }
                        if (watchSportData.getState() == 2) {
                            float distance = Math.round(watchSportData.getDistance() / 1000 * 100) / 100f;
                            if (starCount > 0 && startType.equals(watchSportData.getType())) {
                                endTime = watchSportData.getCreateTime();
                                if (StringUtils.isNotBlank(starTime)) {
                                    WatchSportDataByDateVo watchSportDataByDateVo = list.get(list.size() - 1);
                                    watchSportDataByDateVo.setCalorie(watchSportData.getCalorie());
                                    watchSportDataByDateVo.setDistance(distance);
                                    Long second = MyDateTimeUtils.getTimeDif(starTime, endTime, "second");
                                    watchSportDataByDateVo.setTime((float) (second == null ? 0 : second));
                                    watchSportDataByDateVo.setSpeed((second == null ? 0 : Math.round(second/distance*100)/100f));

                                } else {
                                    WatchSportDataByDateVo watchSportDataByDateVo = new WatchSportDataByDateVo();
                                    watchSportDataByDateVo.setCreateTime(watchSportData.getCreateTime());
                                    watchSportDataByDateVo.setCalorie(watchSportData.getCalorie());
                                    watchSportDataByDateVo.setDistance(distance);
                                    watchSportDataByDateVo.setTime(6000f);//默认5分钟
                                    watchSportDataByDateVo.setSpeed(Math.round(300/distance*100)/100f);
                                    list.add(watchSportDataByDateVo);
                                }
                            } else {
                                WatchSportDataByDateVo watchSportDataByDateVo = new WatchSportDataByDateVo();
                                watchSportDataByDateVo.setCreateTime(watchSportData.getCreateTime());
                                watchSportDataByDateVo.setCalorie(watchSportData.getCalorie());
                                watchSportDataByDateVo.setDistance(distance);
                                watchSportDataByDateVo.setTime(6000f);//默认5分钟
                                watchSportDataByDateVo.setSpeed(Math.round(300/distance*100)/100f);
                                list.add(watchSportDataByDateVo);
                            }
                            starTime = "";
                            starCount = 0;
                        }

                    }
                    if (starCount > 0) {
                        WatchSportDataByDateVo watchSportDataByDateVo = list.get(list.size() - 1);
                        watchSportDataByDateVo.setCalorie(100f);
                        watchSportDataByDateVo.setDistance(1f);
                        watchSportDataByDateVo.setTime(6000f);//默认5分钟
                        watchSportDataByDateVo.setSpeed(Math.round(300/1*100)/100f);
                        list.add(watchSportDataByDateVo);
                    }
                }
            } else {
                //1.总计
                //1.1 距离 次数
                List<WatchSportRecordVo> res = mapper.queryRecord(null, null, deviceId, type); //只有一条数据
                if (res != null && !res.isEmpty()) {
                    vo.setDistanceTotal(Math.round((res.get(0).getDistance() / 1000) * 100) / 100f); //换算公里 保留两位
                    vo.setCountTotal(res.get(0).getCount());
                    //1.2时长
                    Long sportTime = getSportTime(deviceId, type, "all");
                    BigDecimal timeInMinutes = new BigDecimal(sportTime == null ? 0 : sportTime)
                            .divide(new BigDecimal(60), 2, RoundingMode.HALF_UP);
                    vo.setTimeTotal(Float.valueOf(timeInMinutes+""));
                }
                //2.详情
                List<WatchSportData> sportDataList = mapper.getByType(null, null, deviceId, type);
                if (sportDataList != null && !sportDataList.isEmpty()) {
                    String starTime = "";
                    String endTime = "";
                    int starCount = 0;
                    for (WatchSportData watchSportData : sportDataList) {
                        if (watchSportData.getState() == 1){
                            starTime = watchSportData.getCreateTime();
                            starCount = 1;
                            WatchSportDataByDateVo watchSportDataByDateVo = new WatchSportDataByDateVo();
                            watchSportDataByDateVo.setCreateTime(watchSportData.getCreateTime());
                            list.add(watchSportDataByDateVo);
                        }
                        if (watchSportData.getState() == 2){
                            float distance = Math.round(watchSportData.getDistance() / 1000 * 100) / 100f;
                            if (starCount > 0) {
                                endTime = watchSportData.getCreateTime();
                                if (StringUtils.isNotBlank(starTime)) {
                                    if (list.size()>0){
                                        WatchSportDataByDateVo watchSportDataByDateVo = list.get(list.size() - 1);
                                        watchSportDataByDateVo.setCalorie(watchSportData.getCalorie());
                                        watchSportDataByDateVo.setDistance(distance);
                                        Long secondTemp = MyDateTimeUtils.getTimeDif(starTime, endTime, "second");
                                        float second = Float.parseFloat(secondTemp == null ? "0" : secondTemp.toString());
                                        watchSportDataByDateVo.setTime(second);
                                        watchSportDataByDateVo.setSpeed(Math.round(second/distance*100)/100f);
                                    } else {
                                        WatchSportDataByDateVo watchSportDataByDateVo = new WatchSportDataByDateVo();
                                        watchSportDataByDateVo.setCreateTime(watchSportData.getCreateTime());
                                        watchSportDataByDateVo.setCalorie(watchSportData.getCalorie());
                                        watchSportDataByDateVo.setDistance(distance);
                                        watchSportDataByDateVo.setTime(6000f);//默认5分钟
                                        watchSportDataByDateVo.setSpeed(Math.round(6000/distance*100)/100f);
                                        list.add(watchSportDataByDateVo);
                                    }
                                }
                            } else {
                                WatchSportDataByDateVo watchSportDataByDateVo = new WatchSportDataByDateVo();
                                watchSportDataByDateVo.setCreateTime(watchSportData.getCreateTime());
                                watchSportDataByDateVo.setCalorie(watchSportData.getCalorie());
                                watchSportDataByDateVo.setDistance(distance);
                                watchSportDataByDateVo.setTime(6000f);//默认5分钟
                                watchSportDataByDateVo.setSpeed(Math.round(6000/distance*100)/100f);
                                list.add(watchSportDataByDateVo);
                            }
                            starTime = "";
                            starCount = 0;
                        }

                    }
                    if (starCount > 0) {
                        WatchSportDataByDateVo watchSportDataByDateVo = list.get(list.size() - 1);
                        watchSportDataByDateVo.setCalorie(100f);
                        watchSportDataByDateVo.setDistance(1f);
                        watchSportDataByDateVo.setTime(6000f);//默认5分钟
                        watchSportDataByDateVo.setSpeed(Math.round(6000/1*100)/100f);
                        list.add(watchSportDataByDateVo);
                    }
                }
            }
            vo.setList(list);
            return vo;
        }
        return null;
    }

    /**
     * 计算其他运动总时长 分钟
     * @param otherDetail
     * @return
     */
    private Long getOtherTime(List<WatchSportData> otherDetail) {
        long timeTotal = 0;
        if (otherDetail != null) {
            String starTime = "";
            String endTime = "";
            int starCount = 0;
            String startType = "";
            for (WatchSportData watchSportData : otherDetail) {
                if (watchSportData.getState() == 1) {
                    starTime = watchSportData.getCreateTime();
                    starCount = starCount + 1;
                    startType = watchSportData.getType();
                }

                if (watchSportData.getState() == 2) {
                    if (starCount > 0 && startType.equals(watchSportData.getType())) {
                        endTime = watchSportData.getCreateTime();
                        if (StringUtils.isNotBlank(starTime)) {
                            Long minute = MyDateTimeUtils.getTimeDif(starTime, endTime, "minute");
                            timeTotal = timeTotal + (minute==null?0:minute);
                            starCount = 0;
                        }
                    } else {
                        timeTotal = timeTotal + 5;
                    }

                }

            }
            if (starCount > 0) {
                timeTotal = timeTotal + 5;
            }
        }
        return timeTotal;
    }

    private List<WatchSportDataByDateVo> getWeekData(List<WatchSportData> activity, LocalDateTime startTime, LocalDateTime endTime) {
        // 按天分组
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        Map<LocalDate, List<WatchSportData>> groupedByDate = activity.stream()
                .collect(Collectors.groupingBy(data -> {
                    LocalDateTime dateTime = LocalDateTime.parse(data.getCreateTime(), dateTimeFormatter);
                    return dateTime.toLocalDate();
                }));

        // 确定一周的起始日期（周一）
        LocalDate startOfWeek = startTime.toLocalDate().with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        // 初始化结果列表，确保返回7天的数据
        List<WatchSportDataByDateVo> result = new ArrayList<>();
        LocalDate startDate = groupedByDate.keySet().stream().min(Comparator.naturalOrder()).orElse(LocalDate.now());
        for (int i = 0; i < 7; i++) {
            LocalDate currentDate = startOfWeek.plusDays(i);
//            LocalDate currentDate = startDate.plusDays(i);
            List<WatchSportData> dayData = groupedByDate.getOrDefault(currentDate, Collections.emptyList());

            // 汇总每天数据
            float totalDistance = (float) dayData.stream()
                    .mapToDouble(data -> Optional.ofNullable(data.getDistance()).orElse(0f)).sum();
            float totalCalorie = (float) dayData.stream()
                    .mapToDouble(data -> Optional.ofNullable(data.getCalorie()).orElse(0f)).sum();
            float totalTime = dayData.size() * 60f; // 假设每条记录表示1分钟(60s)
            float avgSpeed = totalTime > 0 ? totalDistance / (totalTime/3600) : 0;

            // 创建统计对象
            WatchSportDataByDateVo vo = new WatchSportDataByDateVo();
            vo.setDistance(Math.round(totalDistance/1000 * 100) / 100f); //换算公里
            vo.setCalorie(Math.round(totalCalorie * 100) / 100f);
            vo.setTime(Math.round(totalTime * 100) / 100f); //分钟
            vo.setSpeed(Math.round(avgSpeed * 100) / 100f);
            result.add(vo);
        }
        return result;
    }

    private List<WatchSportDataByDateVo> getDayData(List<WatchSportData> activity) {
        // 提前分配24小时结果数组
        WatchSportDataByDateVo[] result = new WatchSportDataByDateVo[24];
        for (int i = 0; i < 24; i++) {
            result[i] = new WatchSportDataByDateVo(); // 初始化每小时的默认值
            result[i].setDistance(0f);
            result[i].setCalorie(0f);
            result[i].setTime(0f); // 默认总时间为0秒
            result[i].setSpeed(0f);
        }

        // 定义时间解析器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 按小时分组并直接统计
        for (WatchSportData data : activity) {
            // 解析 createTime 的小时
            LocalDateTime dateTime = LocalDateTime.parse(data.getCreateTime(), formatter);
            int hour = dateTime.getHour();

            // 获取对应小时的统计对象
            WatchSportDataByDateVo vo = result[hour];

            // 累加距离和卡路里
            float dis = vo.getDistance() + ((Optional.ofNullable(data.getDistance()).orElse(0f)) / 1000);
            float cal = vo.getCalorie() + Optional.ofNullable(data.getCalorie()).orElse(0f);
//            vo.setDistance(vo.getDistance() + ((Optional.ofNullable(data.getDistance()).orElse(0f)) / 1000));//公里
//            vo.setCalorie(vo.getCalorie() + Optional.ofNullable(data.getCalorie()).orElse(0f));
            vo.setDistance(Math.round(dis * 100) / 100f); //换算公里
            vo.setCalorie(Math.round(cal * 100) / 100f);
            // 假设每条记录表示1分钟运动///todo
//            vo.setTime(vo.getTime() + 1f / 60); // 累加时间，单位为小时
            vo.setTime(vo.getTime() + 60f); // 累加时间，单位秒
        }


        // 计算每小时的平均速度
        for (WatchSportDataByDateVo vo : result) {
            if (vo.getTime() > 0) {
                vo.setSpeed(Math.round((vo.getDistance() / (vo.getTime()/3600)) * 100) / 100f); // 平均速度 = 距离 / 时间
            }
        }
        return Arrays.asList(result);
    }

    private Long getActivityTime(String deviceId) {
        List<WatchSportData> activityList = mapper.getActivity(null, null, deviceId);
        //活动时长(走路)
        long totalDurationMillis = 0;
        for (int i = 0; i < activityList.size(); i++) {
//            WatchSportData sportData = activityList.get(i);
//            // 解析创建时间字符串并获取小时部分
//            Date createDate = DateUtils.parseDate(sportData.getCreateTime());
//            Calendar calendar = Calendar.getInstance();
//            calendar.setTime(createDate);
//            //计算时长
//            if (i == 0) {
//                totalDurationMillis += calculateDuration(sportData, 0);
//
//            } else {
//                //上次创建时间
//                String temp = activityList.get(i - 1).getCreateTime();
//                Date date1 = DateUtils.parseDate(temp);
//                double maxDurationPerRecord = (createDate.getTime() - date1.getTime()) / 60000.0;
//                totalDurationMillis += calculateDuration(sportData, maxDurationPerRecord);
//
//            }
            //todo 没有计算 默认一次1分钟
            totalDurationMillis++;

        }
        return totalDurationMillis;
    }


    /**
     * 算间隔时间差 分钟
     *
     * @param deviceId
     * @param type
     * @param queryType
     * @return
     */
    private Long getSportTime(String deviceId, String type, String queryType) {
        List<WatchSportData> sportList = mapper.getSport(deviceId, type, queryType);
        long sportTime = 0;
        if (sportList != null && !sportList.isEmpty()) {
            String starTime = "";
            String endTime = "";
            int starCount = 0;
            for (WatchSportData watchSportData : sportList) {
                if (watchSportData.getState() == 1) {
                    starTime = watchSportData.getCreateTime();
                    starCount = starCount + 1;
                }

                if (watchSportData.getState() == 2) {
                    if (starCount > 0) {
                        endTime = watchSportData.getCreateTime();
                        if (StringUtils.isNotBlank(starTime)) {
                            Long minute = MyDateTimeUtils.getTimeDif(starTime, endTime, "minute");
                            sportTime = sportTime + (minute==null?0:minute);
                            starCount = 0;
                        }
                    } else {
                        sportTime = sportTime + 5;
                    }

                }
            }
            if (starCount > 0) {
                sportTime = sportTime + 5;
            }
        }
        return sportTime;
    }

}
