package com.fs.store.strategy;

import lombok.Data;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 运费模板类
 */
@Data
public class ShippingTemplate {
    private Long id;
    /**
     * count, weight, volume
     */
    private String calculationType;
    /**
     * 区域列表
     */
    private List<Region> regions;
    /**
     * 包邮规则列表
     */
    private List<FreeShippingRule> freeShippingRules;
    /**
     * 计费方式
     */
    private FeeCalculationStrategy strategy;
    private List<ShippingFeeDecorator> decorators;
    /**
     * 排序
     */
    private int rank;

    public ShippingTemplate(Long id, String calculationType) {
        this.id = id;
        this.calculationType = calculationType;
        this.regions = new ArrayList<>();
        this.freeShippingRules = new ArrayList<>();
        this.decorators = new ArrayList<>();
        this.strategy = ShippingStrategyFactory.createStrategy(calculationType);
    }

    public void addRegion(Region region) {
        regions.add(region);
    }

    public void addFreeShippingRule(FreeShippingRule rule) {
        freeShippingRules.add(rule);
        // 添加包邮装饰器
        decorators.add(new FreeShippingDecorator(freeShippingRules));
    }

    public BigDecimal calculateShippingFee(ShippingOrder order) {
        // 找到对应区域
        Region targetRegion = null;
        for (Region region : regions) {
            if (region.getCityId().equals(order.getCityId())) {
                targetRegion = region;
                break;
            }
        }

        if (targetRegion == null) {
            throw new IllegalArgumentException("找不到匹配的配送区域: " + order.getCityId());
        }

        // 计算基础运费
        BigDecimal baseFee = strategy.calculate(order, targetRegion);

        // 是否包邮
        BigDecimal finalFee = baseFee;
        for (ShippingFeeDecorator decorator : decorators) {
            finalFee = decorator.calculateFee(finalFee, order, targetRegion);
        }

        return finalFee;
    }

    public boolean isFreeShippingEnabled() {
        return !freeShippingRules.isEmpty();
    }
}
