package com.erp.logistics.service.adapter;

import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 物流商适配器工厂
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class CarrierAdapterFactory {

    private final List<CarrierAdapter> carriers;
    private Map<String, CarrierAdapter> carrierMap;

    @PostConstruct
    public void init() {
        carrierMap = carriers.stream()
                .collect(Collectors.toMap(CarrierAdapter::getCarrierCode, Function.identity()));
        log.info("已加载物流商适配器: {}", carrierMap.keySet());
    }

    /**
     * 根据编码获取适配器
     */
    public CarrierAdapter getAdapter(String carrierCode) {
        CarrierAdapter adapter = carrierMap.get(carrierCode.toUpperCase());
        if (adapter == null) {
            throw new IllegalArgumentException("不支持的物流商: " + carrierCode);
        }
        return adapter;
    }

    /**
     * 根据运单号自动识别物流商
     */
    public CarrierAdapter match(String waybillNo) {
        for (CarrierAdapter adapter : carriers) {
            if (adapter.match(waybillNo)) {
                log.debug("运单号 {} 识别为 {}", waybillNo, adapter.getCarrierName());
                return adapter;
            }
        }
        log.warn("无法识别运单号 {} 的物流商", waybillNo);
        return null;
    }

    /**
     * 获取所有支持的物流商
     */
    public List<CarrierAdapter> getAllCarriers() {
        return carriers;
    }

    /**
     * 是否支持该物流商
     */
    public boolean isSupported(String carrierCode) {
        return carrierMap.containsKey(carrierCode.toUpperCase());
    }
}
