package com.sckw.slope.detection.consumer;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sckw.core.model.constant.NumberConstant;
import com.sckw.core.model.enums.*;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.core.utils.IdWorker;
import com.sckw.core.utils.StringUtils;
import com.sckw.core.web.response.HttpResult;
import com.sckw.log.TraceLog.TraceLog;
import com.sckw.slope.detection.common.config.SmsTemplateConfig;
import com.sckw.slope.detection.dao.mysql.*;
import com.sckw.slope.detection.dao.tdengine.SlopeDataMapper;
import com.sckw.slope.detection.model.dos.mysql.*;
import com.sckw.slope.detection.model.dos.tdengine.Devices;
import com.sckw.slope.detection.model.dto.DevicesAlarm;
import com.sckw.slope.detection.model.dto.DevicesItem;
import com.sckw.slope.detection.model.dto.SystemDict;
import com.sckw.slope.detection.model.param.SmsMessageParam;
import com.sckw.slope.detection.service.CommonService;
import com.sckw.slope.detection.service.TdengineService;
import com.sckw.slope.detection.service.api.DetectionApiService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lfdc
 * @description
 * @date 2023-10-26 08:10:45
 */
@Slf4j
@Service("system/iot/device_data_slope_demo")
public class MqttDeviceCallbackHandler extends AbstractHandler {

    @Value("${sms.url}")
    private String messageUrl;

    @Autowired
    CommonService commonService;

    @Autowired
    DetectionApiService detectionApiService;

    @Autowired
    SlopeDataMapper slopeDataMapper;

    @Autowired
    KwsDeviceMapper deviceMapper;

    @Autowired
    KwsThresholdMapper thresholdMapper;

    @Autowired
    HandlerFactory handlerFactory;

    @Autowired
    SmsTemplateConfig smsTemplateConfig;

    @TraceLog(description = "处理system/iot/device_data/")
//    @Transactional
    @DSTransactional
    public HttpResult handle(String topic, String payload) {
        // 根据topic分别进行消息处理。
        log.info("MqttDeviceCallbackHandler:" + topic + "|" + payload);
        System.out.println("system/iot/original_data_slope");
        DevicesAlarm devicesAlarm = JSONObject.parseObject(payload, DevicesAlarm.class);
        Map<String, SystemDict> dictByDictCode = commonService.getDictByDictCode(DictEnum.MODEL_PART);
        JSONObject objects = JSONObject.parseObject(payload);
        String deviceTs = objects.getString("ts");
        String deviceGuid = objects.getString("guid");
        String deviceTslverId = objects.getString("tslver_id");
        String deviceMsgId = objects.getString("msg_id");
        String deviceRawTs = objects.getString("raw_ts");
        JSONArray checkArr = objects.getJSONArray("check_arr");
        try {
//            DevicesAlarm devicesAlarm = JSONObject.parseObject(payload, DevicesAlarm.class);
            String deviceCode = devicesAlarm.getGuid();
            List<KwsDevice> deviceList = deviceMapper.selectList(new LambdaQueryWrapper<KwsDevice>()
                    .eq(KwsDevice::getSnCodeFullName, deviceCode)
                    .eq(KwsDevice::getDelFlag, NumberConstant.ZERO)
            );
            KwsDevice device = null;
            if (!org.springframework.util.CollectionUtils.isEmpty(deviceList)) {
                device = deviceList.get(0);
            }
            if (device == null) {
                log.error("接收处理数据:{}", payload);
                log.error("设备数据并未维护+[" + devicesAlarm.getGuid() + "],不做处理");
                return null;
            }
            List<DevicesItem> devicesItemList = devicesAlarm.getDevicesItemList();
            if (!CollectionUtils.isEmpty(devicesItemList)) {
                for (DevicesItem devicesItem : devicesItemList) {
                    String itemName = devicesItem.getItemName();
                    String itemValue = devicesItem.getItemValue();
                    List<KwsThreshold> kwsThresholds = thresholdMapper.selectList(new LambdaQueryWrapper<KwsThreshold>()
                            .eq(KwsThreshold::getDeviceId, device.getId())
                            .eq(KwsThreshold::getDelFlag, NumberConstant.ZERO)
                            .eq(KwsThreshold::getItemName, itemName)
                    );
                    if (org.springframework.util.CollectionUtils.isEmpty(kwsThresholds)) {
                        continue;
                    }
                    Long ts = devicesAlarm.getTs();
//                    //获取到是 十位 1700970600
//                    if (Objects.nonNull(ts)) {
//                        ts = ts * 1000;
//                    }
                    //判断是否满足设备超时离线报警
                    checkDeviceAlarm(deviceCode, device, itemValue, ts);
                    //判断是否满足数值超阈值报警
                    Map<String, String> map = checkThresholdAlarm(devicesItem, kwsThresholds, device);
                    if ("2".equals(map.get("flag"))) {
                        Long level = Long.valueOf(map.get("level"));
                        Long thresholdId = Long.valueOf(map.get("thresholdId"));
                        //阈值表以及明细表存储
                        long id = insertAlarmAndDetail(level, device, thresholdId, itemValue, ts, AlarmTitleEnum.ALARM_TITLE_TWO.getStatus(), AlarmTypeEnum.ALARM_ONE.getCode());
                        //todo 不适用redis存统计  使用新字段处理
                        /**阈值次数存redis*/
//                        String key = Global.REDIS_SYS_ALARM_PREFIX + Global.POUND + String.valueOf(id) + Global.POUND + AlarmTypeEnum.ALARM_ONE.getStatus()
//                                + Global.POUND + AlarmTitleEnum.ALARM_TITLE_TWO.getStatus();
//                        String number = RedissonUtils.getString(key);
//                        Long count = alarmDetailMapper.selectCount(new LambdaQueryWrapper<KwsAlarmDetail>()
//                                .eq(KwsAlarmDetail::getAlarmId, id)
//                                .eq(KwsAlarmDetail::getStatus, 0)
//                        );
//                        if (StringUtils.isBlank(number)) {
//                            RedissonUtils.putString(key, "1", Global.COMMON_EXPIRE);
//                        } else {
//                            RedissonUtils.putString(key, count.toString(), Global.COMMON_EXPIRE);
//                        }

                        /*【露天矿山边坡监测系统】尊敬的管理员，2023-10-01 12:23:34监测到一级告警。
                            设备名称：位移监测设备-gnss一号机，监测数值：55。123456789N，请尽快处理问题。*/
                        /**
                         * 数据告警
                         * 尊敬的管理员，${time}监测到${level}级告警。
                         * 设备名称: ${name}，监测数值: ${value}，请尽快处理问题。
                         */
                        KwsThreshold kwsThreshold = thresholdMapper.selectById(thresholdId);
                        String phones = kwsThreshold.getPhones();
                        List<String> pushToPhone = StringUtils.splitStrToList(phones, String.class);
                        LocalDateTime localDateTime = Instant.ofEpochSecond(ts).atZone(ZoneId.systemDefault()).toLocalDateTime();
                        String time = DateUtil.format(localDateTime, "yyyy-MM-dd HH:mm:ss");
                        Map<String, String> templateParam = new HashMap<>();
                        templateParam.put("time",time);
                        templateParam.put("level", AlarmLevelEnum.getName(level.intValue()));
                        templateParam.put("name",device.getName());
                        templateParam.put("value",itemValue);
//                        commonService.pushSmsMessage(pushToPhone,
//                                smsTemplateConfig.getDataAlarm().getSmsCode(),
//                                smsTemplateConfig.getDataAlarm().getSignName(),templateParam);
                    }

                }
            }
        } catch (Exception e) {
            log.error("mqtt消费异常:{}", e.getMessage(), e);
        }
        return HttpResult.ok();
    }

    @Async
    public void pushSmsMessage(String messageUrl, KwsDevice device, Long level, Long thresholdId, Map<String, Object> messageMap) {
        Long deviceId = device.getId();
        KwsProjectDevice projectDevice = projectDeviceMapper.selectOne(new LambdaQueryWrapper<KwsProjectDevice>()
                .eq(KwsProjectDevice::getDeviceId, deviceId)
                .eq(KwsProjectDevice::getDelFlag, 0)
                .eq(KwsProjectDevice::getStatus, 0)
                .orderByDesc(KwsProjectDevice::getCreateTime)
                .last(" limit 1")
        );
        LambdaQueryWrapper<KwsAlarm> wrapper = new LambdaQueryWrapper<KwsAlarm>()
                .eq(KwsAlarm::getLevel, level.intValue())
                .eq(KwsAlarm::getDeviceId, deviceId)
                .eq(KwsAlarm::getType, NumberConstant.ONE)
                .orderByDesc(KwsAlarm::getCreateTime);
        if (projectDevice != null) {
            wrapper.eq(KwsAlarm::getProjectId, projectDevice.getProjectId())
                    .eq(KwsAlarm::getMountainId, projectDevice.getMountainId());
            if (projectDevice.getProjectId() != null) {
                wrapper.eq(KwsAlarm::getCompanyId, projectDevice.getCompanyId());
            }
        }
        SmsMessageParam param = new SmsMessageParam();
        param.setCode("123456");
        param.setType(2);
        List<String> stringList = new ArrayList<>();
        stringList.add("18215677925");
        param.setPushTo(stringList);
        SmsMessageParam.Content content = new SmsMessageParam.Content();
        content.setTemplateCode("SMS_262585113");
        content.setSignName("矿拉拉");
//        SmsMessageParam.TemplateParam templateParam = new SmsMessageParam.TemplateParam();
//        templateParam.setName("123");
//        templateParam.setStart("123");
//        content.setTemplateParam(templateParam);
        param.setContent(content);
        detectionApiService.pushSmsMessage(messageUrl, JSONObject.toJSONString(param));

    }

    private void checkDeviceAlarm(String deviceCode, KwsDevice device, String itemValue, Long ts) {
        try {
            Devices devices = tdengineService.selectLastData(device.getSnCode());
            if (devices != null) {
                Date deviceTime = devices.getTs();
                Date date = new Date();
                long diff = Math.abs(date.getTime() - deviceTime.getTime());
                long diffHours = diff / (60 * 60 * 1000) % 24;
                if (diffHours > 24) {
                    long id = insertAlarmAndDetail(1L, device, device.getId(), itemValue, ts, AlarmTitleEnum.ALARM_TITLE_ONE.getStatus(), AlarmTypeEnum.ALARM_TWO.getCode());
//                    /**阈值次数存redis*/
//                    String key = Global.REDIS_SYS_ALARM_PREFIX + Global.POUND + String.valueOf(id) + Global.POUND + AlarmTypeEnum.ALARM_TWO.getStatus()
//                            + Global.POUND + AlarmTitleEnum.ALARM_TITLE_ONE.getStatus();
//                    String number = RedissonUtils.getString(key);
//                    Long count = alarmDetailMapper.selectCount(new LambdaQueryWrapper<KwsAlarmDetail>()
//                            .eq(KwsAlarmDetail::getAlarmId, id)
//                            .eq(KwsAlarmDetail::getStatus, 0)
//                    );
//                    if (StringUtils.isBlank(number)) {
//                        RedissonUtils.putString(key, "1", Global.COMMON_EXPIRE);
//                    } else {
//                        RedissonUtils.putString(key, count.toString(), Global.COMMON_EXPIRE);
//                    }
                    // todo 暂未设备告警电话，设备告警不推送短信
                    device.setOnline(1);
                    deviceMapper.updateById(device);
                } else {
                    device.setOnline(0);
                    deviceMapper.updateById(device);
                }
            }
        } catch (Exception e) {
            log.error("判断是否满足设备超时离线报警 error ", e.getMessage(), e);
        }
    }

    @Autowired
    KwsAlarmMapper alarmMapper;

    @Autowired
    KwsAlarmDetailMapper alarmDetailMapper;

    @Autowired
    KwsDeviceRelationMapper deviceRelationMapper;

    @Autowired
    KwsProjectDeviceMapper projectDeviceMapper;

    @Autowired
    KwsDeviceReferenceMapper deviceReferenceMapper;

    @Autowired
    private TdengineService tdengineService;


    private Map<String, String> checkThresholdAlarm(DevicesItem devicesItem, List<KwsThreshold> kwsThresholds, KwsDevice device) {
        String itemName = devicesItem.getItemName();
        String itemValue = devicesItem.getItemValue();
        Long deviceId = device.getId();
        KwsDeviceReference deviceRelation = deviceReferenceMapper.selectOne(new LambdaQueryWrapper<KwsDeviceReference>()
                .eq(KwsDeviceReference::getDeviceId, deviceId)
                .eq(KwsDeviceReference::getDelFlag, NumberConstant.ZERO)
                .eq(KwsDeviceReference::getType, "1")
                .eq(KwsDeviceReference::getItem, itemName)
        );
        /**x、y、z要进行偏移量计算  其他数值保持源数据进行计算*/
        List<String> checkItemName = new ArrayList<>();
        checkItemName.add(DictItemEnum.ALTITUDE_Z.getValue());
        checkItemName.add(DictItemEnum.LONGITUDE_X.getValue());
        checkItemName.add(DictItemEnum.LATITUDE_Y.getValue());
        //需要计算的阈值
        if (checkItemName.contains(itemName)) {
            BigDecimal offset = commonService.computeOffset(itemValue, itemName, deviceRelation);
            Map<String, Long> maxMap = new HashMap<>();
            Map<String, Long> minMap = new HashMap<>();
            List<BigDecimal> maxList = new ArrayList<>();
            List<BigDecimal> minList = new ArrayList<>();
            //添加阈值map
            for (KwsThreshold kwsThreshold : kwsThresholds) {
                String max = kwsThreshold.getMax();
                Long thresholdId = kwsThreshold.getId();
                String min = kwsThreshold.getMin();
                Integer level = kwsThreshold.getLevel();
                maxMap.put(max, level.longValue());
                maxMap.put(level.toString(), thresholdId.longValue());
                minMap.put(min, level.longValue());
                minMap.put(level.toString(), thresholdId.longValue());
            }
            for (KwsThreshold kwsThreshold : kwsThresholds) {
                maxList.add(new BigDecimal(kwsThreshold.getMax()));
                minList.add(new BigDecimal(kwsThreshold.getMin()));
                String max = kwsThreshold.getMax();
                Long thresholdId = kwsThreshold.getId();
                String min = kwsThreshold.getMin();
                Integer level = kwsThreshold.getLevel();
                /**为了获取最阈值等级*/
                if (maxMap.get(max) != null) {
                    Long integer = maxMap.get(max);
                    if (integer <= level) {
                        maxMap.put(max, level.longValue());
                        maxMap.put(level.toString(), thresholdId.longValue());
                    }
                }
                if (minMap.get(min) != null) {
                    Long integer = minMap.get(min);
                    if (integer <= level) {
                        minMap.put(min, level.longValue());
                        minMap.put(level.toString(), thresholdId.longValue());
                    }
                }
            }
//        minList = minList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
            minList = minList.stream().sorted().distinct().collect(Collectors.toList());
            maxList = maxList.stream().sorted().distinct().collect(Collectors.toList());
            /**计算阈值界限*/
            BigDecimal max = getMaxNumber(offset, maxList);
            BigDecimal min = getMinNumber(offset, minList);
            /**存在阈值触发*/
            Map<String, String> map = new HashMap<>();
            map.put("level", "1");
            map.put("thresholdId", "1");
            map.put("flag", "1");
            if (min != null || max != null) {
                if (max != null) {
                    Long level = maxMap.get(max.toString());
                    Long thresholdId = maxMap.get(level.toString());
                    map.put("level", level.toString());
                    map.put("thresholdId", thresholdId.toString());
                    map.put("flag", "2");
//                    insertAlarmAndDetail(level, device, thresholdId, itemValue, ts);
                }
                if (min != null) {
                    Long level = minMap.get(min.toString());
                    Long thresholdId = minMap.get(level.toString());
                    map.put("level", level.toString());
                    map.put("thresholdId", thresholdId.toString());
                    map.put("flag", "2");
                }
            }
            return map;
        } else {
            //直接阈值计算的处理
            Map<String, Long> maxMap = new HashMap<>();
            Map<String, Long> minMap = new HashMap<>();
            List<BigDecimal> maxList = new ArrayList<>();
            List<BigDecimal> minList = new ArrayList<>();
            for (KwsThreshold kwsThreshold : kwsThresholds) {
                String max = kwsThreshold.getMax();
                Long thresholdId = kwsThreshold.getId();
                String min = kwsThreshold.getMin();
                Integer level = kwsThreshold.getLevel();
                maxMap.put(max, level.longValue());
                maxMap.put(level.toString(), thresholdId.longValue());
                minMap.put(min, level.longValue());
                minMap.put(level.toString(), thresholdId.longValue());
            }
            for (KwsThreshold kwsThreshold : kwsThresholds) {
                maxList.add(new BigDecimal(kwsThreshold.getMax()));
                minList.add(new BigDecimal(kwsThreshold.getMin()));
                String max = kwsThreshold.getMax();
                Long thresholdId = kwsThreshold.getId();
                String min = kwsThreshold.getMin();
                Integer level = kwsThreshold.getLevel();
                /**为了获取最阈值等级*/
                if (maxMap.get(max) != null) {
                    Long integer = maxMap.get(max);
                    if (integer <= level) {
                        maxMap.put(max, level.longValue());
                        maxMap.put(level.toString(), thresholdId.longValue());
                    }
                }
                if (minMap.get(min) != null) {
                    Long integer = minMap.get(min);
                    if (integer <= level) {
                        minMap.put(min, level.longValue());
                        minMap.put(level.toString(), thresholdId.longValue());
                    }
                }
            }
//        minList = minList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
            minList = minList.stream().sorted().distinct().collect(Collectors.toList());
            maxList = maxList.stream().sorted().distinct().collect(Collectors.toList());
            /**计算阈值界限*/
            BigDecimal max = getMaxNumber(new BigDecimal(itemValue), maxList);
            BigDecimal min = getMinNumber(new BigDecimal(itemValue), minList);
            /**存在阈值触发*/
            Map<String, String> map = new HashMap<>();
            map.put("level", "1");
            map.put("thresholdId", "1");
            map.put("flag", "1");
            if (min != null && max != null) {
                if (max != null) {
                    Long level = maxMap.get(max);
                    Long thresholdId = maxMap.get(level.toString());
                    map.put("level", level.toString());
                    map.put("thresholdId", thresholdId.toString());
                    map.put("flag", "2");
//                    insertAlarmAndDetail(level, device, thresholdId, itemValue, ts);
                }
                if (min != null) {
                    Long level = minMap.get(min);
                    Long thresholdId = minMap.get(level.toString());
                    map.put("level", level.toString());
                    map.put("thresholdId", thresholdId.toString());
                    map.put("flag", "2");
                }
            }
            return map;
        }
    }

    /**
     * 保存阈值主表以及明细表
     *
     * @param level       阈值等级
     * @param device      设备
     * @param thresholdId 阈值id/设备id
     * @param itemValue   td数据当时检测值
     * @param ts          td时间
     * @param alarmTitle  设备类型明细
     * @param type        设备类型
     */
    private long insertAlarmAndDetail(Long level, KwsDevice device, Long thresholdId,
                                      String itemValue, Long ts,
                                      String alarmTitle, Integer type
    ) {
        Long deviceId = device.getId();
        KwsProjectDevice projectDevice = projectDeviceMapper.selectOne(new LambdaQueryWrapper<KwsProjectDevice>()
                .eq(KwsProjectDevice::getDeviceId, deviceId)
                .eq(KwsProjectDevice::getDelFlag, 0)
                .orderByDesc(KwsProjectDevice::getCreateTime)
                .last(" limit 1")
        );
        LambdaQueryWrapper<KwsAlarm> wrapper = new LambdaQueryWrapper<KwsAlarm>()
                .eq(KwsAlarm::getLevel, level.intValue())
                .eq(KwsAlarm::getDeviceId, deviceId)
                .eq(KwsAlarm::getStatus, NumberConstant.ZERO)
                .eq(KwsAlarm::getType, type)
                .orderByDesc(KwsAlarm::getCreateTime);
        if (projectDevice != null) {
            wrapper.eq(KwsAlarm::getProjectId, projectDevice.getProjectId())
                    .eq(KwsAlarm::getMountainId, projectDevice.getMountainId());
            if (projectDevice.getProjectId() != null) {
                wrapper.eq(KwsAlarm::getCompanyId, projectDevice.getCompanyId());
            }
        }
        long alarmId = new IdWorker(NumberConstant.ONE).nextId();
        List<KwsAlarm> alarms = alarmMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(alarms)) {
            KwsAlarm alarm = new KwsAlarm();
            String mountainId = projectDevice == null ? null : projectDevice.getMountainId();
            String companyId = projectDevice == null ? null : projectDevice.getCompanyId();
            String projectId = projectDevice == null ? null :
                    (projectDevice.getProjectId() == null ? null : projectDevice.getProjectId().toString());
            alarm.setId(alarmId);
            alarm.setCompanyId(companyId);
            alarm.setMountainId(mountainId);
            alarm.setProjectId(projectId);
            alarm.setDeviceId(deviceId);
            alarm.setTitle(alarmTitle);
            alarm.setLevel(level.intValue());
            alarm.setType(type);
            LocalDateTime localDateTime = Instant.ofEpochSecond(ts).atZone(ZoneId.systemDefault()).toLocalDateTime();
//            LocalDateTime localDateTime = new Date(ts).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
            alarm.setCreateTime(localDateTime);
            alarm.setUpdateTime(localDateTime);
            alarm.setStatus(0);
            alarm.setTriggerTimes(1);
            alarmMapper.insert(alarm);
            KwsAlarmDetail alarmDetail = new KwsAlarmDetail();
            alarmDetail.setId(new IdWorker(NumberConstant.ONE).nextId());
            alarmDetail.setMountainId(mountainId);
            alarmDetail.setCompanyId(companyId);
            alarmDetail.setAlarmId(alarmId);
            alarmDetail.setPid(thresholdId);
            alarmDetail.setVal(itemValue);
            alarmDetail.setLat(device.getLogicLat());
            alarmDetail.setLng(device.getLogicLng());
            alarmDetail.setAlt(device.getLogicAlt());
            alarmDetail.setCreateTime(localDateTime);
            alarmDetail.setUpdateTime(localDateTime);
            alarmDetail.setStatus(0);
            alarmDetailMapper.insert(alarmDetail);
        } else {
            alarmId = alarms.get(0).getId();
            KwsAlarm alarm = alarms.get(0);
            LocalDateTime localDateTime = Instant.ofEpochSecond(ts).atZone(ZoneId.systemDefault()).toLocalDateTime();
//            LocalDateTime localDateTime = new Date(ts).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
            alarm.setUpdateTime(localDateTime);
            alarm.setStatus(0);
            Long aLong = alarmDetailMapper.selectCount(new LambdaQueryWrapper<KwsAlarmDetail>()
                    .eq(KwsAlarmDetail::getAlarmId, alarmId)
                    .eq(KwsAlarmDetail::getStatus, 0));
            alarm.setTriggerTimes(aLong.intValue());
            alarmMapper.updateById(alarm);
            String mountainId = projectDevice == null ? null : projectDevice.getMountainId();
            String companyId = projectDevice == null ? null : projectDevice.getCompanyId();
            String projectId = projectDevice == null ? null :
                    (projectDevice.getProjectId() == null ? null : projectDevice.getProjectId().toString());
            KwsAlarmDetail alarmDetail = new KwsAlarmDetail();
            alarmDetail.setId(new IdWorker(NumberConstant.TWO).nextId());
            alarmDetail.setMountainId(mountainId);
            alarmDetail.setCompanyId(companyId);
            alarmDetail.setAlarmId(alarm.getId());
            alarmDetail.setPid(thresholdId);
            alarmDetail.setVal(itemValue);
            alarmDetail.setLat(device.getLogicLat());
            alarmDetail.setLng(device.getLogicLng());
            alarmDetail.setAlt(device.getLogicAlt());
            alarmDetail.setCreateTime(localDateTime);
            alarmDetail.setUpdateTime(localDateTime);
            alarmDetail.setStatus(0);
            alarmDetailMapper.insert(alarmDetail);
        }
        return alarmId;
    }

    /**
     * 计算最小值
     *
     * @param number
     * @param list
     * @return
     */
    private static BigDecimal getMinNumber(BigDecimal number, List<BigDecimal> list) {
        for (BigDecimal decimal : list) {
            if (number.compareTo(decimal) < 0) {
                return decimal;
            }
        }
        return null;
    }

    private static BigDecimal getMaxNumber(BigDecimal number, List<BigDecimal> list) {
        for (BigDecimal decimal : list) {
            if (number.compareTo(decimal) > 0) {
                return decimal;
            }
        }
        return null;
    }

    public static void main(String[] args) {

        Long ts = 1700969880l;
        Instant timestamp = Instant.ofEpochSecond(ts);

        ts = ts * 1000;
        Instant instant = new Date(ts).toInstant();
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.of("+8"));
        LocalDateTime timeLocalDateTime = offsetDateTime.toLocalDateTime();

        instant = Instant.ofEpochMilli(ts);
        ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
        LocalDateTime localDateTimes = zonedDateTime.toLocalDateTime();
        System.out.println(localDateTimes);

        String aaa = "{\"ts\":1700808976,\"guid\":\"0838161D-4C64-EC3E-A3A8-C736C47D93D4\",\"tslver_id\":\"3\",\"msg_id\":\"586569123094614016\",\"raw_ts\":\"\",\"check_arr\":[{\"itemName\":\"lng\",\"itemValue\":\"103.51826198069217\"},{\"itemName\":\"lat\",\"itemValue\":\"29.46725728245242\"},{\"itemName\":\"high\",\"itemValue\":\"710.1730218537282\"},{\"itemName\":\"fix\",\"itemValue\":4015},{\"itemName\":\"e\",\"itemValue\":\"302.7644742928626\"},{\"itemName\":\"n\",\"itemValue\":\"711.0632664506148\"},{\"itemName\":\"u\",\"itemValue\":\"-271.97856155098333\"},{\"itemName\":\"num\",\"itemValue\":7200},{\"itemName\":\"time\",\"itemValue\":\"2023-11-0818:00:00\"}]}";
        DevicesAlarm alarm = new DevicesAlarm();
        List<DevicesItem> list = new ArrayList<>();
        DevicesItem item = new DevicesItem();
        item.setItemName("alt");
        item.setItemValue("20.12646584");
        long time = new Date().getTime();
        String md5 = new MD5Utils().getMd5(String.valueOf(time));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date());
        list.add(item);
        alarm.setDevicesItemList(list);
        String demoTest = "{\"deviceCode\":\"s8\",\"devicesItemList\":[{\"guid\":\"c7653b298bec06eb78be3140b5c2ea9b\",\"itemName\":\"alt\",\"itemValue\":\"20.12646584\",\"msg_id\":\"2023-11-18 14:49:06\",\"raw_ts\":\"2023-11-18 14:49:06\",\"ts\":1700290146508,\"tslver_Id\":\"2023-11-18 14:49:06\"}]}";
        System.out.println("alarm:" + JSONObject.toJSONString(alarm));
        List<BigDecimal> maxList = new ArrayList<>();
        maxList.add(new BigDecimal("52"));
        maxList.add(new BigDecimal("40"));
        maxList.add(new BigDecimal("35"));
        List<BigDecimal> minList = new ArrayList<>();
        minList.add(new BigDecimal("30"));
        minList.add(new BigDecimal("26"));
        minList.add(new BigDecimal("10"));
        minList = minList.stream().sorted().distinct().collect(Collectors.toList());
        maxList = maxList.stream().sorted().distinct().collect(Collectors.toList());
        BigDecimal max = getMaxNumber(new BigDecimal("38"), maxList);
        System.out.println(max);
        BigDecimal min = getMinNumber(new BigDecimal("8"), minList);
        System.out.println(min);
    }
}

