package com.moral.service.impl; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.alibaba.druid.support.json.JSONUtils; import com.moral.mapper.AlarmMapper; import com.moral.service.AlarmService; @Service public class AlarmServiceImpl implements AlarmService { @Resource private AlarmMapper alarmMapper; @Override public int insertAlarmDaily() { LocalDateTime time = LocalDateTime.now(); LocalDateTime endTime = time.truncatedTo(ChronoUnit.DAYS); LocalDateTime startTime = endTime.minusDays(1); String year = startTime.getYear() + ""; String month = null; int monthValue = startTime.getMonthValue(); if (monthValue < 10) { month = "0" + monthValue; } else { month = monthValue + ""; } String yearAndMonth = year + month; Map devices = new HashMap<>(); devices.put("start", startTime); devices.put("end", endTime); devices.put("yearAndMonth", yearAndMonth); List macs = alarmMapper.getMacs(devices); int count = 0; for (String mac : macs) { List> resultList = new ArrayList<>(); devices.put("mac", mac); List> list = alarmMapper.getAlarmData(devices); List> newList = list.stream().distinct().collect(Collectors.toList()); for (Map map : newList) { for (String key : map.keySet()) { String[] strings = map.get(key).toString().replace("$.", "") .replace("[", "").replace("]", "") .replace("\"", "").replace(" ", "").split(","); List sensors = new ArrayList(Arrays.asList(strings)); map.put(key, sensors); } } Map hashMap = new HashMap<>(); Set stateSet1 = new HashSet<>(); Set stateSet2 = new HashSet<>(); Set stateSet3 = new HashSet<>(); for (Map map : newList) { if (map.get("1") != null) { stateSet1.addAll((ArrayList) map.get("1")); hashMap.put("1", stateSet1); } if (map.get("2") != null) { stateSet2.addAll((ArrayList) map.get("2")); hashMap.put("2", stateSet2); } if (map.get("3") != null) { stateSet3.addAll((ArrayList) map.get("3")); hashMap.put("3", stateSet3); } } for (String key : hashMap.keySet()) { Map jsonMap = new HashMap<>(); Map map = new HashMap<>(); map.put("mac", mac); map.put("time", startTime); map.put("state", key); Set sensors = (Set) hashMap.get(key); for (String sensor : sensors) { jsonMap.put(sensor, 1); } map.put("json", JSONUtils.toJSONString(jsonMap)); resultList.add(map); } count = count + alarmMapper.insertAlarmDaily(resultList); } return count; } @Override public void createTable(String yearAndMonth) { alarmMapper.createTable(yearAndMonth); } }