package com.zcxk.service;

import com.zcxk.dto.*;
import com.zcxk.entity.*;
import com.zcxk.service.impl.MonitorDataReportServiceImpl;
import com.zcxk.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SecSupplyService {
    @Autowired
    private SceneService sceneService;
    @Autowired
    private MonthReportService monthReportService;
    @Autowired
    private DeviceParmService deviceParmService;
    @Autowired
    private MonitorDataReportServiceImpl monitorDataReportServiceImpl;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private  DayReportService dayReportService;
    @Autowired
    private  YearReportService yearReportService;
    /**
     * 查询30天供水量
     * @param sceneEntity
     * @return
     */
    public List<AmountDayThirtyDto> getAmountDayThirty(SceneEntity sceneEntity) {
        List<SceneEntity> sceneEntities = sceneService.selectByTypeName(sceneEntity);
        if (sceneEntities.size() == 0) {
            return null;
        }
        MonthReportEntity monthReportEntity = new MonthReportEntity();
        monthReportEntity.setParentSceneLists(sceneEntities);
        List<MonthReportEntity> monthReportEntities = monthReportService.findAmountBySceneIds(monthReportEntity);
        Map<String, Double> maps = new LinkedHashMap<>();
        for (MonthReportEntity item : monthReportEntities) {
            maps.put(item.getYear() + "-" + String.format("%02d", item.getMonth()) + "-" + String.format("%02d", item.getDay()), item.getSumValue());
        }
        Calendar begin = Calendar.getInstance();// 得到一个Calendar的实例
        begin.setTime(new Date()); // 设置时间为当前时间
        List<AmountDayThirtyDto> listC = new ArrayList<>();
        for (int i = 1; i <= 15; i++) {
            begin.add(Calendar.DATE, -1);// 日期加1
            Date d = new Date(begin.getTimeInMillis());
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            AmountDayThirtyDto amountDayThirtyDto = new AmountDayThirtyDto();
            if (maps.containsKey(df.format(d).toString())) {
                amountDayThirtyDto.setAmountTime(d);
                if (maps.get(df.format(d)) != null) {
                    amountDayThirtyDto.setAmount((double) Math.round(maps.get(df.format(d)) * 1000) / 1000);
                }
            } else {
                amountDayThirtyDto.setAmountTime(d);
                amountDayThirtyDto.setAmount(0d);
            }
            listC.add(amountDayThirtyDto);
        }

        return listC;
    }

    /**
     * 查询供水及瞬时流量
     * @param sceneEntity
     * @return
     */
    public AmountTotalDto findAmountTotalByTypeName(SceneEntity sceneEntity) {
        BigDecimal multipleData;
        if("泵站".equals(sceneEntity.getSceneTypeName())){
            multipleData = new BigDecimal("1");
        }else{
            multipleData = new BigDecimal("10000");
        }
        AmountTotalDto amountTotalDto = new AmountTotalDto();
        BigDecimal  instantFlow = monitorDataReportServiceImpl.getAmountCount(null,null,sceneEntity.getSceneTypeName(),14,1);
        BigDecimal  dayAmount = monitorDataReportServiceImpl.getAmountCount(null,null,sceneEntity.getSceneTypeName(),3,1);
        BigDecimal  monthAmount = monitorDataReportServiceImpl.getAmountCount(null,null,sceneEntity.getSceneTypeName(),3,2);
        BigDecimal  yearAmount = monitorDataReportServiceImpl.getAmountCount(null,null,sceneEntity.getSceneTypeName(),3,3);
        amountTotalDto.setInstantFlow(instantFlow.setScale(3,BigDecimal.ROUND_HALF_UP).doubleValue());
        amountTotalDto.setDayAmount(dayAmount.divide(multipleData,3,BigDecimal.ROUND_HALF_UP).doubleValue());
        amountTotalDto.setMonthAmount(monthAmount.divide(multipleData,3,BigDecimal.ROUND_HALF_UP).doubleValue());
        amountTotalDto.setYearAmount(yearAmount.divide(multipleData,3,BigDecimal.ROUND_HALF_UP).doubleValue());

        /*List<SceneEntity> sceneEntities = sceneService.selectByTypeName(sceneEntity);
        if (sceneEntities.size() == 0)
            return null;
        Calendar begin = Calendar.getInstance();// 得到一个Calendar的实例
        begin.setTime(new Date()); // 设置时间为当前时间
        begin.add(Calendar.DATE, -1);// 日期加1
        //查询所有的关联设备及测点信息
        DeviceParmEntity deviceParmEntity = new DeviceParmEntity();
        deviceParmEntity.setSceneEntities(sceneEntities);
        deviceParmEntity.setParmType(14);//查询瞬时流量
        List<DeviceParmEntity> deviceParmEntities = deviceParmService.selectDeviceBySceneIdAndType(deviceParmEntity);
        //瞬时流量
        double instantFlow = 0d;
        for (DeviceParmEntity item : deviceParmEntities) {
            //取缓存里的数据
            byte[] bytes = redisUtil.get(("sms_water_" + item.getDeviceCode()).getBytes());
            if (bytes != null && bytes.length > 0) {
                MonitorDataEntity monitorDataEntity = (MonitorDataEntity) ByteArrayUtils.bytesToObject(bytes).get();
                //筛选该设备相同属性的值
                Map<Long, MonitorDataValueEntity> map = new HashMap<>();
                //将缓存中的实时数据放到map中方便进行遍历
                for (MonitorDataValueEntity dateValue : monitorDataEntity.getDataValues()) {
                    map.put(dateValue.getAttributeId(), dateValue);
                }
                if (map.containsKey(item.getAttributeId().longValue()))
                    instantFlow += map.get(item.getAttributeId().longValue()).getDataValue();
            }
        }
        amountTotalDto.setInstantFlow((double) Math.round(instantFlow * 1000) / 1000);
        //本日供水量
        deviceParmEntity.setParmType(3);//查询供水量
        List<DeviceParmEntity> deviceParms = deviceParmService.selectDeviceBySceneIdAndType(deviceParmEntity);
        double dayAmount = 0d;
        for (DeviceParmEntity item : deviceParms) {
            //取缓存里的数据
            byte[] bytes = redisUtil.get(("sms_water_" + item.getDeviceCode()).getBytes());
            if (bytes != null && bytes.length > 0) {
                MonitorDataEntity monitorDataEntity = (MonitorDataEntity) ByteArrayUtils.bytesToObject(bytes).get();
                //筛选该设备相同属性的值
                Map<Long, MonitorDataValueEntity> map = new HashMap<>();
                //将缓存中的实时数据放到map中方便进行遍历
                for (MonitorDataValueEntity dateValue : monitorDataEntity.getDataValues()) {
                    map.put(dateValue.getAttributeId(), dateValue);
                }
                if (map.containsKey(item.getAttributeId().longValue())) {

                    DayReportEntity dayReportEntity = new DayReportEntity();
                    dayReportEntity.setYear(begin.get(Calendar.YEAR));
                    dayReportEntity.setMonth(begin.get(Calendar.MONTH) + 1);
                    dayReportEntity.setDay(begin.get(Calendar.DAY_OF_MONTH));
                    dayReportEntity.setDeviceId(item.getDeviceId().longValue());
                    dayReportEntity.setAttributeId(item.getAttributeId().longValue());
                    List<DayReportEntity> dayReportEntities = dayReportService.findDeviceLastDayValue(dayReportEntity);
                    if (dayReportEntities.size() > 0) {
                        dayAmount += map.get(item.getAttributeId().longValue()).getDataValue();
                        System.out.println("item.getAttributeId()"+item.getAttributeId()+"--"+map.get(item.getAttributeId().longValue()));
                        dayAmount = dayAmount - dayReportEntities.get(0).getLatestValue();
                    }
                }
            }
        }
        amountTotalDto.setDayAmount(BigDecimal.valueOf(dayAmount).divide(multipleData,3,BigDecimal.ROUND_HALF_UP).doubleValue());
        //本月供水量
        double monthAmount = 0d;
        begin.add(Calendar.DATE, 1);// 恢复到当前日期
        MonthReportEntity monthReportEntity = new MonthReportEntity();
        monthReportEntity.setYear(begin.get(Calendar.YEAR));
        monthReportEntity.setMonth(begin.get(Calendar.MONTH) + 1);
        monthReportEntity.setParentSceneLists(sceneEntities);
        List<MonthReportEntity> monthReportNew = monthReportService.findAmountTotalBySceneIds(monthReportEntity);
        begin.add(Calendar.MONTH, -1);// 恢复到当前日期
        MonthReportEntity monthReportLast = new MonthReportEntity();
        monthReportLast.setYear(begin.get(Calendar.YEAR));
        monthReportLast.setMonth(begin.get(Calendar.MONTH) + 1);
        monthReportLast.setParentSceneLists(sceneEntities);
        List<MonthReportEntity> monthReportsLast = monthReportService.findAmountTotalBySceneIds(monthReportLast);
        if (monthReportNew.size() > 0 && monthReportsLast.size() > 0 && monthReportNew.get(0) != null && monthReportsLast.get(0) != null) {
            monthAmount = monthReportNew.get(0).getLatestValue() - monthReportsLast.get(0).getLatestValue() + dayAmount;
        } else if (monthReportNew.size() > 0 && monthReportNew.get(0) != null) {
            monthAmount = monthReportNew.get(0).getLatestValue() + dayAmount;
        } else {
            monthAmount = dayAmount;
        }
        amountTotalDto.setMonthAmount(BigDecimal.valueOf(monthAmount).divide(multipleData,3,BigDecimal.ROUND_HALF_UP).doubleValue());
        //本年供水量
        double yearAmount = 0d;
        begin.add(Calendar.MONTH, 1);// 恢复到当前日期
        YearReportEntity yearReportEntity = new YearReportEntity();
        yearReportEntity.setYear(begin.get(Calendar.YEAR));
        yearReportEntity.setParentSceneLists(sceneEntities);
        List<YearReportEntity> yearReportsNew = yearReportService.findAmountTotalBySceneIds(yearReportEntity);
        yearReportEntity.setYear(begin.get(Calendar.YEAR) - 1);
        List<YearReportEntity> yearReportsLast = yearReportService.findAmountTotalBySceneIds(yearReportEntity);
        if (yearReportsNew.size() > 0 && yearReportsLast.size() > 0 && yearReportsNew.get(0) != null && yearReportsLast.get(0) != null) {
            yearAmount = yearReportsNew.get(0).getLatestValue() - yearReportsLast.get(0).getLatestValue() + monthAmount;
        } else if (yearReportsNew.size() > 0 && yearReportsNew.get(0) != null) {
            yearAmount = yearReportsNew.get(0).getLatestValue() + monthAmount;
        } else {
            yearAmount = monthAmount;
        }
        amountTotalDto.setYearAmount(BigDecimal.valueOf(yearAmount).divide(multipleData,3,BigDecimal.ROUND_HALF_UP).doubleValue());
       */
        return amountTotalDto;
    }

    public WaterPieDto selectWaterQualityByTypeName(SceneEntity sceneEntity) {
        List<SceneEntity> sceneEntities = sceneService.selectByTypeName(sceneEntity);
        if (sceneEntities.size() == 0) {
            return null;
        }
        WaterPieDto waterPieDto = new WaterPieDto();
        DeviceParmEntity deviceParmEntity = new DeviceParmEntity();
        deviceParmEntity.setSceneEntities(sceneEntities);


        List<ParmTypeCountDto> listTotal = deviceParmService.findAlarmTotalCount(deviceParmEntity);

        List<ParmTypeCountDto> listAlarmTotal =deviceParmService.findAlarmCountTotalCount(deviceParmEntity);

        WaterPieStateDto waterPieStateDto4 = new WaterPieStateDto();
        waterPieStateDto4.setNormalCount(listTotal.get(0).getTotalCount()- listAlarmTotal.get(0).getNbnormalCount());
        waterPieStateDto4.setNbnormalCount(listAlarmTotal.get(0).getNbnormalCount());
        waterPieStateDto4.setPercentage((double) (Math.round((Double.valueOf(listTotal.get(0).getTotalCount()- listAlarmTotal.get(0).getNbnormalCount())/Double.valueOf(listTotal.get(0).getTotalCount()))*100)));
        waterPieDto.setWaterQuality(waterPieStateDto4);



        List<ParmTypeCountDto> list = deviceParmService.findAlarmCount(deviceParmEntity);
        //余氯11 浊度9  PH8  cod 15   15,8,9,11,18,19
        for(ParmTypeCountDto item : list)
        {
            switch(item.getParmType())
            {
                case 8:
                    WaterPieStateDto waterPieStateDto1 = new WaterPieStateDto();
                    waterPieStateDto1.setNormalCount(listTotal.get(0).getTotalCount()- item.getNbnormalCount());
                    waterPieStateDto1.setNbnormalCount(item.getNbnormalCount());
                    DecimalFormat df1 = new DecimalFormat("#.00");
                    waterPieStateDto1.setPercentage((double) (Math.round((Double.valueOf(listTotal.get(0).getTotalCount()- item.getNbnormalCount())/Double.valueOf(listTotal.get(0).getTotalCount()))*100)));
                    waterPieDto.setPh(waterPieStateDto1);
                    break;
                case 10:
                    WaterPieStateDto waterPieStateDto2 = new WaterPieStateDto();
                    waterPieStateDto2.setNormalCount(listTotal.get(0).getTotalCount()- item.getNbnormalCount());
                    waterPieStateDto2.setNbnormalCount(item.getNbnormalCount());
                    DecimalFormat df2 = new DecimalFormat("#.00");
                    waterPieStateDto2.setPercentage((double) (Math.round((Double.valueOf(listTotal.get(0).getTotalCount()- item.getNbnormalCount())/Double.valueOf(listTotal.get(0).getTotalCount()))*100)));
                    waterPieDto.setTurbidity(waterPieStateDto2);
                    break;
                case 11:
                    WaterPieStateDto waterPieStateDto3 = new WaterPieStateDto();
                    waterPieStateDto3.setNormalCount(listTotal.get(0).getTotalCount()- item.getNbnormalCount());
                    waterPieStateDto3.setNbnormalCount(item.getNbnormalCount());
                    waterPieStateDto3.setPercentage((double) (Math.round((Double.valueOf(listTotal.get(0).getTotalCount()- item.getNbnormalCount())/Double.valueOf(listTotal.get(0).getTotalCount()))*100)));
                    waterPieDto.setResidualChlorine(waterPieStateDto3);
                    break;
            }
        }

        if(waterPieDto.getPh()==null)
        {
            WaterPieStateDto waterPieStateDto1 = new WaterPieStateDto();
            waterPieStateDto1.setNormalCount(listTotal.get(0).getTotalCount());
            waterPieStateDto1.setNbnormalCount(0);
            DecimalFormat df1 = new DecimalFormat("#.00");
            waterPieStateDto1.setPercentage((double) (Math.round((Double.valueOf(listTotal.get(0).getTotalCount())/Double.valueOf(listTotal.get(0).getTotalCount()))*100)));
            waterPieDto.setPh(waterPieStateDto1);
        }
        if(waterPieDto.getTurbidity()==null)
        {
            WaterPieStateDto waterPieStateDto2 = new WaterPieStateDto();
            waterPieStateDto2.setNormalCount(listTotal.get(0).getTotalCount());
            waterPieStateDto2.setNbnormalCount(0);
            DecimalFormat df2 = new DecimalFormat("#.00");
            waterPieStateDto2.setPercentage((double) (Math.round((Double.valueOf(listTotal.get(0).getTotalCount())/Double.valueOf(listTotal.get(0).getTotalCount()))*100)));
            waterPieDto.setTurbidity(waterPieStateDto2);
        }
        if(waterPieDto.getResidualChlorine()==null)
        {
            WaterPieStateDto waterPieStateDto3 = new WaterPieStateDto();
            waterPieStateDto3.setNormalCount(listTotal.get(0).getTotalCount());
            waterPieStateDto3.setNbnormalCount(0);
            waterPieStateDto3.setPercentage((double) (Math.round((Double.valueOf(listTotal.get(0).getTotalCount())/Double.valueOf(listTotal.get(0).getTotalCount()))*100)));
            waterPieDto.setResidualChlorine(waterPieStateDto3);
        }
        return waterPieDto;
    }
}
