package com.njcn.gather.steady.checksquare.component;

import com.njcn.gather.steady.checksquare.pojo.vo.SteadyChecksquareSegmentVO;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 数据校验连续性计算组件。
 */
@Component
public class SteadyChecksquareCalculator {

    public static final String STATUS_NORMAL = "NORMAL";
    public static final String STATUS_MISSING = "MISSING";
    private static final DateTimeFormatter OUTPUT_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public List<SteadyChecksquareSegmentVO> buildSegments(List<LocalDateTime> slots, Set<LocalDateTime> actualSlots,
                                                          int intervalMinutes) {
        List<SteadyChecksquareSegmentVO> result = new ArrayList<SteadyChecksquareSegmentVO>();
        if (slots == null || slots.isEmpty()) {
            return result;
        }
        String currentStatus = resolveStatus(slots.get(0), actualSlots);
        LocalDateTime segmentStart = slots.get(0);
        LocalDateTime previousSlot = slots.get(0);
        int pointCount = 1;
        for (int i = 1; i < slots.size(); i++) {
            LocalDateTime slot = slots.get(i);
            String status = resolveStatus(slot, actualSlots);
            if (!currentStatus.equals(status)) {
                result.add(buildSegment(segmentStart, previousSlot, currentStatus, pointCount, intervalMinutes));
                segmentStart = slot;
                pointCount = 0;
                currentStatus = status;
            }
            previousSlot = slot;
            pointCount++;
        }
        result.add(buildSegment(segmentStart, previousSlot, currentStatus, pointCount, intervalMinutes));
        return result;
    }

    private SteadyChecksquareSegmentVO buildSegment(LocalDateTime startTime, LocalDateTime endTime, String status,
                                                   int pointCount, int intervalMinutes) {
        SteadyChecksquareSegmentVO segment = new SteadyChecksquareSegmentVO();
        segment.setStartTime(OUTPUT_TIME_FORMATTER.format(startTime));
        segment.setEndTime(OUTPUT_TIME_FORMATTER.format(endTime));
        segment.setStatus(status);
        segment.setMissingPointCount(STATUS_MISSING.equals(status) ? pointCount : 0);
        segment.setDurationMinutes(pointCount * intervalMinutes);
        return segment;
    }

    private String resolveStatus(LocalDateTime slot, Set<LocalDateTime> actualSlots) {
        return actualSlots != null && actualSlots.contains(slot) ? STATUS_NORMAL : STATUS_MISSING;
    }
}
