package com.cpp.web.service.electricityRestriction.impl;

import com.cpp.web.domain.station.ElectricField;
import com.cpp.web.domain.station.PowerStationStatusData;
import com.cpp.web.service.electricityRestriction.ElectricityRestrictionService;
import com.cpp.web.service.station.ElectricFieldService;
import com.cpp.web.service.station.PowerStationStatusDataService;
import com.cpp.web.utils.DateTimeUtil;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
@RequiredArgsConstructor
public class ElectricityRestrictionServiceImpl implements ElectricityRestrictionService {

    private final PowerStationStatusDataService powerStationStatusDataService;

    private final ElectricFieldService electricFieldService;

    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    private final static SimpleDateFormat formatDate = new SimpleDateFormat("HH:mm");

    @Override
    public List getElectricityRestriction(Date startTime, Date endTime, String stationCode) {
        List<ElectricField> electricFieldList;
        List<ElectricityRestrictionDto> list = new ArrayList<>();
        List<PowerStationStatusData> powerStationStatusDataList = powerStationStatusDataService.findByTimeBetweenAndStationCode(startTime, endTime, stationCode);

        if (null == stationCode) {
            electricFieldList = electricFieldService.list();
            for (ElectricField electricField : electricFieldList) {
                List<PowerStationStatusData> collectList = powerStationStatusDataList.stream().filter(f -> f.getPowerRationing() == 1 && f.getStationCode().equals(electricField.getStationCode())).collect(Collectors.toList());
                list.addAll(get(collectList, startTime, endTime, electricField.getStationCode()));
            }
        } else {
            powerStationStatusDataList = powerStationStatusDataList.stream().filter(f -> f.getPowerRationing() == 1).collect(Collectors.toList());
            list = get(powerStationStatusDataList, startTime, endTime, stationCode);
        }
        return list;
    }

    /**
     * 获取相关所需
     *
     * @param powerStationStatusDataList
     * @param startTime
     * @param endTime
     * @param stationCode
     * @return
     */
    public List<ElectricityRestrictionDto> get(List<PowerStationStatusData> powerStationStatusDataList, Date startTime, Date endTime, String stationCode) {
        List<ElectricityRestrictionDto> list = new ArrayList<>();
        if (null != powerStationStatusDataList && powerStationStatusDataList.size() > 0) {
            List<String> dayList = DateTimeUtil.getDatesInRange(startTime, endTime);
            for (String s : dayList) {
                List<PowerStationStatusData> collectList = powerStationStatusDataList.stream().filter(f -> dateFormat.format(f.getTime()).equals(s)).collect(Collectors.toList());
                if (collectList.size() > 0) {
                    ElectricityRestrictionDto electricityRestrictionDto = new ElectricityRestrictionDto();
                    // 总限电量
                    BigDecimal totalPowerLimit = collectList.stream().map(PowerStationStatusData::getBlockedCapacity).reduce(BigDecimal.ZERO, BigDecimal::add).divide(new BigDecimal(12), 2, RoundingMode.HALF_UP);
                    electricityRestrictionDto.setTime(s);
                    electricityRestrictionDto.setTotalPowerLimit(totalPowerLimit.divide(new BigDecimal(12), 2, RoundingMode.HALF_UP));
                    // 限电时长
                    electricityRestrictionDto.setDuration(new BigDecimal(collectList.size()).divide(new BigDecimal(12), 2, RoundingMode.HALF_UP).doubleValue());
                    electricityRestrictionDto.setTimeSlot(mergeTime(collectList));
                    electricityRestrictionDto.setStationCode(stationCode);
                    list.add(electricityRestrictionDto);
                }
            }
        }
        return list;
    }


    /**
     * 合并时间段
     *
     * @param list
     * @return
     */
    public String mergeTime(List<PowerStationStatusData> list) {
        // 检查并拼接连续的日期
        StringBuilder result = new StringBuilder();
        Date prevDate = null;
        for (int i = 0; i < list.size(); i++) {
            Date finalTime = list.get(i).getTime();
            if (null == prevDate) {
                prevDate = finalTime;
                result.append(formatDate.format(finalTime) + "~");
            } else {
                if (DateTimeUtil.isMinutesDifference(finalTime, prevDate, 5L)) {
                    prevDate = finalTime;
                    if (i == list.size() - 1) {
                        result.append(formatDate.format(finalTime) + ";");
                    }
                } else if (i == list.size() - 1) {
                    result.append(formatDate.format(list.get(i - 1).getTime()) + ";").append(formatDate.format(finalTime) + "~").append(formatDate.format(finalTime) + ";");
                    prevDate = finalTime;
                } else {
                    result.append(formatDate.format(list.get(i - 1).getTime()) + ";").append(formatDate.format(finalTime) + "~");
                    prevDate = finalTime;
                }
            }
        }
        return result.toString();
    }


    @Data
    public class ElectricityRestrictionDto {
        // 日期
        private String time;
        // 时间段
        private String timeSlot;
        // 限电时长
        private Double duration;
        // 总限电量
        private BigDecimal totalPowerLimit;
        // 场站编号
        private String stationCode;
    }
}
