package com.fs.watch.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.his.utils.PhoneUtil;
import com.fs.watch.domain.*;
import com.fs.watch.domain.vo.AlarmClockObjectVo;
import com.fs.watch.domain.vo.AlarmClockVos;
import com.fs.watch.service.*;
import com.fs.watch.utils.MyHttpUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class DeviceSetUpServiceImpl implements DeviceSetUpService {
    private MyHttpUtils httpUtils = new MyHttpUtils();
    @Autowired
    private WatchUserService userService;
    @Autowired
    private WatchDeviceSetupService iDeviceSetupService;
    @Autowired
    private WatchDeviceDataService watchDeviceDataService;
    @Autowired
    private WatchSendMsgSetService watchSendMsgSetService;
    @Autowired
    private WatchSendMsgLogService watchSendMsgLogService;

    /**
     * 下发用户设置到设备
     *
     * @param userInfo
     * @return
     */
    @Override
    public Boolean userinfo(UserInfo userInfo) {


        if (userInfo.getDeviceId() != null) {
            //1.下发app
            WatchFsUser user = new WatchFsUser();
            user.setNickName(userInfo.getNickname());
            user.setSex(userInfo.getGender());
            user.setHeight(userInfo.getHeight());
            user.setWeight(userInfo.getWeight());
            user.setBirthday(userInfo.getBirthday());
            user.setTargetStep(userInfo.getTargetStep());
            user.setTargetCalorie(userInfo.getTargetCalorie());
            user.setDeviceId(userInfo.getDeviceId());
            userService.updateFsUserByDeviceId(user);

            //2.下发设备
            setDeviceUserInfo(userInfo);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Boolean setDeviceUserInfo(UserInfo userInfo) {
        Map<String, Object> params = new HashMap<>();
        params.put("device_id", userInfo.getDeviceId());
        if (userInfo.getBirthday() != null) {
            // 定义日期格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            // 将字符串解析为 LocalDate 对象

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            // 使用format方法将Date对象格式化为字符串
            LocalDate birthday = LocalDate.parse(sdf.format(userInfo.getBirthday()), formatter);
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            // 计算年龄
            int age = Period.between(birthday, currentDate).getYears();

            params.put("age", age);
        }
        if (userInfo.getHeight() != 0) {
            params.put("height", userInfo.getHeight());
        }
        if (userInfo.getWeight() != 0) {
            params.put("weight", userInfo.getWeight());
        }
        if (userInfo.getGender() != 0) {
            params.put("gender", userInfo.getGender());
        }
        if (userInfo.getBirthday() != null) {

        }
        //默认
//        params.put("calibrate_walk", 100);
//        params.put("calibrate_run", 100);
        //{"ReturnCode":0,"Data":{"MessageId":1816661214168709632,"PayloadBase64Byte":"MTU=","RequestId":"02A8C8C6-BD06-5C89-B5F8-B526246B18E6","RrpcCode":"SUCCESS","Success":true}}
        Map response = httpUtils.getPost("/entservice/cmd/userinfo", params);
        if (response != null) {
            return (Boolean) response.get("Success");
        } else {
            return false;
        }
    }

    /**
     * 设备实时定位
     *
     * @param deviceNumber
     * @return
     */
    @Override
    public Boolean realtimeLocation(String deviceNumber) {
        Map<String, Object> params = new HashMap<>();
        params.put("device_id", deviceNumber);
        Map response = httpUtils.getPost("/entservice/cmd/realtime/location", params);
        if (response != null) {
            return (Boolean) response.get("Success");
        } else {
            return false;
        }
    }

    /**
     * 设备数据一键同步
     *
     * @param deviceNumber
     * @return
     */
    @Override
    public Boolean datasync(String deviceNumber) {
        List<String> list = Arrays.asList(deviceNumber.split(","));
        Boolean result = true;
        for (String id : list) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            Map response = httpUtils.getPost("/entservice/cmd/datasync", params);
            if (response != null) {
                result = result && (Boolean) response.get("Success");
            }

        }
        return result;
    }

    /**
     * 设备在线状态
     *
     * @param deviceNumber
     * @return
     */
    @Override
    public Integer status(String deviceNumber) {
        Map<String, Object> params = new HashMap<>();
        params.put("device_id", deviceNumber);
        Map response = httpUtils.getRequest1("/entservice/device/status", params);
        if (response != null) {
            if (response.get("Data") != null) {
                HashMap<String,Object> data = JSON.parseObject(response.get("Data").toString(), HashMap.class);
                if (data.get("status") != null) {
                    return (Integer) data.get("status");
                }
            }
        }

        return -1;
    }

    @Override
    public Boolean fallcheck(String deviceNumber, Boolean flag) {
        List<String> list = Arrays.asList(deviceNumber.split(","));
        Boolean result = true;
        for (String id : list) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            params.put("fall_check", flag);
            Map response = httpUtils.getPost("/entservice/cmd/fallcheck", params);
            if (response != null) {
                result = result && (Boolean) response.get("Success");
                if ((Boolean) response.get("Success")) {
                    WatchDeviceSetup deviceSetup = iDeviceSetupService.selectDeviceSetupByDeviceId(id);
                    if (deviceSetup != null) {
                        deviceSetup.setFallcheck(flag ? 1 : 0);
                        iDeviceSetupService.updateDeviceSetup(deviceSetup);
                    }
                }
            }
        }
        return result;
    }

    /**
     * gps_interval_time - unit is minute
     * power_mode - 可选，设备省电设置：
     * 1 - low耗电
     * 2 - mid耗电
     * 3 - high耗电
     * 这个指令仅对H200生效，其他设备请使用 设备数据上传间隔设置
     */
    @Override
    public Boolean autolocate(String deviceNumber, Boolean flag, Integer time, Integer mode) {

        List<String> list = Arrays.asList(deviceNumber.split(","));
        Boolean result = false;
        for (String id : list) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            params.put("gps_auto_check", flag);
            params.put("gps_interval_time", time);
            if (mode != 1 && mode != 2 && mode != 3) {
                return false;
            } else {
                params.put("power_mode", mode);
            }
            //获取设备model 这个指令仅对H200生效，其他设备请使用 设备数据上传间隔设置
            WatchDeviceData deviceData = watchDeviceDataService.getByDeviceId(deviceNumber);
            if (deviceData != null && deviceData.getModel().contains("H200")) {
                Map response = httpUtils.getPost("/entservice/cmd/autolocate?device_model=H200A", params);
                if (response != null) {
                    result = result || (Boolean) response.get("Success");
                }
            } else {
                return datafreq(deviceNumber, flag, time, mode);
            }

        }
        return result;
    }

    @Override
    public AjaxResult phonebook(PhoneBooks phoneBooks) {
        List<String> list = Arrays.asList(phoneBooks.getDeviceId().split(","));
        Boolean result = true;
        for (String id : list) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            params.put("phone_book", phoneBooks.getPhoneList());
            //forbid - 可选，1 拦截陌生来电, 2 不拦截陌生来电。不传的时候不设置陌生来电拦截
            Integer forbid = phoneBooks.getForbid();
            if (forbid != 1 && forbid != 2) {
//                return false;
                return AjaxResult.success();
            }
            params.put("forbid", forbid);
            Map response = httpUtils.getPost("/entservice/phonebook/sync", params);
            if (response != null) {
                result = result && (Boolean) response.get("Success");
                if ((Boolean) response.get("Success")) {
                    WatchDeviceSetup deviceSetup = iDeviceSetupService.selectDeviceSetupByDeviceId(id);
                    if (deviceSetup != null) {
                        DevicePhonebooks devicePhonebooks = new DevicePhonebooks();
                        devicePhonebooks.setForbid(forbid);
                        devicePhonebooks.setPhoneList(phoneBooks.getPhoneList());
                        deviceSetup.setPhonebook(JSONUtil.toJsonStr(devicePhonebooks));
                        iDeviceSetupService.updateDeviceSetup(deviceSetup);
                    }
                } else if (StringUtils.contains(response.get("ErrorMessage").toString(), "The device is offline.")) {
                    return AjaxResult.error("该设备不在线!");
                }
            }
        }
//        return result;
        return result ? AjaxResult.success() : AjaxResult.error();
    }

    @Override
    public Boolean phonebookClear(String deviceNumber) {
        List<String> list = Arrays.asList(deviceNumber.split(","));
        Boolean result = true;
        for (String id : list) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            Map response = httpUtils.getPost("/entservice/phonebook/clear", params);
            if (response != null) {
                result = result && (Boolean) response.get("Success");
                if ((Boolean) response.get("Success")) {
                    WatchDeviceSetup deviceSetup = iDeviceSetupService.selectDeviceSetupByDeviceId(id);
                    if (deviceSetup != null) {
                        String phonebook = deviceSetup.getPhonebook();
                        DevicePhonebooks devicePhonebooks = JSONObject.parseObject(phonebook, DevicePhonebooks.class);
                        devicePhonebooks.setPhoneList(null);
                        deviceSetup.setPhonebook(JSONUtil.toJsonStr(devicePhonebooks));
                        iDeviceSetupService.updateDeviceSetup(deviceSetup);
                    }
                }
            }
        }
        return result;
    }

    @Override
    public Boolean datafreq(String deviceNumber, Boolean flag, Integer time, Integer mode) {
        List<String> list = Arrays.asList(deviceNumber.split(","));
        Boolean result = true;
        for (String id : list) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            params.put("gps_auto_check", flag);
            params.put("gps_interval_time", time);
            if (mode != 1 && mode != 2 && mode != 3) {
                return false;
            } else {
                params.put("power_mode", mode);
            }
            //ErrorMessage -> The specified operation has failed. The device has timed out.
            Map response = httpUtils.getPost("/entservice/cmd/datafreq", params);
            if (response != null) {
                result = result && (Boolean) response.get("Success");
            }
        }
        return result;
    }

    @Override
    public Boolean lcdgesture(String deviceNumber, Boolean flag, Integer start, Integer end) {
        List<String> list = Arrays.asList(deviceNumber.split(","));
        Boolean result = true;
        for (String id : list) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            if (flag) {
                if (!((0 <= start && start <= 23)) || (!(end >= 0 && end <= 24)) || (start > end)) {
                    return false;
                } else {
                    params.put("start_hour", start);
                    params.put("end_hour", end);
                }
            }
            Map response = httpUtils.getPost("/entservice/cmd/lcdgesture", params);
            if (response != null) {
                result = result && (Boolean) response.get("Success");
                if ((Boolean) response.get("Success")) {
                    WatchDeviceSetup deviceSetup = iDeviceSetupService.selectDeviceSetupByDeviceId(id);
                    if (deviceSetup != null) {
                        DeviceLcdgesture deviceLcdgesture = new DeviceLcdgesture();
                        deviceLcdgesture.setOpen(flag);
                        deviceLcdgesture.setStart_hour(start);
                        deviceLcdgesture.setEnd_hour(end);
                        deviceSetup.setLcdgesture(JSONUtil.toJsonStr(deviceLcdgesture));
                        //关联省电
                        DevicePower devicePower = JSONObject.parseObject(deviceSetup.getPower(), DevicePower.class);
                        devicePower.setIsLcdgesture(flag);
                        deviceSetup.setPower(JSONUtil.toJsonStr(devicePower));
                        iDeviceSetupService.updateDeviceSetup(deviceSetup);
                    }
                }
            }
        }
        return result;
    }

    /**
     * open - true 打开心率报警, false 关闭心率报警
     * high - 正常心率最高值
     * low - 正常心率最低值
     * threshold - 产生几次异常心率，开始报警
     * alarm_interval - 报警间隔，单位分钟
     *
     * @param hrWarnSetting
     * @return
     */
    @Override
    public Boolean hralarm(HrWarnSetting hrWarnSetting) {
        List<String> list = Arrays.asList(hrWarnSetting.getDeviceId().split(","));
        Boolean result = true;
        for (String id : list) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            params.put("open", hrWarnSetting.isOpen());
            int high = hrWarnSetting.getHigh();
            if (high > 200) {
                high = 200;
            } else if (high < 50) {
                high = 50;
            }
            params.put("high", high);
            int low = hrWarnSetting.getLow();
            if (low > 190) {
                low = 190;
            } else if (high < 40) {
                low = 50;
            }
            params.put("low", low);
            params.put("threshold", hrWarnSetting.getTimeout());
            params.put("alarm_interval", hrWarnSetting.getInterval());
            Map response = httpUtils.getPost("/entservice/cmd/hralarm", params);
            if (response != null) {
                result = result && (Boolean) response.get("Success");
                if ((Boolean) response.get("Success")) {
                    WatchDeviceSetup deviceSetup = iDeviceSetupService.selectDeviceSetupByDeviceId(id);
                    if (deviceSetup != null) {
                        DeviceHralarm deviceHralarm = new DeviceHralarm();
                        deviceHralarm.setOpen(hrWarnSetting.isOpen());
                        deviceHralarm.setHigh(high);
                        deviceHralarm.setLow(low);
                        deviceHralarm.setThreshold(hrWarnSetting.getTimeout());
                        deviceHralarm.setAlarm_interval(hrWarnSetting.getInterval());
                        deviceSetup.setHralarm(JSONUtil.toJsonStr(deviceHralarm));
                        iDeviceSetupService.updateDeviceSetup(deviceSetup);
                    }
                }
            }
        }
        return result;
    }

    /**
     * open - true 打开血氧报警, false 关闭血氧心率报警
     * low - 低于此血氧值报警
     *
     * @param spo2WarnSetting
     * @return
     */
    @Override
    public Boolean spo2alarm(Spo2WarnSetting spo2WarnSetting) {
        List<String> list = Arrays.asList(spo2WarnSetting.getDeviceId().split(","));
        Boolean result = true;
        for (String id : list) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            params.put("open", spo2WarnSetting.isOpen());
            int low = spo2WarnSetting.getLow();
            if (low > 93) {
                low = 93;
            } else if (low < 80) {
                low = 80;
            }
            params.put("low", low);
            Map response = httpUtils.getPost("/entservice/cmd/spo2alarm", params);
            if (response != null) {
                result = result && (Boolean) response.get("Success");
                if ((Boolean) response.get("Success")) {
                    WatchDeviceSetup deviceSetup = iDeviceSetupService.selectDeviceSetupByDeviceId(id);
                    if (deviceSetup != null) {
                        DeviceSpo2alarm deviceSpo2alarm = new DeviceSpo2alarm();
                        deviceSpo2alarm.setOpen(spo2WarnSetting.isOpen());
                        deviceSpo2alarm.setLow(low);
                        deviceSetup.setSpo2alarm(JSONUtil.toJsonStr(deviceSpo2alarm));
                        iDeviceSetupService.updateDeviceSetup(deviceSetup);
                    }
                }
            }
        }
        return result;
    }

    /**
     * open - true 打开血压报警, false 关闭血压报警
     * sbp_high - 高压最高值，单位：mmhg
     * sbp_below - 高压最低值，单位：mmhg
     * dbp_high - 低压最高值，单位：mmhg
     * dbp_below - 低压最低值，单位：mmhg
     *
     * @param bpWarnSetting
     * @return
     */
    @Override
    public Boolean bpalarm(BpWarnSetting bpWarnSetting) {
        List<String> list = Arrays.asList(bpWarnSetting.getDeviceId().split(","));
        Boolean result = true;
        for (String id : list) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            params.put("open", bpWarnSetting.isOpen());
            params.put("sbp_high", bpWarnSetting.getSbp_high());
            params.put("sbp_below", bpWarnSetting.getSbp_below());
            params.put("dbp_high", bpWarnSetting.getDbp_high());
            params.put("dbp_below", bpWarnSetting.getDbp_below());
            Map response = httpUtils.getPost("/entservice/cmd/bpalarm", params);
            if (response != null) {
                result = result && (Boolean) response.get("Success");
            }
        }
        return result;
    }

    /**
     * temperatue set as 10 times of your prefer value, e.g. 36.1 set 361
     *
     * @param deviceNumber
     * @param flag
     * @param high
     * @param low
     * @return
     */
    @Override
    public Boolean temperature(String deviceNumber, Boolean flag, Integer high, Integer low) {
        List<String> list = Arrays.asList(deviceNumber.split(","));
        Boolean result = true;
        for (String id : list) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            params.put("open", flag);
            if (flag) {
                params.put("high", high);
                params.put("low", low);
            }
            Map response = httpUtils.getPost("/entservice/cmd/temperature/alarm", params);
            if (response != null) {
                result = result && (Boolean) response.get("Success");
            }
        }
        return result;
    }

    /**
     * open - true 打开自动房颤, false 关闭自动房颤
     * interval - 自动房颤测量间隔，单位秒，最小取值30，最大取值120，设置超出范围则按60生效
     * rri_single_time - 可选值。设置为true，按照心率间隔，每次测量完心率后测量一次。设置为false，一直测量
     *
     * @param deviceNumber
     * @param flag
     * @param interval
     * @param rriSingleTime
     * @return
     */
    @Override
    public Boolean autoaf(String deviceNumber, Boolean flag, Integer interval, Boolean rriSingleTime) {
        List<String> list = Arrays.asList(deviceNumber.split(","));
        Boolean result = true;

        for (String id : list) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            params.put("open", flag);
            if (flag) {
                if (interval == null) {
                    interval = 60;
                    rriSingleTime = false;
                } else {
                    if (interval < 30 || interval > 120) {
                        interval = 60;
                    }
                    if (rriSingleTime == null) {
                        rriSingleTime = true;
                    }
                }

                params.put("interval", interval);
                params.put("rri_single_time", rriSingleTime);
            }
            Map response = httpUtils.getPost("/entservice/cmd/autoaf", params);
            if (response != null) {
                result = result && (Boolean) response.get("Success");
                if ((Boolean) response.get("Success")) {
                    WatchDeviceSetup deviceSetup = iDeviceSetupService.selectDeviceSetupByDeviceId(id);
                    if (deviceSetup != null) {
                        deviceSetup.setHeartHealth(flag ? 1 : 0);
                        //关联省电设置
                        DevicePower devicePower = JSONObject.parseObject(deviceSetup.getPower().toString(), DevicePower.class);
                        if (devicePower != null) {
                            devicePower.setIsHeartHealth(flag);
                            deviceSetup.setPower(JSONUtil.toJsonStr(devicePower));
                        }
                        iDeviceSetupService.updateDeviceSetup(deviceSetup);

                    }
                }
            }
        }

        return result;
    }

    /**
     * 最多设置5个闹钟
     * repeat - true 重复, false 一次性
     * monday ~ sunday 对应的那天是否打开
     * hour/minute: 时间 小时:分钟, 24小时
     * title: 闹钟内容
     *
     * @param alarmClockVos
     * @return
     */
    @Override
    public AjaxResult clockalarm(AlarmClockVos alarmClockVos) {
        List<AlarmClockObjectVo> alarmclockVos = alarmClockVos.getAlarmclockVo();
        if (alarmclockVos.size() > 5) {
            return AjaxResult.error("最多只能5个闹钟");
        }
        List<AlarmClockObject> alarmClocks = new ArrayList<>();
        List<AlarmClockObject> falseAlarmClocks = new ArrayList<>();
        String deviceId = alarmClockVos.getDeviceId();
        List<String> list = Arrays.asList(deviceId.split(","));
        if (alarmclockVos.size() == 0) {
            for (String id : list) {
                //清除
                Boolean clearFlag = clockalarmClear(id);
                if (clearFlag) {
                    //更新设置
                    WatchDeviceSetup deviceSetup = iDeviceSetupService.selectDeviceSetupByDeviceId(id);
                    deviceSetup.setAlarmClock(null);
                    iDeviceSetupService.updateDeviceSetup(deviceSetup);
                    return AjaxResult.success();
                } else {
                    return AjaxResult.error("删除失败");
                }
            }

        }
        for (AlarmClockObjectVo alarmClockObjectVo : alarmclockVos) {
            int hour = alarmClockObjectVo.getHour();
            if (hour < 0 || hour > 23) {
                return AjaxResult.error("时间格式不对");
            }
            int minute = alarmClockObjectVo.getMinute();
            if (minute < 0 || minute > 59) {
                return AjaxResult.error("时间格式不对");
            }
            alarmClockObjectVo.setSetupTime(new Date());
            if (alarmClockObjectVo.getStatus() == null || alarmClockObjectVo.getStatus()) {
                AlarmClockObject alarmClock = new AlarmClockObject();
                BeanUtils.copyProperties(alarmClockObjectVo, alarmClock);
                //判断是否重复
                setIsRepeat(alarmClock, hour, minute);
                alarmClocks.add(alarmClock);
            } else {
                falseAlarmClocks.add(alarmClockObjectVo);
            }


        }

        Boolean result = true;

        if (alarmClocks.size() > 0) {
            for (String id : list) {
                Map<String, Object> params = new HashMap<>();
                params.put("device_id", id);
                params.put("alarms", alarmClocks);
                Map response = httpUtils.getPost("/entservice2/clockalarm/set", params);
                if (response != null) {
                    result = result && (Boolean) response.get("Success");
                    if ((Boolean) response.get("Success")) {
                        WatchDeviceSetup deviceSetup = iDeviceSetupService.selectDeviceSetupByDeviceId(id);
                        if (deviceSetup != null) {
                            DeviceAlarmClock deviceAlarmClock = new DeviceAlarmClock();

                            deviceAlarmClock.setOpen(true);
                            deviceAlarmClock.setAlarmClockObjectVos(alarmclockVos);
                            deviceSetup.setAlarmClock(JSONUtil.toJsonStr(deviceAlarmClock));
                            iDeviceSetupService.updateDeviceSetup(deviceSetup);
                        }
                    } else if (StringUtils.contains(response.get("ErrorMessage").toString(), "The device is offline.")) {
                        return AjaxResult.error("该设备不在线!");
                    } else {
                        return AjaxResult.error("设置失败!");
                    }
                }
            }
            return result ? AjaxResult.success() : AjaxResult.error();
        } else {
            for (String id : list) {
                WatchDeviceSetup deviceSetup = iDeviceSetupService.selectDeviceSetupByDeviceId(id);
                if (deviceSetup != null) {
                    DeviceAlarmClock deviceAlarmClock = new DeviceAlarmClock();

                    deviceAlarmClock.setOpen(true);
                    deviceAlarmClock.setAlarmClockObjectVos(alarmclockVos);
                    deviceSetup.setAlarmClock(JSONUtil.toJsonStr(deviceAlarmClock));
                    iDeviceSetupService.updateDeviceSetup(deviceSetup);
                }
            }

            return AjaxResult.success();
        }

    }

    private static void setIsRepeat(AlarmClockObject alarmClock, int hour, int minute) {
        boolean repeat = alarmClock.isRepeat();
        if (!repeat) {
            //仅一次
            if (!(alarmClock.isMonday()
                    || alarmClock.isTuesday()
                    || alarmClock.isWednesday()
                    || alarmClock.isThursday()
                    || alarmClock.isFriday()
                    || alarmClock.isSaturday()
                    || alarmClock.isSunday()
            )) {
                //设置时间是否超过当前时间
                LocalTime specifiedTime = LocalTime.of(hour, minute, 0); // 设置时间，例如 14:30:45
                LocalTime currentTime = LocalTime.now(); // 获取当前时间

                //获取当前周几
                int i = DateUtil.dayOfWeek(DateUtils.getNowDate()); //1表示周日，2表示周一
                if (specifiedTime.isBefore(currentTime)) {
                    //指定时间在当前时间之前,设置第二天
                    switch (i) {
                        case 1:
                            alarmClock.setMonday(true);
                            break;
                        case 2:
                            alarmClock.setTuesday(true);
                            break;
                        case 3:
                            alarmClock.setWednesday(true);
                            break;
                        case 4:
                            alarmClock.setThursday(true);
                            break;
                        case 5:
                            alarmClock.setFriday(true);
                            break;
                        case 6:
                            alarmClock.setSaturday(true);
                            break;
                        case 7:
                            alarmClock.setSunday(true);
                            break;
                        default:
                            break;
                    }
                } else {
                    switch (i) {
                        case 1:
                            alarmClock.setSunday(true);
                            break;
                        case 2:
                            alarmClock.setMonday(true);
                            break;
                        case 3:
                            alarmClock.setTuesday(true);
                            break;
                        case 4:
                            alarmClock.setWednesday(true);
                            break;
                        case 5:
                            alarmClock.setThursday(true);
                            break;
                        case 6:
                            alarmClock.setFriday(true);
                            break;
                        case 7:
                            alarmClock.setSaturday(true);
                            break;
                        default:
                            break;
                    }
                }

            }
        }
    }

    @Override
    public Boolean clockalarmClear(String deviceNumber) {
        List<String> list = Arrays.asList(deviceNumber.split(","));
        Boolean result = true;
        for (String id : list) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            Map response = httpUtils.getPost("/entservice2/clockalarm/clear", params);
            if (response != null) {
                result = result && (Boolean) response.get("Success");
                if ((Boolean) response.get("Success")) {
                    WatchDeviceSetup deviceSetup = iDeviceSetupService.selectDeviceSetupByDeviceId(id);
                    if (deviceSetup != null) {
                        DeviceAlarmClock deviceAlarmClock = new DeviceAlarmClock();
                        deviceAlarmClock.setOpen(false);
                        deviceSetup.setAlarmClock(JSONUtil.toJsonStr(deviceAlarmClock));
                        iDeviceSetupService.updateDeviceSetup(deviceSetup);
                    }
                }
            }
        }
        return result;
    }

    /**
     * 最多设置3个久坐提醒
     * repeat - true 重复, false 一次性
     * monday ~ sunday 对应的那天是否打开
     * start_hour/end_hour: 久坐检查时间段，开始/结束小时 24小时
     * duration: 设置累计久坐分钟数达到多少分钟提醒, 单位为5分钟，即设置1，等于5分钟
     * threshold: 一分钟内步数少于多少，判断这一分钟为久坐，计数+1，单位步，默认40
     * duration/threshold: 只针对新设备新版本有效
     *
     * @param sedentaries
     * @return
     */
    @Override
    public Boolean sedentary(Sedentaries sedentaries) {
        if (sedentaries.getDeviceId() == null) {
            return false;
        }
        List<SedentaryObject> list = sedentaries.getSedentaries();
        //最多设置3个久坐提醒
        if (list.size() > 3 || list.isEmpty()) {
            return false;
        }
        //久坐检查时间段，开始/结束小时 24小时
        for (SedentaryObject sedentaryObject : list) {
            int startHour = sedentaryObject.getStart_hour();
            if (startHour < 0 || startHour > 24) {
                return false;
            }
            int endHour = sedentaryObject.getEnd_hour();
            if (endHour < 0 || endHour > 24) {
                return false;
            }
            if (startHour > endHour) {
                return false;
            }
            //threshold: 一分钟内步数少于多少，判断这一分钟为久坐，计数+1，单位步，默认40
            if (sedentaryObject.getThreshold() == 0) {
                sedentaryObject.setThreshold(40);
            }
        }
        List<String> idList = Arrays.asList(sedentaries.getDeviceId().split(","));
        Boolean result = true;
        for (String id : idList) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            params.put("sedentaries", list);
            Map response = httpUtils.getPost("/entservice3/sedentary/set", params);
            if (response != null) {
                result = result && (Boolean) response.get("Success");
                if ((Boolean) response.get("Success")) {
                    WatchDeviceSetup deviceSetup = iDeviceSetupService.selectDeviceSetupByDeviceId(id);
                    if (deviceSetup != null) {
                        DeviceSedentary deviceSedentary = new DeviceSedentary();
                        if (list.size() > 0) {
                            deviceSedentary.setOpen(1);
                            deviceSedentary.setSedentaries(list);
                        } else {
                            deviceSedentary.setOpen(0);
                        }
                        deviceSetup.setSedentary(JSONUtil.toJsonStr(deviceSedentary));
                        iDeviceSetupService.updateDeviceSetup(deviceSetup);
                    }
                }
            }
        }
        return result;
    }

    @Override
    public Boolean sedentaryClear(String deviceNumber) {
        List<String> idList = Arrays.asList(deviceNumber.split(","));
        Boolean result = true;
        for (String id : idList) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            Map response = httpUtils.getPost("/entservice3/sedentary/clear", params);
            if (response != null) {
                result = result && (Boolean) response.get("Success");
                if ((Boolean) response.get("Success")) {
                    WatchDeviceSetup deviceSetup = iDeviceSetupService.selectDeviceSetupByDeviceId(id);
                    if (deviceSetup != null) {
                        DeviceSedentary deviceSedentary = new DeviceSedentary();
                        deviceSedentary.setOpen(0);
                        deviceSetup.setSedentary(JSONUtil.toJsonStr(deviceSedentary));
                        iDeviceSetupService.updateDeviceSetup(deviceSetup);
                    }
                }
            }
        }
        return result;
    }

    /**
     * step - 目标步数
     * distance - 目标距离,单位米
     * calorie - 目标卡路里,单位千卡
     *
     * @param targetSetting
     * @return
     */
    @Override
    public Boolean goal(TargetSetting targetSetting) {
        List<String> idList = Arrays.asList(targetSetting.getDeviceId().split(","));
        Boolean result = true;
        for (String id : idList) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            params.put("step", targetSetting.getStep());
            params.put("distance", targetSetting.getDistance());
            params.put("calorie", targetSetting.getCalorie());
            Map response = httpUtils.getPost("/entservice/cmd/goal", params);
            if (response != null) {
                result = result && (Boolean) response.get("Success");
            }
        }
        return result;
    }

    @Override
    public Boolean reset(String deviceNumber) {
        List<String> idList = Arrays.asList(deviceNumber.split(","));
        Boolean result = true;
        for (String id : idList) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            Map response = httpUtils.getPost("/entservice/cmd/factory/reset", params);
            if (response != null) {
                result = result && (Boolean) response.get("Success");
                if ((Boolean) response.get("Success")) {
                    WatchDeviceSetup deviceSetup = iDeviceSetupService.selectDeviceSetupByDeviceId(id);
                    if (deviceSetup != null) {
                        //添加设备设置信息
                        deviceSetup.setSmartDoctor(0);
                        deviceSetup.setSedentary(JSONUtil.toJsonStr(new DeviceSedentary()));
                        deviceSetup.setFallcheck(0);
                        deviceSetup.setHeartHealth(0);
                        deviceSetup.setHralarm(JSONUtil.toJsonStr(new DeviceHralarm()));
                        deviceSetup.setSpo2alarm(JSONUtil.toJsonStr(new DeviceSpo2alarm()));
                        deviceSetup.setAlarmClock(JSONUtil.toJsonStr(new DeviceAlarmClock()));
                        deviceSetup.setPower(JSONUtil.toJsonStr(new DevicePower()));
                        deviceSetup.setPhonebook(JSONUtil.toJsonStr(new DevicePhonebooks()));
                        deviceSetup.setTime(JSONUtil.toJsonStr(new DeviceTime()));
                        deviceSetup.setLcdgesture(JSONUtil.toJsonStr(new DeviceLcdgesture()));
                        deviceSetup.setUnit(JSONUtil.toJsonStr(new DeviceUnit()));
                        deviceSetup.setMode(JSONUtil.toJsonStr(new DeviceMode()));
                        deviceSetup.setVersion("1.0.0");
                        iDeviceSetupService.updateDeviceSetup(deviceSetup);
                    }
                }
            }
        }
        return result;
    }

    @Override
    public Boolean language(LanguageSetting languageSetting) {
        List<String> idList = Arrays.asList(languageSetting.getDeviceId().split(","));
        Boolean result = true;
        for (String id : idList) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            int languageid = languageSetting.getLanguageid();
            if (languageid < 0 || languageid > 23) {
                return false;
            }
            params.put("language", languageid);
            Map response = httpUtils.getPost("/entservice/cmd/language/set", params);
            if (response != null) {
                result = result && (Boolean) response.get("Success");
            }
        }
        return result;
    }

    /**
     * 向设备发送消息
     * @param deviceNumber 设备id
     * @param title 消息标题
     * @param description 消息内容
     * @param type
     * @param operatorType
     * @param userId
     * @return
     */
    @Override
    public AjaxResult message(String deviceNumber,
                              String title,
                              String description,
                              String type,
                              Integer operatorType,
                              Long userId,
                              String detailsType) {
        //1.记录发送消息日志
        WatchSendMsgLog watchSendMsgLog = new WatchSendMsgLog();
        watchSendMsgLog.setOperatorType(operatorType);
        watchSendMsgLog.setOperId(userId);
        watchSendMsgLog.setTitle(title);
        watchSendMsgLog.setDescription(description);
        watchSendMsgLog.setDeviceIds(deviceNumber);
        watchSendMsgLog.setDetailsType(detailsType);
        if (type!=null){
            if ("medication".equals(type)) {
                //用药提醒
                watchSendMsgLog.setMsgType(1);
            } else if ("study".equals(type)){
                //看课提醒
                watchSendMsgLog.setMsgType(0);
            } else if ("test".equals(type)){
                //系统测试提醒
                watchSendMsgLog.setMsgType(2);
            } else {
                //其他消息
                watchSendMsgLog.setMsgType(3);
            }
        }
        Integer sendStatus = null;
        //2.判断是否在允许发送时间内
        WatchSendMsgSet watchSendMsgSet = watchSendMsgSetService.selectWatchSendMsgSetByType(type);
        if (watchSendMsgSet != null) {
            if (watchSendMsgSet.getStatus()==1){
                String start = watchSendMsgSet.getStart();
                String end = watchSendMsgSet.getEnd();
                if (StringUtils.isNotBlank(start) && StringUtils.isNotBlank(end)) {
                    // 解析时间字符串为 LocalTime 对象
                    DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
                    LocalTime startTime = LocalTime.parse(start, timeFormatter);
                    LocalTime endTime = LocalTime.parse(end, timeFormatter);
                    LocalTime now = LocalTime.now();
                    //在开始时间前或在结束时间后
                    if (now.isBefore(startTime) || now.isAfter(endTime)) {
                        sendStatus = 1;
                        watchSendMsgLog.setStatus(sendStatus);
                        watchSendMsgLog.setErrorMsg("未在设置时间"+start+"-" +end + "内发送消息");
                        watchSendMsgLogService.insertWatchSendMsgLog(watchSendMsgLog);
                        return AjaxResult.error("未在设置时间"+start+"-" +end + "内发送消息");
                    }
                }
            }
        }

        List<String> idList = Arrays.asList(deviceNumber.split(","));
        boolean result = true;
        sendStatus = 0;
        for (String id : idList) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            params.put("title", title);
            params.put("description", description);
            Map response = httpUtils.getPost("/entservice/cmd/message", params);
            if (response != null) {
                if (response.get("ErrorMessage") != null) {
//                    if ("ErrorMessage -> The specified operation has failed. The device has timed out.".equals(response.get("ErrorMessage"))) {
//                        return true;
//                    }
                    sendStatus = 1;
                    watchSendMsgLog.setErrorMsg(response.get("ErrorMessage").toString());

                }
                result = result && (Boolean) response.get("Success");
            }
        }
        watchSendMsgLog.setStatus(sendStatus);
        watchSendMsgLogService.insertWatchSendMsgLog(watchSendMsgLog);
        return result?AjaxResult.success():AjaxResult.error(watchSendMsgLog.getErrorMsg());
    }

    /**
     * fall_threshold: 跌倒检测的灵敏度，默认14000
     *
     * @param deviceNumber
     * @param fallThreshold
     * @return
     */
    @Override
    public Boolean sensitivity(String deviceNumber, Integer fallThreshold) {
        List<String> idList = Arrays.asList(deviceNumber.split(","));
        boolean result = true;
        for (String id : idList) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            if (fallThreshold == null || fallThreshold < 0) {
                fallThreshold = 14000;
            }
            params.put("fall_threshold", fallThreshold);
            Map response = httpUtils.getPost("/entservice/cmd/fallcheck/sensitivity", params);
            if (response != null) {
                result = result && (Boolean) response.get("Success");
            }
        }
        return result;
    }

    @Override
    public Boolean measureInterval(String deviceNumber, Integer interval) {
        List<String> idList = Arrays.asList(deviceNumber.split(","));
        boolean result = true;
        for (String id : idList) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            params.put("interval", interval);
            Map response = httpUtils.getPost("/entservice/cmd/measure/interval/hr", params);
            if (response != null) {
                result = result && (Boolean) response.get("Success");
            }
        }
        return result;
    }

    @Override
    public Boolean other(String deviceNumber, Integer interval) {
        List<String> idList = Arrays.asList(deviceNumber.split(","));
        boolean result = true;
        for (String id : idList) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            params.put("interval", interval);
            Map response = httpUtils.getPost("/entservice/cmd/measure/interval/other", params);
            if (response != null) {
                result = result && (Boolean) response.get("Success");
            }
        }
        return result;
    }

//    @Override
//    public DeviceUserInfo getuserinfo(String deviceId) {
//        /**
//         *  "device_id": "phone",
//         *             "nickname": "迈远",
//         *             "gender": 1,
//         *             "height": 175,
//         *             "weight": 60,
//         *             "birthday": "1970-12-12",
//         *             "uid": "",
//         *             "target_step": 10000,
//         *             "target_calorie": 300,
//         *             "phone": "18183110924"
//         */
//        //查询用户
//        FsUser user = userService.selectFsUserByDeviceId(deviceId);
//        if (user == null) {
//            return null;
//        } else {
//            DeviceUserInfo userInfo = new DeviceUserInfo();
//            userInfo.setDeviceId(deviceId);
//            userInfo.setNickname(user.getNickname());
//            userInfo.setGender(user.getSex() == 1 ? "男" : "女");
//            userInfo.setHeight(user.getHeight());
//            userInfo.setWeight(user.getWeight());
//
//
//            userInfo.setBirthday(DateTimeFormatter.ofPattern("yyyy-MM-dd")
//                    .withZone(ZoneId.systemDefault()).format(user.getBirthday().toInstant()));
//            userInfo.setTargetStep(user.getTargetStep());
//            userInfo.setTargetCalorie(user.getTargetCalorie());
//            userInfo.setPhone(user.getPhone());
//            return userInfo;
//
//        }
//    }

    @Override
    public Boolean gpsLocate(String deviceNumber, Boolean gpsAutoCheck, Integer gpsIntervalTime, Boolean runGps) {
        List<String> idList = Arrays.asList(deviceNumber.split(","));
        boolean result = true;
        for (String id : idList) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            params.put("gps_auto_check", gpsAutoCheck);
            params.put("gps_interval_time", gpsIntervalTime);
            params.put("run_gps", runGps);
            Map response = httpUtils.getPost("/entservice/cmd/gps/locate", params);
            if (response != null) {
                result = result && (Boolean) response.get("Success");
            }
        }
        return result;
    }

    @Override
    public Boolean timeFormat(String deviceNumber, Integer format) {
        List<String> idList = Arrays.asList(deviceNumber.split(","));
        boolean result = true;
        for (String id : idList) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            params.put("hour_format", format);
            Map response = httpUtils.getPost("/entservice/cmd/timeformat", params);
            if (response != null) {
                result = result && (Boolean) response.get("Success");
            }
        }
        return result;
    }

    @Override
    public Boolean dateFormat(String deviceNumber, Integer format) {
        List<String> idList = Arrays.asList(deviceNumber.split(","));
        boolean result = true;
        for (String id : idList) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            params.put("date_format", format);
            Map response = httpUtils.getPost("/entservice/cmd/dateformat", params);
            if (response != null) {
                result = result && (Boolean) response.get("Success");
            }
        }
        return result;
    }

    @Override
    public Boolean distanceUnit(String deviceNumber, Integer unit) {
        List<String> idList = Arrays.asList(deviceNumber.split(","));
        boolean result = true;
        for (String id : idList) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            params.put("distance_unit", unit);
            Map response = httpUtils.getPost("/entservice/cmd/distanceunit", params);
            if (response != null) {
                result = result && (Boolean) response.get("Success");
            }
        }
        return result;
    }

    @Override
    public Boolean temperatureUnit(String deviceNumber, Integer unit) {
        List<String> idList = Arrays.asList(deviceNumber.split(","));
        boolean result = true;
        for (String id : idList) {
            Map<String, Object> params = new HashMap<>();
            params.put("device_id", id);
            params.put("temperature_unit", unit);
            Map response = httpUtils.getPost("/entservice/cmd/temperatureunit", params);
            if (response != null) {
                result = result && (Boolean) response.get("Success");
            }
        }
        return result;
    }

    @Override
    public DeviceUserInfo getUserinfo(String deviceId,Long userId,Integer selectType) {
        /**
         *  "device_id": "phone",
         *             "nickname": "迈远",
         *             "gender": 1,
         *             "height": 175,
         *             "weight": 60,
         *             "birthday": "1970-12-12",
         *             "uid": "",
         *             "target_step": 10000,
         *             "target_calorie": 300,
         *             "phone": "18183110924"
         */
        //查询用户
        WatchFsUser user = userService.selectWatchFsUserByDeviceIdAndUserId(deviceId, userId,selectType);
        if (user != null) {
            DeviceUserInfo userInfo = new DeviceUserInfo();
            userInfo.setDeviceId(deviceId);
            userInfo.setNickname(user.getNickName());
            if (user.getSex() != null) {
                userInfo.setGender(user.getSex() == 1 ? "男" : "女");
            }
            if (user.getHeight() != null) {
                userInfo.setHeight(user.getHeight());
            }
            if (user.getWeight() != null) {

                userInfo.setWeight(user.getWeight());
            }
            if (user.getBirthday() != null) {

                userInfo.setBirthday(DateTimeFormatter.ofPattern("yyyy-MM-dd")
                        .withZone(ZoneId.systemDefault()).format(user.getBirthday().toInstant()));
            }
            if (user.getTargetStep() != null) {
                userInfo.setTargetStep(user.getTargetStep());
            }
            if (user.getTargetCalorie() != null) {
                userInfo.setTargetCalorie(user.getTargetCalorie());
            }
            String phone = user.getPhone();
            if (phone != null) {
//                userInfo.setPhone(user.getPhone());
                if (phone.startsWith("1") && phone.length() == 11) {
                    userInfo.setPhone(phone);
                } else {
                    userInfo.setPhone(PhoneUtil.decryptPhone(phone));
                }
            }
            return userInfo;
        }
        return null;
    }
}
