package com.aps.macroplanner.util;

import com.aps.macroplanner.data.Period;

/**
 * 安全库存天数折算结果 — 单个周期项。
 *
 * <p>每次安全库存天数折算会在一个或多个未来周期上产生折算项。
 * 每个项包含: 周期信息、折算比例、对应的 DemandFulfillment 变量 key。</p>
 *
 * <h3>示例</h3>
 * 安全库存天数 = 10, 每周期 = 7 天, 当前周期 = P0:
 * <pre>
 *   P1: ratio=1.0   (7/7, 全覆盖, remainingBefore=10, remainingAfter=3)
 *   P2: ratio=0.43  (3/7, 部分覆盖, remainingBefore=3,  remainingAfter=0)
 * </pre>
 */
public class SafetyStockTerm {
    /** 周期索引 */
    private final int periodIndex;
    /** 周期名称 */
    private final String periodName;
    /** 周期长度 (天) */
    private final double periodDuration;
    /** 折算比例: 该周期贡献了多少天到安全库存中 */
    private final double ratio;
    /** 折算前剩余天数 */
    private final double remainingDaysBefore;
    /** 折算后剩余天数 */
    private final double remainingDaysAfter;
    /** DemandFulfillment 变量 key (productId_spId_periodIndex) */
    private final String demandFulfillmentKey;

    public SafetyStockTerm(Period period, double ratio,
                           double remainingDaysBefore, double remainingDaysAfter,
                           String demandFulfillmentKey) {
        this.periodIndex = period.getIndex();
        this.periodName = period.getName();
        this.periodDuration = period.getDurationInDays();
        this.ratio = ratio;
        this.remainingDaysBefore = remainingDaysBefore;
        this.remainingDaysAfter = remainingDaysAfter;
        this.demandFulfillmentKey = demandFulfillmentKey;
    }

    public int getPeriodIndex() { return periodIndex; }
    public String getPeriodName() { return periodName; }
    public double getPeriodDuration() { return periodDuration; }
    public double getRatio() { return ratio; }
    public double getRemainingDaysBefore() { return remainingDaysBefore; }
    public double getRemainingDaysAfter() { return remainingDaysAfter; }
    public String getDemandFulfillmentKey() { return demandFulfillmentKey; }

    /**
     * 该周期对安全库存天数的实际贡献天数。
     */
    public double getContributionDays() {
        return ratio * periodDuration;
    }

    @Override
    public String toString() {
        String coverage = (ratio >= 0.999) ? "全覆盖" : String.format("部分(%.1f%%)", ratio * 100);
        return String.format("  %s: 剩余 %5.1f天 → 消耗 %5.1f天/%s 周期(%s) → 剩余 %5.1f天",
                periodName, remainingDaysBefore, getContributionDays(), coverage,
                (ratio >= 0.999) ? "1.00" : String.format("%.2f", ratio),
                remainingDaysAfter);
    }
}