package com.tzy.common.dto.order;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.tzy.common.exception.ServiceException;
import lombok.Data;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Comparator;
import java.util.List;

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class MerchantCostConfig implements Serializable {
    private Integer minNum;
    private Integer maxNum;
    private List<CostConfig> costConfig;

    @Data
    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class CostConfig implements Serializable {
        private Integer startNum;
        private Integer endNum;
        private BigDecimal cost;
    }

    public static BigDecimal buildMerchantShippingCost(MerchantCostConfig config, Integer totalCount) {
        if (CollectionUtils.isEmpty(config.getCostConfig())) {
            throw new ServiceException("商家运费配置异常,请联系商家客服!");
        }
        return config.getCostConfig().stream().filter(c -> totalCount >= c.getStartNum() && c.getCost() != null)
                .max(Comparator.comparing(MerchantCostConfig.CostConfig::getEndNum))
                .orElseThrow(() -> new ServiceException("商家运费配置异常,请联系商家客服!"))
                .getCost();
    }
}
