cjl
2023-09-26 c0c80bebcc93e90834e06404d6056322e51b02dd
screen-api/src/main/java/com/moral/api/service/impl/CityAqiServiceImpl.java
@@ -1,18 +1,19 @@
package com.moral.api.service.impl;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.moral.api.config.properties.SpecialCitiesProperties;
import com.moral.api.dto.CityAqiDailyListDTO;
import com.moral.api.entity.*;
import com.moral.api.mapper.CityAqiMapper;
import com.moral.api.mapper.DeviceMapper;
import com.moral.api.mapper.ForecastMapper;
import com.moral.api.mapper.*;
import com.moral.api.pojo.dto.cityAQI.CityPollutionLevel;
import com.moral.api.pojo.dto.cityAQI.ConcentrationAndPercent;
import com.moral.api.pojo.form.aqi.AirQualityComparisonForm;
import com.moral.api.pojo.vo.cityAQI.AirQualityComparisonVO;
import com.moral.api.pojo.vo.cityAQI.CityAreaRangeVO;
import com.moral.api.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moral.constant.Constants;
@@ -25,11 +26,13 @@
import com.moral.util.MathUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
@@ -48,6 +51,8 @@
    @Autowired
    private CityAqiMapper cityAqiMapper;
    @Autowired
    private CityAqiDailyMapper cityAqiDailyMapper;
    @Autowired
    private ForecastMapper forecastMapper;
@@ -81,6 +86,12 @@
    @Autowired
    private HistoryHourlyService historyHourlyService;
    @Autowired
    SpecialCitiesProperties citiesProperties;
    @Autowired
    private SysAreaMapper sysAreaMapper;
    @Override
    public List<Map<String, Object>> measuredCompareForecastOfO3(Map<String, Object> params) {
@@ -138,6 +149,34 @@
        return result;
    }
    @Override
    public List<Map<String, Object>> measuredCompareForecastOfO3_8H(Map<String, Object> params) {
        String regionCode = params.get("regionCode").toString();
        String time = params.get("time").toString();
        Date endTime = DateUtils.getDate(time+" "+"23:00:00",DateUtils.yyyy_MM_dd_HH_mm_ss_EN);
        Date startDate = DateUtils.getDate(time+" "+"00:00:00",DateUtils.yyyy_MM_dd_HH_mm_ss_EN);
        Date startTime = DateUtils.addHours(startDate,-7);
        //预测数据
        QueryWrapper<Forecast> forecastQueryWrapper = new QueryWrapper<>();
        forecastQueryWrapper.select("time", "value")
                .eq("city_code", regionCode)
        .between("time",startTime,endTime)
                .orderByAsc("time");
        List<Map<String, Object>> forecastData = forecastMapper.selectMaps(forecastQueryWrapper);
        //实测数据
        QueryWrapper<CityAqi> cityAqiQueryWrapper = new QueryWrapper<>();
        cityAqiQueryWrapper.select("time", "value")
                .eq("city_code", regionCode)
                .between("time",startTime,endTime).orderByAsc("time");
        List<Map<String, Object>> measuredData = cityAqiMapper.selectMaps(cityAqiQueryWrapper);
        List<Map<String, Object>> result = getO3_8H(forecastData,0,time);
        result.addAll(getO3_8H(measuredData,1,time));
        return result;
    }
    @Override
    public Map<String, Object> queryCityAqiByRegionCode(Integer regionCode) {
        Map<String, Object> value = (Map<String, Object>) redisTemplate.opsForHash().get(RedisConstants.CITY_AQI, String.valueOf(regionCode));
@@ -170,7 +209,7 @@
    @Override
    public Map<String, Object> query24HoursAqiByRegionCode(Integer regionCode) {
        //查询最新一条数据,用于获取最新的时间
        QueryWrapper<CityAqi> lastDataWrapper = new QueryWrapper<>();
        /*QueryWrapper<CityAqi> lastDataWrapper = new QueryWrapper<>();
        lastDataWrapper.eq("city_code", regionCode);
        lastDataWrapper.orderByDesc("time");
        lastDataWrapper.last(true, "limit 1");
@@ -183,39 +222,33 @@
        //查询数据
        QueryWrapper<CityAqi> wrapper = new QueryWrapper<>();
        wrapper.between("time", startDate, endDate);
        wrapper.eq("city_code", regionCode);
        List<CityAqi> cityAqis = cityAqiMapper.selectList(wrapper);
        wrapper.eq("city_code", regionCode);*/
        List<CityAqi> cityAqis = cityAqiMapper.listCity(regionCode);
        //如果数据不足24小时则补全
        if (cityAqis.size() != 24) {
            Map<Date, CityAqi> dateCityAqiMap = new HashMap<>();
            cityAqis.forEach(value -> dateCityAqiMap.put(value.getTime(), value));
        if(CollectionUtils.isEmpty(cityAqis)){
            return new HashMap<>();
        }
        Date startDate = cityAqis.get(0).getTime();
        if(cityAqis.size()<24){
            for (int i = 0; i < 24; i++) {
                Date date = DateUtils.addHours(startDate, i);
                CityAqi cityAqi1 = dateCityAqiMap.get(date);
                if (cityAqi1 == null) {
                Date dateTime = DateUtils.addHours(startDate, i);
                if(cityAqis.size()-1 <i){
                    CityAqi newCityAqi = new CityAqi();
                    newCityAqi.setTime(date);
                    newCityAqi.setTime(dateTime);
                    newCityAqi.setValue("0");
                    cityAqis.add(newCityAqi);
                    continue;
                }
            }
            //按照时间进行排序
            cityAqis.sort(Comparator.comparing(CityAqi::getTime));
        }
            //按照时间进行排序
        cityAqis.sort(Comparator.comparing(CityAqi::getTime));
        //封装返回数据,map的key为yyyy-MM-dd HH:mm格式的时间,value为aqi的数值
        Map<String, Object> result = new LinkedHashMap<>();
        for (CityAqi aqi : cityAqis) {
            String key = DateUtils.dateToDateString(aqi.getTime(), "yyyy-MM-dd HH:mm");
            String allDataJson = aqi.getValue();
            if (allDataJson == null) {
                result.put(key, "");
                continue;
            }
            Map<String, Object> allDataMap = JSON.parseObject(allDataJson, Map.class);
            Object aqiData = allDataMap.get("AQI");
            if (aqiData == null)
                result.put(key, "");
            else
                result.put(key, aqiData);
            result.put(key,aqi.getValue());
        }
        return result;
    }
@@ -367,7 +400,7 @@
                }
            });
            //今日累计O3_8H计算,取每小时O3_8H最大值
            //今日累计O3_8H计算,取每小时O3——8H最大值
            if (!ObjectUtils.isEmpty(doubles)) {
                dataMap.put("O3_8H", Collections.max(doubles));
            }
@@ -629,7 +662,7 @@
    /**
     * @Description: 从数据库查询数据
     * @Param: [regionCode]
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     * @return: java.util.Map<java.lang.String                                                               ,                                                                                                                               java.lang.Object>
     * @Author: 陈凯裕
     * @Date: 2021/10/28
     */
@@ -654,13 +687,34 @@
        Date now = new Date();
        //昨日
        Date yesterday = DateUtils.dataToTimeStampTime(DateUtils.getDateOfDay(now, -1), DateUtils.yyyy_MM_dd_EN);
        String dateString = DateUtils.dateToDateString(yesterday, DateUtils.yyyy_MM_dd_HH_mm_ss_EN);
        String dateString = DateUtils.dateToDateString(yesterday, DateUtils.yyyy_MM_dd_EN);
        String s = String.valueOf(regionCode);
        //获取省,市code
        Integer provinceCode = Integer.parseInt(s.substring(0, 2) + "0000");
        Integer cityCode = Integer.parseInt(s.substring(0, 4) + "00");
        //获取省内所有city_code
        Map<String,Object> params = new HashMap<>();
        params.put("cityCode",provinceCode);
        params.put("start",dateString);
        params.put("end",dateString);
        params.put("type",1);
        List<CityAqiDailyListDTO> dayList = cityAqiDailyMapper.CityAqiDailyMap(params);
        String start = DateUtils.dateToDateString(DateUtils.addMonths(DateUtils.getFirstDayOfLastMonth(), 1));
        params.put("start",start);
        params.put("type",2);
        List<CityAqiDailyListDTO> monList = cityAqiDailyMapper.CityAqiDailyMap(params);
        start =DateUtils.dateToDateString(now, DateUtils.yyyy);
        params.put("start",start);
        params.put("end",start);
        params.put("type",3);
        List<CityAqiDailyListDTO> yearList = cityAqiDailyMapper.CityAqiDailyMap(params);
        int indexDay = dayList.stream().map(CityAqiDailyListDTO::getCityCode).collect(Collectors.toList()).indexOf(cityCode.toString());
        int indexMon = monList.stream().map(CityAqiDailyListDTO::getCityCode).collect(Collectors.toList()).indexOf(cityCode.toString());
        int indexYear = yearList.stream().map(CityAqiDailyListDTO::getCityCode).collect(Collectors.toList()).indexOf(cityCode.toString());
        result.put("day",mapResult(dayList,indexDay));
        result.put("month",mapResult(monList,indexMon));
        result.put("year",mapResult(yearList,indexYear));
       /* //获取省内所有city_code
        QueryWrapper<SysArea> wrapper = new QueryWrapper<>();
        wrapper.select("area_code").eq("parent_code", provinceCode);
        List<Object> cityCodes = sysAreaService.listObjs(wrapper);
@@ -748,11 +802,19 @@
            yearMap.put("size", null);
        }
        yearMap.put("compositeIndex", yearMap.remove("value"));
        result.put("year", yearMap);
        result.put("year", yearMap);*/
        //时间,昨日
        result.put("time", DateUtils.dateToDateString(yesterday, DateUtils.yyyy_MM_dd_EN));
        return result;
    }
    private Map<String,Object> mapResult(List<CityAqiDailyListDTO> list, int length){
        Map<String,Object> map = new HashMap<>();
        map.put("AQI",CollectionUtils.isNotEmpty(list)&&length>0&&Objects.nonNull(list.get(length-1))?list.get(length-1).getAqi():0);
        map.put("rank",CollectionUtils.isNotEmpty(list)&&length>0?length:0);
        map.put("size",CollectionUtils.isNotEmpty(list)&&length>0?list.size():0);
        return map;
    }
    @Override
@@ -1041,6 +1103,123 @@
        return result;
    }
    @Override
    public Map<String, Object> countyData(Integer regionCode) {
        Map<String,Object> resultMap = new HashMap<>();
        //获取时间
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH");
        Calendar calendar = Calendar.getInstance();
        int minute = calendar.get(Calendar.MINUTE);
        if (minute >= 45){
            calendar.set(Calendar.HOUR_OF_DAY,calendar.get(Calendar.HOUR_OF_DAY)-1);
        }else {
            calendar.set(Calendar.HOUR_OF_DAY,calendar.get(Calendar.HOUR_OF_DAY)-2);
        }
        String time = df.format(calendar.getTime())+":00:00";
        QueryWrapper<CityAqi> cityAqiQueryWrapper = new QueryWrapper<>();
        cityAqiQueryWrapper.likeRight("city_code",regionCode.toString().substring(0,4));
        cityAqiQueryWrapper.ne("city_code",regionCode);
        cityAqiQueryWrapper.eq("time",time);
        List<CityAqi> cityAqis = cityAqiMapper.selectList(cityAqiQueryWrapper);
        QueryWrapper<SysArea> sysAreaQueryWrapper = new QueryWrapper<>();
        sysAreaQueryWrapper.eq("parent_code",regionCode);
        List<SysArea> sysAreas = sysAreaMapper.selectList(sysAreaQueryWrapper);
        Map<Integer, Object> sysAreaMap = new HashMap<>();
        for (SysArea sysarea:sysAreas) {
            sysAreaMap.put(sysarea.getAreaCode(),sysarea.getAreaName());
        }
        List<Map<String,Object>> resultList = new ArrayList<>();
        for (CityAqi cityAqi:cityAqis) {
            if (!ObjectUtils.isEmpty(cityAqi.getValue())){
                Map<String, Object> cityAqiMap = new HashMap<>();
                String cityAqiValue = cityAqi.getValue();
                JSONObject jsonObject = JSONObject.parseObject(cityAqiValue);
                String AQI = "--";
                String PM10 = "--";
                String PM2_5 = "--";
                String SO2 = "--";
                String NO2 = "--";
                String CO = "--";
                String O3 = "--";
                String thirty = "--";
                String forty = "--";
                String fifty = "--";
                String city_name = "--";
                if (!ObjectUtils.isEmpty(jsonObject.get("AQI"))){
                    AQI = jsonObject.get("AQI").toString();
                    BigDecimal AQI_base = BigDecimal.valueOf(Double.parseDouble(AQI));
                    BigDecimal thirty_percent = BigDecimal.valueOf(1.3);
                    BigDecimal forty_percent = BigDecimal.valueOf(1.4);
                    BigDecimal fifty_percent = BigDecimal.valueOf(1.5);
                    Double AQI_thirty = AQI_base.multiply(thirty_percent).doubleValue();
                    Double AQI_forty = AQI_base.multiply(forty_percent).doubleValue();
                    Double AQI_fifty = AQI_base.multiply(fifty_percent).doubleValue();
                    thirty = String.valueOf(Math.round(AQI_thirty));
                    forty = String.valueOf(Math.round(AQI_forty));
                    fifty = String.valueOf(Math.round(AQI_fifty));
                }
                if (!ObjectUtils.isEmpty(jsonObject.get("PM10"))){
                    PM10 = String.valueOf(Math.round(Double.parseDouble(jsonObject.get("PM10").toString())));
                }
                if (!ObjectUtils.isEmpty(jsonObject.get("PM2_5"))){
                    PM2_5 = String.valueOf(Math.round(Double.parseDouble(jsonObject.get("PM2_5").toString())));
                }
                if (!ObjectUtils.isEmpty(jsonObject.get("SO2"))){
                    SO2 = String.valueOf(Math.round(Double.parseDouble(jsonObject.get("SO2").toString())));
                }
                if (!ObjectUtils.isEmpty(jsonObject.get("NO2"))){
                    NO2 = String.valueOf(Math.round(Double.parseDouble(jsonObject.get("NO2").toString())));
                }
                if (!ObjectUtils.isEmpty(jsonObject.get("CO"))){
                    CO = String.valueOf(Math.round(Double.parseDouble(jsonObject.get("CO").toString())));
                }
                if (!ObjectUtils.isEmpty(jsonObject.get("O3"))){
                    O3 = String.valueOf(Math.round(Double.parseDouble(jsonObject.get("O3").toString())));
                }
                if (!ObjectUtils.isEmpty(jsonObject.get("cityName"))){
                    city_name = jsonObject.get("cityName").toString();
                }
                cityAqiMap.put("AQI",AQI);
                cityAqiMap.put("PM10",PM10);
                cityAqiMap.put("PM2_5",PM2_5);
                cityAqiMap.put("SO2",SO2);
                cityAqiMap.put("NO2",NO2);
                cityAqiMap.put("CO",CO);
                cityAqiMap.put("O3",O3);
                cityAqiMap.put("thirty",thirty);
                cityAqiMap.put("forty",forty);
                cityAqiMap.put("fifty",fifty);
                cityAqiMap.put("city_name",city_name);
                resultList.add(cityAqiMap);
            }
            sysAreaMap.remove(cityAqi.getCityCode());
        }
        if (sysAreaMap.size()>0){
            for(Integer key:sysAreaMap.keySet()){
                Map<String,Object> nullMap = new HashMap<>();
                nullMap.put("AQI","--");
                nullMap.put("PM10","--");
                nullMap.put("PM2_5","--");
                nullMap.put("SO2","--");
                nullMap.put("NO2","--");
                nullMap.put("CO","--");
                nullMap.put("O3","--");
                nullMap.put("thirty","--");
                nullMap.put("forty","--");
                nullMap.put("fifty","--");
                nullMap.put("city_name",sysAreaMap.get(key));
                resultList.add(nullMap);
            }
        }
        resultMap.put("resultList",resultList);
        resultMap.put("time",time);
        QueryWrapper<SysArea> areaQueryWrapper = new QueryWrapper<>();
        areaQueryWrapper.eq("area_code",regionCode);
        SysArea sysArea = sysAreaMapper.selectOne(areaQueryWrapper);
        resultMap.put("areaName",sysArea.getAreaName());
        return resultMap;
    }
    /**
     * @Description: 计算6参和综合指数对比的百分比
     * @Param: [data, comparisonData]
@@ -1069,15 +1248,15 @@
     */
    private ConcentrationAndPercent contrastParam(Double data, Double comparisonData, String sensor) {
        double percentD = MathUtils.division(data - comparisonData, comparisonData, 4);
        String percent = MathUtils.mul(percentD, 100d) + "%";
        String percent = MathUtils.mul(percentD,100d) + "%";
        ConcentrationAndPercent concentrationAndPercent = new ConcentrationAndPercent();
        concentrationAndPercent.setPercent(percent);
        if (sensor.equals("CO")) {//CO小数点保留一位
            Double CO = AmendUtils.sciCal(data, 1);
            concentrationAndPercent.setConcentration(CO.toString());
        } else if (sensor.equals("compositeIndex")) {
        }else if (sensor.equals("compositeIndex")){
            concentrationAndPercent.setConcentration(data.toString());
        } else {
        }else{
            Double sensorD = AmendUtils.sciCal(data, 0);
            Integer sensorI = new Double(sensorD).intValue();
            concentrationAndPercent.setConcentration(sensorI.toString());
@@ -1103,7 +1282,7 @@
    /**
     * @Description: 根据时间类型查询对应的6参以及综合指数,自定义时间类型用日数据做均值处理
     * @Param: [comparisonType, startDate, endDate, regionCode]
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     * @return: java.util.Map<java.lang.String                                                               ,                                                               java.lang.Object>
     * @Author: 陈凯裕
     * @Date: 2022/1/17
     */
@@ -1187,8 +1366,7 @@
    private List<SysArea> getSysAreasByRegionType(String regionType, Integer regionCode) {
        List<SysArea> areas;
        if (regionType.equals(Constants.TWENTY_EIGHT_CITIES)) {
            SpecialCitiesProperties properties = new SpecialCitiesProperties();
            areas = properties.getTwentyEightCities();
            areas = citiesProperties.getTwentyEightCities();
        } else {
            areas = sysAreaService.getChildren(regionCode);
        }
@@ -1198,7 +1376,7 @@
    /**
     * @Description: 计算6参平均值
     * @Param: [cityAqiList]
     * @return: java.util.Map<java.lang.String, java.lang.Double>
     * @return: java.util.Map<java.lang.String                                                               ,                                                                                                                               java.lang.Double>
     * 返回值key为sensorCode,value为值
     * @Author: 陈凯裕
     * @Date: 2021/11/2
@@ -1261,4 +1439,40 @@
        }
        return s;
    }
    public  List<Map<String, Object>> getO3_8H(List<Map<String, Object>> data , int type,String day) {
        List<Map<String, Object>> list = new ArrayList<>();
        for(int i = 0 ;i<=23;i++){
            Map<String, Object> map = new HashMap<>();
            if(type == 0){
                map.put("type","预测");
            }else {
                map.put("type","实测");
            }
            String times = day+" "+i;
            Date endDate = DateUtils.getDate(times,DateUtils.yyyy_MM_dd_HH_EN);
            Date startDate = DateUtils.addHours(DateUtils.getDate(day+" "+i,DateUtils.yyyy_MM_dd_HH_EN),-7);
            List<Double> value = new ArrayList<>();
            for(Map<String, Object> m : data){
                Date time = (Date) m.get("time");
                if(DateUtils.isTimeBeforE(time,startDate) && DateUtils.isTimeBeforE(endDate,time)){
                    Map<String, Object> sensorValue = JSONObject.parseObject((String) m.get("value"), Map.class);
                    Double o3 = Double.parseDouble(sensorValue.get("O3").toString());
                    value.add(o3);
                }
            }
            if (value.size() < 6) {
                continue;
            }
            double average = value.stream().mapToDouble(aDouble -> aDouble).summaryStatistics().getAverage();
            map.put("O3", new BigDecimal(average).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue());
            map.put("time",times);
            list.add(map);
        }
        return list;
    }
}