package com.usky.ai.dto;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

@Data
@NoArgsConstructor
public class AlgScheduleCreateRequestDTO {
    @JsonProperty("BoardId")
    private String boardId;

    @JsonProperty("Event")
    private String event = "/alg_schedule_create";

    @JsonProperty("name")
    private String name;

    @JsonProperty("summary")
    private String summary;

    @JsonProperty("timePeriods")
    private List<TimePeriod> timePeriods;

    @JsonProperty("value")
    private String value;

    public void convertTimePeriodsToBinary() {
        StringBuilder binaryValue = new StringBuilder();
        for (int i = 0; i < 336; i++) {
            binaryValue.append("0");
        }

        for (TimePeriod period : timePeriods) {
            processTimePeriod(binaryValue, period);
        }

        this.value = binaryValue.toString();
    }

    private void processTimePeriod(StringBuilder binaryValue, TimePeriod period) {
        // 将 dayOfWeek 转换为从 0 开始的索引
        int startDay = period.getDayOfWeek() - 1;
        int endDay = startDay; // 默认结束天数与开始天数相同
        if (period.getToDayOfWeek() != null) {
            endDay = period.getToDayOfWeek() - 1; // 如果有结束天数，也转换为从 0 开始的索引
        }

        // 计算开始和结束时间的分钟数
        int startMinutes = Integer.parseInt(period.getStartTime().substring(0, 2)) * 60 + Integer.parseInt(period.getStartTime().substring(3));
        int endMinutes = Integer.parseInt(period.getEndTime().substring(0, 2)) * 60 + Integer.parseInt(period.getEndTime().substring(3));

        // 计算开始和结束时间的索引
        int startIdx = (startDay * 48) + (startMinutes / 30);
        int endIdx = (endDay * 48) + (endMinutes / 30);

        // 填充时间段
        for (int i = startIdx; i < endIdx; i++) {
            binaryValue.setCharAt(i, '1');
        }
    }

    @Data
    @NoArgsConstructor
    public static class TimePeriod {
        @JsonProperty("dayOfWeek")
        private int dayOfWeek; // 0-6 表示周日到周六

        @JsonProperty("toDayOfWeek")
        private Integer toDayOfWeek; // 可选，表示连续的结束星期几

        @JsonProperty("startTime")
        private String startTime; // 格式为 "HH:mm"

        @JsonProperty("endTime")
        private String endTime; // 格式为 "HH:mm"
    }
}