package com.fs.app.controller;


import com.alibaba.fastjson.JSONObject;
import com.fs.app.annotation.Login;
import com.fs.app.param.DeviceModeParam;
import com.fs.app.param.DevicePowerParam;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.watch.domain.*;
import com.fs.watch.domain.vo.*;
import com.fs.watch.param.WatchDataQueryParam;
import com.fs.watch.service.*;
import com.fs.watch.utils.GeocodingUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Api("腕表接口")
@RestController
@RequestMapping(value = "/app/watch")
public class WatchController extends AppBaseController {

    @Autowired
    private WatchHeartRateDataService watchHeartRateDataService;

    @Autowired
    private WatchSleepDataService watchSleepDataService;

    @Autowired
    private WatchBloodPressureDataService watchBloodPressureDataService;

    @Autowired
    private WatchBloodGlucoseDataService watchBloodGlucoseDataService;

    @Autowired
    private WatchSpo2DataService watchSpo2DataService;

    @Autowired
    private WatchAlarmDataService watchAlarmDataService;

    @Autowired
    private WatchDataService watchDataService;

    @Autowired
    private WatchDeviceInfoService deviceInfoService;


    @Autowired
    private WatchMonitorDataTypeService fsMonitorDataTypeService;

    @Autowired
    private WatchDeviceDataService watchDeviceDataService;

    @Autowired
    private DeviceSetUpService deviceSetUpService;

    @Autowired
    private WatchBeginnerGuideService watchBeginnerGuideService;

    @Autowired
    private WatchDeviceSetupService watchDeviceSetupService;

    @Autowired
    private WatchUserService watchUserService;

    @Autowired
    private WatchThirdBpDataService watchThirdBpDataService;

    @Autowired
    private WatchThirdUaDataService watchThirdUaDataService;

    @Autowired
    private WatchBasicInfoService watchBasicInfoService;

    @Autowired
    private WatchTemperatureDataService watchTemperatureDataService;

    @Autowired
    private WatchSportDataService watchSportDataService;
    @Autowired
    private WatchFatigueDataService watchFatigueDataService;

    /**
     * 活动详情统计
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     */
    @Login
    @GetMapping("/sport/dataByDate")
    public R sportDataByDate(
            @RequestParam(value = "startTime") Date startTime,
            @RequestParam(value = "endTime") Date endTime,
            @RequestParam(value = "deviceId") String deviceId) {
        List<WatchSportDataByDateVo> data = watchSportDataService.sportDataByDate(startTime, endTime, deviceId);
        Float distanceTotal = 0f;
        Float calorieTotal = 0f;
        Float timeTotal = 0f;
        for (WatchSportDataByDateVo vo : data) {
            distanceTotal = vo.getDistance() + distanceTotal;
            calorieTotal = vo.getCalorie() + calorieTotal;
            timeTotal = vo.getTime() + timeTotal;
        }
        Float speedTotal = Math.round((distanceTotal / (timeTotal/60/60)) * 100) / 100f;
        return R.ok().put("data",data)
                .put("distanceTotal",distanceTotal)
                .put("calorieTotal",calorieTotal)
                .put("timeTotal",timeTotal)
                .put("speedTotal",speedTotal);
    }


    /**
     * 运动列表 分页
     * @param deviceId
     * @return
     */
    @Login
    @GetMapping("/sport/dataByType")
    public AjaxResult dataByType(@RequestParam(value = "deviceId") String deviceId,
                                 @RequestParam(value = "type")String type,
                                 @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                 @RequestParam(value = "pageSize", required = false) Integer pageSize
    ) {
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;  // 默认页面大小
        }
        WatchSportDetailDataVo vo = watchSportDataService.dataByType(deviceId, type);
        if (vo != null) {
            List<WatchSportDataByDateVo> list = vo.getList();
            if (list!=null && !list.isEmpty()) {
                vo.setTotal(list.size());
                int i = (pageNum - 1) * pageSize + pageSize + 1;
                vo.setList(list.subList((pageNum-1)*pageSize,i>(list.size())?list.size():i));
            } else {
                vo.setTotal(0);
            }

        }
        return AjaxResult.success(vo);
    }

    /**
     * 首页运动/目标 (当天)
     * @param deviceId
     * @return
     */
    @Login
    @GetMapping("/sport/data")
    public AjaxResult sportData(@RequestParam(value = "deviceId") String deviceId,@RequestParam(value = "isFamily",required = false) Boolean isFamily) {
        String userId = getUserId();
        return AjaxResult.success(watchSportDataService.sportData(userId,deviceId,isFamily));
    }

    /**
     * 查询当天运动
     * @param deviceId
     * @return
     */
    @Login
    @GetMapping("/sport/queryRecord")
    public AjaxResult queryRecord(@RequestParam(value = "deviceId") String deviceId) {
        return AjaxResult.success(watchSportDataService.queryRecord(deviceId));
    }


    /**
     * 查询某个时间段尿酸数据 分页
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param deviceId  设备编号
     * @return 查询某个时间段数据
     */
    @Login
    @GetMapping("/ua/page")
    public TableDataInfo queryUaPageByDate(@RequestParam(value = "startTime") Date startTime,
                                           @RequestParam(value = "endTime") Date endTime,
                                           @RequestParam(value = "deviceId") String deviceId,
                                           @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                           @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                           @RequestParam(value = "status", required = false) Integer status
    ) {
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;  // 默认页面大小
        }

        // 获取总记录数
        int total = this.watchThirdUaDataService.countTotalDate(startTime, endTime, deviceId,status);

        // 获取分页数据
        List<WatchThirdUaData> list = this.watchThirdUaDataService.queryListByDate
                (startTime, endTime, deviceId, ((pageNum - 1) * pageSize), pageSize,status
                );

        // 返回包含数据的TableDataInfo对象
        return new TableDataInfo(list, total);
    }


    /**
     * 查询某个时间段尿酸异常数据统计
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param deviceId  设备编号
     * @return 查询某个时间段数据
     */
    @Login
    @GetMapping("/ua/count")
    public AjaxResult countUaByDate(@RequestParam(value = "startTime") Date startTime,
                                    @RequestParam(value = "endTime") Date endTime,
                                    @RequestParam(value = "deviceId") String deviceId) {
        return AjaxResult.success(this.watchThirdUaDataService.countUaByDate(startTime, endTime, deviceId));
    }


    /**
     * 查询某个时间段尿酸数据
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param deviceId  设备编号
     * @return 查询某个时间段数据
     */
    @GetMapping("/ua/list")
    public AjaxResult queryUaByDate(@RequestParam(value = "startTime") Date startTime,
                                    @RequestParam(value = "endTime") Date endTime,
                                    @RequestParam(value = "deviceId") String deviceId) {
        return AjaxResult.success(this.watchThirdUaDataService.list(startTime, endTime, deviceId));
    }

    /**
     * 查询某个时间段温度数据
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param deviceId  设备编号
     * @return 查询某个时间段数据
     */
    @GetMapping("/temperature/list")
    public AjaxResult queryTemperatureByDate(@RequestParam(value = "startTime") Date startTime,
                                             @RequestParam(value = "endTime") Date endTime,
                                             @RequestParam(value = "deviceId") String deviceId) {
        WatchTemperatureDataVo vo = new WatchTemperatureDataVo();
        List<WatchTemperatureData> list = this.watchTemperatureDataService.list(startTime, endTime, deviceId);
        if (list != null && !list.isEmpty()) {
            //最高温度
            vo.setMax(list.stream().max(Comparator.comparingDouble(WatchTemperatureData::getEstTemp)).get().getEstTemp());
            //最低温度
            vo.setMin(list.stream().min(Comparator.comparingDouble(WatchTemperatureData::getEstTemp)).get().getEstTemp());
            //最新温度
            vo.setLast(list.get(list.size() - 1).getEstTemp());
            vo.setList(list);
        }

        return AjaxResult.success(vo);
    }


    /**
     * 查询某个时间段心率数据
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param deviceId  设备编号
     * @return 查询某个时间段数据
     */
//    @Login
    @GetMapping("/heart/rate/list")
    public AjaxResult queryHeartByDate(@RequestParam(value = "startTime") Date startTime,
                                       @RequestParam(value = "endTime") Date endTime,
                                       @RequestParam(value = "deviceId") String deviceId) {
        return AjaxResult.success(this.watchHeartRateDataService.list(startTime, endTime, deviceId));
    }

    /**
     * 查询某个时间段血心率异常数据统计
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param deviceId  设备编号
     * @return 查询某个时间段数据
     */
    @Login
    @GetMapping("/heart/rate/count")
    public AjaxResult countHeartByDate(@RequestParam(value = "startTime") Date startTime,
                                       @RequestParam(value = "endTime") Date endTime,
                                       @RequestParam(value = "deviceId") String deviceId) {
        return AjaxResult.success(this.watchHeartRateDataService.countHeartByDate(startTime, endTime, deviceId));
    }

    /**
     * 查询某个时间段心率数据 分页
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param deviceId  设备编号
     * @return 查询某个时间段数据
     */
    @Login
    @GetMapping("/heart/rate/page")
    public TableDataInfo queryHeartPageByDate(@RequestParam(value = "startTime") Date startTime,
                                              @RequestParam(value = "endTime") Date endTime,
                                              @RequestParam(value = "deviceId") String deviceId,
                                              @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                              @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;  // 默认页面大小
        }

        // 获取总记录数
        int total = this.watchHeartRateDataService.countHeartRateByDate(startTime, endTime, deviceId);

        // 获取分页数据
        List<WatchHeartRateData> list = this.watchHeartRateDataService.queryHeartPageByDate
                (startTime, endTime, deviceId, ((pageNum - 1) * pageSize), pageSize
                );

        // 返回包含数据的TableDataInfo对象
        return new TableDataInfo(list, total);
    }


    /**
     * 查询某个时间段睡眠数据
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param deviceId  设备编号
     * @return 查询某个时间段数据
     */
//    @Login
    @GetMapping("/sleep/list")
    public AjaxResult querySleepByDate(@RequestParam(value = "startTime") Date startTime,
                                       @RequestParam(value = "endTime") Date endTime,
                                       @RequestParam(value = "deviceId") String deviceId) {
        return AjaxResult.success(this.watchSleepDataService.list(startTime, endTime, deviceId));
    }

    /**
     * 查询某个时间段血压数据
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param deviceId  设备编号
     * @param deviceId  状态
     * @return 查询某个时间段数据
     */
//    @Login
    @GetMapping("/bp/list")
    public AjaxResult queryBpByDate(@RequestParam(value = "startTime") Date startTime,
                                    @RequestParam(value = "endTime") Date endTime,
                                    @RequestParam(value = "deviceId") String deviceId,
                                    @RequestParam(value = "status", required = false) Integer status) {
        return AjaxResult.success(this.watchThirdBpDataService.queryBpByDate(
                DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, startTime),
                DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, endTime),
                deviceId,
                status));
    }

    /**
     * 查询某个时间段血压异常数据统计
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param deviceId  设备编号
     * @return 查询某个时间段数据
     */
    @Login
    @GetMapping("/bp/count")
    public AjaxResult countBpByDate(@RequestParam(value = "startTime") Date startTime,
                                    @RequestParam(value = "endTime") Date endTime,
                                    @RequestParam(value = "deviceId") String deviceId) {
        return AjaxResult.success(this.watchThirdBpDataService.countBpByDate(startTime, endTime, deviceId));
    }


    /**
     * 查询某个时间段血压数据 分页
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param deviceId  设备编号
     * @return 查询某个时间段数据
     */
    @Login
    @GetMapping("/bp/page")
    public TableDataInfo queryBpPageByDate(@RequestParam(value = "startTime") Date startTime,
                                           @RequestParam(value = "endTime") Date endTime,
                                           @RequestParam(value = "deviceId") String deviceId,
                                           @RequestParam(value = "status", required = false) Integer status,
                                           @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                           @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;  // 默认页面大小
        }

        // 获取总记录数
//        int total = this.watchBloodPressureDataService.countBpPageByDate(startTime, endTime, deviceId, status);
        int total = this.watchThirdBpDataService.countBpPageByDate(startTime, endTime, deviceId, status);

        // 获取分页数据
//        List<WatchBloodPressureData> list = this.watchBloodPressureDataService.queryBgPageByDate(startTime, endTime, deviceId, status, ((pageNum - 1) * pageSize), pageSize);
        List<WatchThirdBpData> list = this.watchThirdBpDataService.queryBgPageByDate(startTime, endTime, deviceId, status, ((pageNum - 1) * pageSize), pageSize);

        // 返回包含数据的TableDataInfo对象
        return new TableDataInfo(list, total);
    }

    /**
     * 查询某个时间段血糖数据
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param deviceId  设备编号
     * @return 查询某个时间段数据
     */
//    @Login
    @GetMapping("/bg/list")
    public AjaxResult queryBgByDate(@RequestParam(value = "startTime") Date startTime,
                                    @RequestParam(value = "endTime") Date endTime,
                                    @RequestParam(value = "deviceId") String deviceId,
                                    @RequestParam(value = "status", required = false) Integer status) {
        return AjaxResult.success(this.watchBloodGlucoseDataService.queryBgByDate(startTime, endTime, deviceId, status));
    }


    /**
     * 查询某个时间段血糖数据 分页
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param deviceId  设备编号
     * @return 查询某个时间段数据
     */
    @Login
    @GetMapping("/bg/page")
    public TableDataInfo queryBgPageByDate(@RequestParam(value = "startTime") Date startTime,
                                           @RequestParam(value = "endTime") Date endTime,
                                           @RequestParam(value = "deviceId") String deviceId,
                                           @RequestParam(value = "status", required = false) Integer status,
                                           @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                           @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;  // 默认页面大小
        }

        // 获取总记录数
        int total = this.watchBloodGlucoseDataService.countBgPageByDate(startTime, endTime, deviceId, status);

        // 获取分页数据
        List<WatchBloodGlucoseData> list = this.watchBloodGlucoseDataService.queryBgPageByDate
                (startTime, endTime, deviceId, status, ((pageNum - 1) * pageSize), pageSize
                );

        // 返回包含数据的TableDataInfo对象
        return new TableDataInfo(list, total);
    }

    /**
     * 查询某个时间段血糖异常数据统计
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param deviceId  设备编号
     * @return 查询某个时间段数据
     */

    @Login
    @GetMapping("/bg/count")
    public AjaxResult countBgByDate(@RequestParam(value = "startTime") Date startTime,
                                    @RequestParam(value = "endTime") Date endTime,
                                    @RequestParam(value = "deviceId") String deviceId) {
        return AjaxResult.success(this.watchBloodGlucoseDataService.countBgByDate(startTime, endTime, deviceId));
    }

    /**
     * 查询某个时间段血氧数据
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param deviceId  设备编号
     * @return 查询某个时间段数据
     */
//    @Login
    @GetMapping("/sp/list")
    public AjaxResult querySpByDate(@RequestParam(value = "startTime") Date startTime,
                                    @RequestParam(value = "endTime") Date endTime,
                                    @RequestParam(value = "deviceId") String deviceId) {
        return AjaxResult.success(this.watchSpo2DataService.querySpByDate(startTime, endTime, deviceId));
    }

    /**
     * 查询某个时间段血氧数据 分页
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param deviceId  设备编号
     * @return 查询某个时间段数据
     */
    @Login
    @GetMapping("/sp/page")
    public TableDataInfo querySpPageByDate(@RequestParam(value = "startTime") Date startTime,
                                           @RequestParam(value = "endTime") Date endTime,
                                           @RequestParam(value = "deviceId") String deviceId,
                                           @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                           @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;  // 默认页面大小
        }

        // 获取总记录数
        int total = this.watchSpo2DataService.countSpPageByDate(startTime, endTime, deviceId);

        // 获取分页数据
        List<WatchSpo2DataVo> list = this.watchSpo2DataService.querySpPageByDate
                (startTime, endTime, deviceId, ((pageNum - 1) * pageSize), pageSize
                );

        // 返回包含数据的TableDataInfo对象
        return new TableDataInfo(list, total);
    }

    /**
     * 查询某个时间段血氧异常数据统计
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param deviceId  设备编号
     * @return 查询某个时间段数据
     */
    @Login
    @GetMapping("/sp/count")
    public AjaxResult countSpByDate(@RequestParam(value = "startTime") Date startTime,
                                    @RequestParam(value = "endTime") Date endTime,
                                    @RequestParam(value = "deviceId") String deviceId) {
        return AjaxResult.success(this.watchSpo2DataService.countSpByDate(startTime, endTime, deviceId));
    }

    /**
     * 预警通知 查询所有/未读0/已读1数据
     *
     * @param appStatus 状态
     * @return 所有/未读/已读数据
     */
    @Login
    @GetMapping("/queryAlarmByStatus")
    public AjaxResult queryAlarmByStatus(@RequestParam(value = "appStatus", required = false) Integer appStatus,
                                         @RequestParam(value = "deviceId", required = false) String deviceId) {
        if (StringUtils.isNotBlank(deviceId)) {
            return AjaxResult.success(this.watchAlarmDataService.queryByAppStatusAndDeviceid(appStatus, deviceId));
        }
        //查询当前登录用户腕表信息
        String userId = getUserId();
        WatchFsUser user = watchUserService.selectWatchFsUserById(Long.valueOf(userId));
        if (user == null) {
            return AjaxResult.error("当前用户没有绑定设备");
        }
        String deviceIdsStr = user.getDeviceId();
        if (StringUtils.isBlank(deviceIdsStr)) {
            return AjaxResult.error("当前用户没有绑定设备");
        }

        return AjaxResult.success(this.watchAlarmDataService.queryByAppStatusAndDeviceid(appStatus, deviceIdsStr));
    }

    /**
     * 预警通知 查询所有/未读0/已读1数据 分页
     *
     * @param data 状态
     * @return 所有/未读/已读数据
     */
    @Login
    @GetMapping("/queryAlarmPageByStatus")
    public AppTableDataInfoVo queryPageByStatus(WatchAlarmData data) {
        startPage();
        if (StringUtils.isBlank(data.getDeviceId())) {
            //查询当前登录用户
            String userId = getUserId();
            WatchFsUser user = watchUserService.selectWatchFsUserById(Long.valueOf(userId));
            if (user == null) {
                return null;
            }
            String deviceIdsStr = user.getDeviceId();
            if (StringUtils.isBlank(deviceIdsStr)) {
                return null;
            }


            if (StringUtils.isBlank(deviceIdsStr)) {
                return null;
            }
            data.setDeviceId(deviceIdsStr);
        }
        AppWatchAlarmDataVo vo = this.watchAlarmDataService.queryPageByAppStatus(data);
        TableDataInfo dataTable = getDataTable(vo.getData());
        AppTableDataInfoVo appTableDataInfoVo = new AppTableDataInfoVo();
        appTableDataInfoVo.setTotal(dataTable.getTotal());
        appTableDataInfoVo.setRows(dataTable.getRows());
        appTableDataInfoVo.setCode(dataTable.getCode());
        appTableDataInfoVo.setMsg(dataTable.getMsg());
        appTableDataInfoVo.setUnreadNum(vo.getUnreadNum());
        return appTableDataInfoVo;
    }

    /**
     * 根据经纬度获取地址
     */
    @GetMapping("/getAddressByLocation")
    public AjaxResult query(@RequestParam("location") String location) {
        String address = "";
        if (StringUtils.isNotBlank(location)) {
            List<String> loc = Arrays.asList(location.split(","));

            double latitude = Double.valueOf(loc.get(0));  // 北京的纬度
            double longitude = Double.valueOf(loc.get(1));  // 北京的经度
            if (latitude != 0.0 && longitude != 0.0) {
                address = GeocodingUtils.getAddressFromLatLng(latitude, longitude);
            }
        }

        return AjaxResult.success(address);
    }

    /**
     * 预警通知 一键设置已读
     *
     * @param deviceId
     * @return
     */
    @Login
    @GetMapping("/setAlarmStatusByDeviceId")
    public AjaxResult setAlarmStatusByDeviceId(@RequestParam("deviceId") String deviceId) {
        return AjaxResult.success(this.watchAlarmDataService.setAppStatusByDeviceId(deviceId));
    }

    /**
     * 预警通知 设置已读
     *
     * @param ids
     * @return
     */
    @Login
    @PostMapping("/setAlarmStatusById")
    public AjaxResult setAlarmAppStatusById(@RequestBody List<String> ids) {
        return AjaxResult.success(this.watchAlarmDataService.setAppStatusById(ids));
    }

    /**
     * 预警通知 删除
     *
     * @param ids
     * @return
     */
    @Login
    @PostMapping("/deleteByIds")
    public AjaxResult deleteByIds(@RequestBody List<String> ids) {
        return AjaxResult.success(this.watchAlarmDataService.deleteByIds(ids));
    }

    /**
     * 预警通知 一键删除
     *
     * @param deviceId
     * @return
     */
    @Login
    @GetMapping("/deleteByDeviceId")
    public AjaxResult deleteByDeviceId(@RequestParam("deviceId") String deviceId) {
        return AjaxResult.success(this.watchAlarmDataService.deleteByDeviceId(deviceId));
    }

    /**
     * 首页-健康监测
     *
     * @param type
     * @return 健康数据
     */
    @GetMapping("/queryIndexWatchData")
    @Login
    public AjaxResult queryIndexWatchData(String type, String deviceId) {
        if (StringUtils.isBlank(type)) {
            return null;
        }
        String userId = getUserId();
        List<String> types = Arrays.stream(type.split(",")).collect(Collectors.toList());
        return AjaxResult.success(this.watchDataService.queryIndexWatchData(types, deviceId,userId));
    }

    /**
     * 查询设备状态
     *
     * @param deviceId
     * @return 设备状态
     */
    @GetMapping("/getStatus")
    public AjaxResult getStatus(@RequestParam("deviceId") String deviceId) {
        return AjaxResult.success(this.deviceInfoService.getStatus(deviceId));
    }


    /**
     * 查询app-健康监测数据类型列表
     */
    @GetMapping("/monitorDataType")
    public AjaxResult monitorDataType(WatchMonitorDataType fsMonitorDataType) {
        List<WatchMonitorDataType> list = fsMonitorDataTypeService.selectFsMonitorDataTypeList(fsMonitorDataType);
        return AjaxResult.success(list);
    }

    /**
     * 根据康监测数据类型id批量查询详情
     */
    @GetMapping("/getBatchData")
    public AjaxResult getBatchData(@RequestParam("ids") String ids) {
        if (StringUtils.isBlank(ids)) {
            return null;
        }
//        List<String> idList = Arrays.stream(ids.split(",")).collect(Collectors.toList());
//        if (!idList.isEmpty()) {
        if (StringUtils.isNotBlank(ids)) {
            return AjaxResult.success(fsMonitorDataTypeService.selectFsMonitorDataTypeByIds(ids));
        }
        return null;
    }

    /**
     * 查询绑定手表版本信息
     */
    @Login
    @GetMapping("/getDeviceData")
    @ApiOperation("绑定手表版本信息")
    public AjaxResult getDeviceData(@RequestParam(value = "deviceId", required = false) String deviceId) {
        if (StringUtils.isBlank(deviceId)) {
            String userId = getUserId();
            return AjaxResult.success(watchDeviceDataService.getByUserId(userId));
        } else {
            return AjaxResult.success(watchDeviceDataService.getByDeviceId(deviceId));
        }
    }

    /**
     * 健康报告-查询数据月份
     */
    @Login
    @ApiOperation("健康报告-查询数据月份")
    @GetMapping("/queryMonthByDeviceId")
    public TableDataInfo queryMonthByDeviceId(@RequestParam(value = "deviceId") String deviceId,
                                              @RequestParam("pageSize") Integer pageSize,
                                              @RequestParam("pageNum") Integer pageNum
    ) {
        if (StringUtils.isBlank(deviceId)) {
            return null;
        }
        TableDataInfo tableDataInfo = new TableDataInfo();
        QueryPageMonthVo vo = this.watchDataService.queryMonthByDeviceId(deviceId, pageSize, pageNum);
        tableDataInfo.setTotal(vo.getTotal());
        tableDataInfo.setRows(vo.getMonth());
        return tableDataInfo;
    }

    /**
     * 健康报告-血压趋势
     */
    @Login
    @ApiOperation("健康报告-血压趋势")
    @GetMapping("/queryBpByDateAndDeviceId")
    public AjaxResult queryBpByDateAndDeviceId(@RequestParam(value = "date", required = false) String date,
                                               @RequestParam(value = "deviceId") String deviceId) {
        return AjaxResult.success(this.watchThirdBpDataService.queryByDateAndDeviceId(date, deviceId));
    }

    /**
     * 健康报告-血糖趋势
     *
     * @param date     日期
     * @param deviceId 主键
     * @return 单条数据
     */
    @Login
    @GetMapping("/queryBgByDateAndDeviceId")
    @ApiOperation("健康报告-血糖趋势")
    public AjaxResult queryBgByDateAndDeviceId(@RequestParam(value = "date", required = false) String date,
                                               @RequestParam(value = "deviceId") String deviceId) {
        return AjaxResult.success(this.watchBloodGlucoseDataService.queryByDateAndDeviceId(date, deviceId));
    }

    /**
     * 健康报告-心率趋势
     *
     * @param date     当天日期
     * @param deviceId 主键
     * @return 单条数据
     */
    @Login
    @GetMapping("/queryHrByDate")
    @ApiOperation("健康报告-心率趋势")
    public AjaxResult queryHrByDate(@RequestParam(value = "date", required = false) String date,
                                    @RequestParam(value = "deviceId") String deviceId) {
        return AjaxResult.success(this.watchHeartRateDataService.queryByDate(date, deviceId));
    }

    /**
     * 健康报告-血氧监测
     *
     * @param date     日期
     * @param deviceId 主键
     * @return 某天的数据
     */
    @Login
    @ApiOperation("健康报告-血氧监测")
    @GetMapping("/querySpByDateAndDeviceId")
    public AjaxResult querySpByDateAndDeviceId(@RequestParam(value = "date", required = false) String date,
                                               @RequestParam(value = "deviceId") String deviceId) {
        return AjaxResult.success(this.watchSpo2DataService.queryByDateAndDeviceIdAndState(date, deviceId));
    }

    /**
     * 健康报告-睡眠趋势
     *
     * @param date     日期
     * @param deviceId 主键
     * @return 查询某天的数据, 及分析结论
     */
    @Login
    @ApiOperation("健康报告-睡眠趋势")
    @GetMapping("/querySlByDateAndDeviceId")
    public AjaxResult querySlByDateAndDeviceId(@RequestParam(value = "date", required = false) String date,
                                               @RequestParam(value = "deviceId") String deviceId) {
        return AjaxResult.success(this.watchSleepDataService.queryByDateAndDeviceIdAndState(date, deviceId));
    }

    //智慧医生

    /**
     * 智慧医生
     *
     * @param isOpen 智慧医生 0:关闭 1:打开
     * @return 结果
     */
    @Login
    @ApiOperation("智慧医生")
    @PostMapping("/smartDoctor/set")
    public AjaxResult smartDoctor(@RequestParam("deviceId") String deviceId, @RequestParam("isOpen") Integer isOpen) {
        if (StringUtils.isNotBlank(deviceId)) {
            WatchDeviceSetup watchDeviceSetup = watchDeviceSetupService.selectDeviceSetupByDeviceId(deviceId);
            if (isOpen == 1) {
                watchDeviceSetup.setSmartDoctor(isOpen);
            } else {
                watchDeviceSetup.setSmartDoctor(0);
            }
            return toAjax(watchDeviceSetupService.updateDeviceSetup(watchDeviceSetup));

        }
        return toAjax(false);
    }

    /**
     * 设置久坐
     *
     * @param sedentaries 久坐设置
     * @return 结果
     * 最多设置3个久坐提醒
     * repeat - true 重复, false 一次性
     * monday ~ sunday 对应的那天是否打开
     * start_hour/end_hour: 久坐检查时间段，开始/结束小时 24小时
     * duration: 设置累计久坐分钟数达到多少分钟提醒, 单位为5分钟，即设置1，等于5分钟
     * threshold: 一分钟内步数少于多少，判断这一分钟为久坐，计数+1，单位步，默认40
     * duration/threshold: 只针对新设备新版本有效
     */
    @Login
    @ApiOperation("设置久坐")
    @PostMapping("/sedentary/set")
    public AjaxResult sedentary(@RequestBody Sedentaries sedentaries) {
        if (StringUtils.isNotBlank(sedentaries.getDeviceId())) {
            return (deviceSetUpService.sedentary(sedentaries) ? AjaxResult.success() : AjaxResult.error("设备离线"));

        }
        return AjaxResult.error("未选择设备");
    }

    /**
     * 清除久坐
     *
     * @param deviceId 设备编号
     * @return 结果
     */
    @Login
    @ApiOperation("清除久坐")
    @GetMapping("/sedentary/clear")
    public AjaxResult sedentaryClear(@RequestParam("deviceId") String deviceId) {
        if (StringUtils.isNotBlank(deviceId)) {
            return (deviceSetUpService.sedentaryClear(deviceId) ? AjaxResult.success() : AjaxResult.error("设备离线"));
        }
        return AjaxResult.error("未选择设备");
    }

    /**
     * 设备跌倒检测开关
     *
     * @param deviceId 设备编号
     * @param flag     开/关
     * @return 结果
     */
    @Login
    @ApiOperation("设备跌倒检测开关")
    @GetMapping("/fallcheck")
    public AjaxResult fallcheck(@RequestParam("deviceId") String deviceId, @RequestParam("flag") Boolean flag) {
        if (StringUtils.isNotBlank(deviceId)) {
            return (deviceSetUpService.fallcheck(deviceId, flag) ? AjaxResult.success() : AjaxResult.error("设备离线"));
        }
        return AjaxResult.error("未选择设备");
    }

    //心脏健康

    /**
     * 自动房颤设置
     *
     * @param deviceId      设备编号
     * @param flag          打开自动房颤, false 关闭自动房颤
     * @param interval      自动房颤测量间隔，单位秒，最小取值30，最大取值120，设置超出范围则按60生效
     * @param rriSingleTime 可选值。设置为true，按照心率间隔，每次测量完心率后测量一次。设置为false，一直测量
     * @return 结果
     */
    @Login
    @GetMapping("/autoaf")
    public AjaxResult autoaf(@RequestParam("deviceId") String deviceId,
                             @RequestParam("flag") Boolean flag,
                             @RequestParam(value = "interval", required = false) Integer interval,
                             @RequestParam(value = "rriSingleTime", required = false) Boolean rriSingleTime) {
        if (StringUtils.isNotBlank(deviceId)) {
            Boolean isTrue = deviceSetUpService.autoaf(deviceId, flag, interval, rriSingleTime);
            return isTrue ? AjaxResult.success() : AjaxResult.error("设备离线");

        }
        return AjaxResult.error("未选择设备");
    }

    /**
     * 心率报警设置
     *
     * @param hrWarnSetting 设置信息
     * @return 结果
     * open - true 打开心率报警, false 关闭心率报警
     * high - 正常心率最高值
     * low - 正常心率最低值
     * threshold - 产生几次异常心率，开始报警
     * alarm_interval - 报警间隔，单位分钟
     */
    @Login
    @ApiOperation("心率报警设置")
    @PostMapping("/hralarm")
    public AjaxResult hralarm(@RequestBody HrWarnSetting hrWarnSetting) {
        if (StringUtils.isNotBlank(hrWarnSetting.getDeviceId())) {
            return (deviceSetUpService.hralarm(hrWarnSetting) ? AjaxResult.success() : AjaxResult.error("设备离线"));
        }
        return AjaxResult.error("未选择设备");
    }

    /**
     * 血氧报警设置
     *
     * @param spo2WarnSetting 设置信息
     * @return 结果
     * open - true 打开血氧报警, false 关闭血氧心率报警
     * low - 低于此血氧值报警
     */
    @Login
    @ApiOperation("血氧报警设置")
    @PostMapping("/spo2alarm")
    public AjaxResult spo2alarm(@RequestBody Spo2WarnSetting spo2WarnSetting) {
        if (StringUtils.isNotBlank(spo2WarnSetting.getDeviceId())) {
            return (deviceSetUpService.spo2alarm(spo2WarnSetting) ? AjaxResult.success() : AjaxResult.error("设备离线"));
        }
        return AjaxResult.error("未选择设备");
    }

    /**
     * 设置闹钟
     *
     * @param alarmClockVos 闹钟设置
     * @return 结果
     * 最多设置5个闹钟
     * repeat - true 重复, false 一次性
     * monday ~ sunday 对应的那天是否打开
     * hour/minute: 时间 小时:分钟, 24小时
     * title: 闹钟内容
     */
    @Login
    @ApiOperation("设置闹钟")
    @PostMapping("/clockalarm/set")
    public AjaxResult clockalarm(@RequestBody AlarmClockVos alarmClockVos) {
        if (StringUtils.isNotBlank(alarmClockVos.getDeviceId())) {
            return deviceSetUpService.clockalarm(alarmClockVos);
        }
        return AjaxResult.error("未选择设备");
    }

    /**
     * 清除闹钟
     *
     * @param deviceId 设备编号
     * @return 结果
     */
    @Login
    @ApiOperation("清除闹钟")
    @GetMapping("/clockalarm/clear")
    public AjaxResult clockalarmClear(@RequestParam("deviceId") String deviceId) {
        if (StringUtils.isNotBlank(deviceId)) {
            return deviceSetUpService.clockalarmClear(deviceId) ? AjaxResult.success() : AjaxResult.error("设备离线");
        }
        return AjaxResult.error("未选择设备");
    }

    /**
     * 省电
     *
     * @param param
     * @return 结果
     */
    @Login
    @ApiOperation("省电")
    @PostMapping("/power")
    public AjaxResult power(@RequestBody DevicePowerParam param) {
        if (StringUtils.isNotBlank(param.getDeviceId())) {
            return watchDataService.power(param.getDeviceId(),
                    param.getIsLcdgesture(),
                    param.getIsLocation(),
                    param.getIsPower(),
                    param.getIsHeartHealth()) ? AjaxResult.success() : AjaxResult.error("设备离线");
        }
        return AjaxResult.error("未选择设备");
    }


    /**
     * 下发通讯录
     *
     * @param phoneBooks 通讯录列表
     * @return 结果
     * sos - 是否紧急联系人, 要求至少有一个号码是SOS的
     * forbid - 可选，1 拦截陌生来电, 2 不拦截陌生来电。不传的时候不设置陌生来电拦截
     */
    @Login
    @ApiOperation("下发通讯录")
    @PostMapping("/phonebook/sync")
    public AjaxResult phonebook(@RequestBody PhoneBooks phoneBooks) {
        if (StringUtils.isNotBlank(phoneBooks.getDeviceId())) {
            return deviceSetUpService.phonebook(phoneBooks);
        }
        return AjaxResult.error("未选择设备");
    }

    /**
     * 清空通讯录
     *
     * @param deviceId 设备编号
     * @return 结果
     */
    @Login
    @ApiOperation("清空通讯录")
    @GetMapping("/phonebook/clear")
    public AjaxResult phonebookClear(@RequestParam("deviceId") String deviceId) {
        if (StringUtils.isNotBlank(deviceId)) {
            return toAjax(deviceSetUpService.phonebookClear(deviceId));

        }
        return toAjax(false);
    }


    /**
     * 日期与时间
     *
     * @param deviceId
     * @return 结果
     */
    @Login
    @ApiOperation("日期与时间")
    @GetMapping("/setDeviceTime")
    public AjaxResult setDeviceTime(@RequestParam("deviceId") String deviceId,
                                    @RequestParam("Itime") Integer Itime,
                                    @RequestParam("IDate") Integer IDate) {
        if (StringUtils.isNotBlank(deviceId)) {
            return watchDataService.setDeviceTime(deviceId, Itime, IDate) ? AjaxResult.success() : AjaxResult.error("设备设置超时");

        }
        return AjaxResult.error("未选择设备");
    }

    /**
     * 翻腕亮屏设置
     *
     * @param deviceId 设备编号
     * @param flag     开/关
     * @param start    开始
     * @param end      结束
     * @return 结果
     * open - true 打开, false 关闭
     * start_hour - start hour of lcd gesture, 0 - 23
     * end_hour - end hour of lcd gesture, 0 - 23
     */
    @Login
    @ApiOperation("翻腕亮屏设置")
    @GetMapping("/lcdgesture")
    public AjaxResult lcdgesture(@RequestParam("deviceId") String deviceId,
                                 @RequestParam("flag") Boolean flag,
                                 @RequestParam(value = "start", required = false) Integer start,
                                 @RequestParam(value = "end", required = false) Integer end) {
        if (StringUtils.isNotBlank(deviceId)) {
            Boolean isTrue = deviceSetUpService.lcdgesture(deviceId, flag, start, end);
            return isTrue ? AjaxResult.success() : AjaxResult.error("设备离线");

        }
        return AjaxResult.error("未选择设备");
    }


    /**
     * 单位设置
     *
     * @param deviceId
     * @return 结果
     */
    @Login
    @ApiOperation("单位设置")
    @GetMapping("/setDeviceUnit")
    public AjaxResult setDeviceUnit(@RequestParam("deviceId") String deviceId,
                                    @RequestParam("measure") Integer measure,
                                    @RequestParam("temperature") Integer temperature) {
        if (StringUtils.isNotBlank(deviceId)) {
            return watchDataService.setDeviceUnit(deviceId, measure, temperature) ? AjaxResult.success() : AjaxResult.error("设备离线");

        }
        return AjaxResult.error("未选择设备");
    }
    //新手指导

    /**
     * 查询新手引导列表
     */
    @ApiOperation("查询新手引导列表")
    @GetMapping("/guidList")
    public TableDataInfo guidList(WatchBeginnerGuide deviceBeginnerGuide) {
        startPage();
        deviceBeginnerGuide.setBelong("rt");
        List<WatchBeginnerGuide> list = watchBeginnerGuideService.selectWatchBeginnerGuideList(deviceBeginnerGuide);
        return getDataTable(list);
    }


    /**
     * 手表模式
     */
    @Login
    @ApiOperation("手表模式")
    @PostMapping("/setDeviceMode")
    public AjaxResult setDeviceMode(@RequestBody DeviceModeParam param) {
        if (StringUtils.isNotBlank(param.getDeviceId())) {
            return watchDataService.setDeviceMode(param.getDeviceId(),
                    param.getIsLocation(),
                    param.getInterval(),
                    param.getIsPower()) ? AjaxResult.success() : AjaxResult.error("设备离线");

        }
        return AjaxResult.error("未选择设备");
    }


    //设备信息
    @Login
    @ApiOperation("设备版本二维码json")
    @GetMapping("/getDeviceDataJson")
    public AjaxResult getDeviceDataJson(@RequestParam("deviceId") String deviceId) {
        if (StringUtils.isBlank(deviceId)) {
            return null;
        }
        WatchDeviceData watchDeviceData = watchDeviceDataService.getByDeviceId(deviceId);
        //组装json
        JSONObject jsonObject = new JSONObject();
        JSONObject json = new JSONObject();
        json.put("ble", watchDeviceData.getBle());
        json.put("imei", watchDeviceData.getDeviceId());
        json.put("model", watchDeviceData.getModel());
        json.put("version", watchDeviceData.getVersion());
        jsonObject.put("dev_info", json);
        return AjaxResult.success(jsonObject);
    }


    //    @Login
    @ApiOperation("修改sim手机号")
    @GetMapping("/updateSim")
    public AjaxResult updateSim(@RequestParam("deviceId") String deviceId, @RequestParam("sim") String sim) {
        if (StringUtils.isBlank(deviceId)) {
            return null;
        }
        WatchDeviceData watchDeviceData = new WatchDeviceData();
        watchDeviceData.setDeviceId(deviceId);
//        watchDeviceData.setSim(sim);
        watchDeviceData.setSIM(sim);
        return AjaxResult.success(watchDeviceDataService.updateByDeviceId(watchDeviceData));
    }


    @Login
    @ApiOperation("获取sim手机号")
    @GetMapping("/getSim")
    public AjaxResult getSim(@RequestParam("deviceId") String deviceId) {
        if (StringUtils.isBlank(deviceId)) {
            return AjaxResult.error("请选择设备!");
        }
        WatchDeviceData data = watchDeviceDataService.getByDeviceId(deviceId);
        if (data == null) {
            return AjaxResult.error("该设备不存在!");
        }
//        String sim = data.getSim();
        String sim = data.getSIM();
        if (StringUtils.isBlank(sim)) {
            return AjaxResult.error("该设备未设置手机号!");
        }
        return AjaxResult.success(sim);
    }
    //固件升级
    //恢复出厂

    /**
     * 设备恢复出厂
     *
     * @param deviceId 设备编号
     * @return 结果
     */
    @Login
    @GetMapping("/factory/reset")
    public AjaxResult reset(@RequestParam("deviceId") String deviceId) {
        if (StringUtils.isNotBlank(deviceId)) {
            return deviceSetUpService.reset(deviceId) ? AjaxResult.success() : AjaxResult.error("设备离线");

        }
        return AjaxResult.error("未选择设备");
    }


    /**
     * 首页绑定-设备信息
     */
    @GetMapping("/getInfoByDeviceIds")
    @Login
    @ApiOperation("首页绑定-设备信息")
    public AjaxResult getUserByDeviceId(@RequestParam("deviceIds") String deviceIds,
                                        @RequestParam(value = "isFamily") Boolean isFamily) {
        if (StringUtils.isBlank(deviceIds)) {
            return null;
        }
        String userId = getUserId();
        return AjaxResult.success(watchDataService.getUserByDeviceId(deviceIds, isFamily,Long.valueOf(userId)));
    }

    /**
     * 设备管理 -刷新
     *
     * @param deviceId 设备编号
     * @return 结果
     */
    @Login
    @GetMapping("/refresh")
    public AjaxResult refresh(@RequestParam("deviceId") String deviceId) {
        if (StringUtils.isNotBlank(deviceId)) {
            return AjaxResult.success(deviceSetUpService.datasync(deviceId));
        }
        return AjaxResult.error("未选择设备");
    }

    /**
     * 设备管理 -主页查询
     *
     * @param deviceId 设备编号
     * @return 结果
     */
    @Login
    @GetMapping("/getSetUpInfoByDeviceId")
    public AjaxResult getSetUpInfoByDeviceId(@RequestParam("deviceId") String deviceId) {
        if (StringUtils.isNotBlank(deviceId)) {
            return AjaxResult.success(watchDeviceSetupService.getSetUpInfoByDeviceId(deviceId));
        }
        return toAjax(false);
    }

    /**
     * 查询某天地理信息
     *
     * @param date     日期
     * @param deviceId 主键
     * @return 单条数据
     */
    @GetMapping("/queryGnssByDateAndDeviceId")
    public AjaxResult queryByDateAndDeviceId(@RequestParam(value = "date", required = false) String date,
                                             @RequestParam(value = "deviceId") String deviceId) {
        return AjaxResult.success(this.watchBasicInfoService.queryGnssByDateAndDeviceId(date, deviceId));
    }

    /**
     * 查询周报文字解析
     *
     * @param deviceId 主键
     * @return
     */
    @GetMapping("/queryHealthReport")
    public AjaxResult queryHealthReport(@RequestParam(value = "startTime") Date startTime,
                                        @RequestParam(value = "endTime") Date endTime,
                                        @RequestParam(value = "deviceId") String deviceId) {
        return AjaxResult.success(watchBasicInfoService.getAppFsUserHealthReportVo(startTime,endTime, deviceId));
    }

    /**
     * 查询某个时间段压力数据
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param deviceId  设备编号
     * @return 查询某个时间段数据
     */
    @GetMapping("/fatigue/list")
    public AjaxResult queryFatigueByDate(@RequestParam(value = "startTime") Date startTime,
                                         @RequestParam(value = "endTime") Date endTime,
                                         @RequestParam(value = "deviceId") String deviceId) {
        return AjaxResult.success(watchFatigueDataService.list(startTime, endTime, deviceId));
    }

    /**
     * 查询某个时间段压力异常数据统计
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param deviceId  设备编号
     * @return 查询某个时间段数据
     */
    @Login
    @GetMapping("/fatigue/count")
    public AjaxResult countFatigueByDate(@RequestParam(value = "startTime") Date startTime,
                                         @RequestParam(value = "endTime") Date endTime,
                                         @RequestParam(value = "deviceId") String deviceId) {
        return AjaxResult.success(watchFatigueDataService.countByDate(startTime, endTime, deviceId));
    }

    /**
     * 查询某个时间段压力数据 分页
     *
     * @param param
     * @return 查询某个时间段数据
     */
    @Login
    @GetMapping("/fatigue/page")
    public TableDataInfo queryFatiguePageByDate(WatchDataQueryParam param) {
        startPage();

        // 获取分页数据
        List<WatchFatigueDataVo> list = watchFatigueDataService.page(param);

        // 返回包含数据的TableDataInfo对象
        return getDataTable(list);
    }

    /**
     * 健康周报
     */
    @GetMapping("/getUserHealthInfoByDeviceId")
    @ApiOperation("健康周报-步数,卡路里,睡眠")
    public AjaxResult getUserHealthInfoByDeviceId(@RequestParam(value = "startTime") Date startTime,
                                                  @RequestParam(value = "endTime") Date endTime,
                                                  @RequestParam(value = "deviceId") String deviceId,
                                                  @RequestParam(value = "userId",required = false) Long userId) {
        if (com.fs.common.utils.StringUtils.isBlank(deviceId)) {
            return null;
        }
        if (userId == null){
            userId = Long.valueOf(getUserId());
        }
        return AjaxResult.success(watchSportDataService.getUserHealthInfoByDeviceId(deviceId,startTime,endTime,userId));
    }

}
