package jnpf.attendance.schedule;

import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * 相似历史日模板拆成的「自然日 + 半小时槽 + 岗位 + 人数」一行，对应需求侧表结构。
 * <p>
 * 岗位展示默认使用 {@link #getPostId()}；名称需业务侧用岗位字典解析。
 */
public final class SimilarHistoricalJobSlotRow implements Serializable {

    private static final DateTimeFormatter HM = DateTimeFormatter.ofPattern("HH:mm");

    private final LocalDate rowDate;
    private final LocalTime slotStartInclusive;
    private final LocalTime slotEndExclusive;
    private final String postId;
    private final int headcount;
    private final String shiftId;
    /** 排班区间内的「模板日」：本行由该排班日对应的相似历史日展开得到，用于第四步按日聚合。 */
    private final LocalDate templateScheduleDay;

    public SimilarHistoricalJobSlotRow(
            LocalDate rowDate,
            LocalTime slotStartInclusive,
            LocalTime slotEndExclusive,
            String postId,
            int headcount,
            String shiftId,
            LocalDate templateScheduleDay) {
        this.rowDate = Objects.requireNonNull(rowDate, "rowDate");
        this.slotStartInclusive = Objects.requireNonNull(slotStartInclusive, "slotStartInclusive");
        this.slotEndExclusive = Objects.requireNonNull(slotEndExclusive, "slotEndExclusive");
        this.postId = postId == null ? "" : postId;
        this.headcount = Math.max(0, headcount);
        this.shiftId = shiftId == null ? "" : shiftId;
        this.templateScheduleDay = Objects.requireNonNull(templateScheduleDay, "templateScheduleDay");
    }

    public LocalDate getRowDate() {
        return rowDate;
    }

    public LocalTime getSlotStartInclusive() {
        return slotStartInclusive;
    }

    public LocalTime getSlotEndExclusive() {
        return slotEndExclusive;
    }

    public String getPostId() {
        return postId;
    }

    public int getHeadcount() {
        return headcount;
    }

    public String getShiftId() {
        return shiftId;
    }

    public LocalDate getTemplateScheduleDay() {
        return templateScheduleDay;
    }

    /** 与文档表头「时间段」一致，如 {@code 09:00-09:30}（左闭右开半小时）；尾段跨午夜时显示为 {@code 23:30-00:00}。 */
    public String getSlotRangeLabel() {
        if (slotEndExclusive.equals(LocalTime.MIDNIGHT) && slotStartInclusive.isAfter(LocalTime.MIDNIGHT)) {
            return slotStartInclusive.format(HM) + "-00:00";
        }
        return slotStartInclusive.format(HM) + "-" + slotEndExclusive.format(HM);
    }

    @Override
    public String toString() {
        return rowDate
                + "\t"
                + getSlotRangeLabel()
                + "\t"
                + postId
                + "\t"
                + headcount
                + "\t"
                + templateScheduleDay;
    }
}
