package com.seer.teach.mall.factory;

import com.seer.teach.mall.service.ILogisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 物流服务工厂
 * 根据物流编码动态获取对应的物流服务实例
 */
@Component
public class LogisticsServiceFactory {


    private final Map<String, ILogisticsService> serviceMap = new ConcurrentHashMap<>();

    @Autowired
    public LogisticsServiceFactory(Map<String, ILogisticsService> logisticsServices) {
        for (Map.Entry<String, ILogisticsService> entry : logisticsServices.entrySet()) {
            String beanName = entry.getKey();
            // 物流公司 Bean 名称格式为：xxxLogisticsServiceImpl
            String code = beanName.replace("LogisticsServiceImpl", "").toUpperCase(Locale.ROOT);
            serviceMap.put(code, entry.getValue());
        }
    }

    /**
     * 获取物流服务实例
     *
     * @param logisticsCode 物流公司编码（如 JT、SF）
     * @return 对应的物流服务
     */
    public ILogisticsService getService(String logisticsCode) {
        ILogisticsService service = serviceMap.get(logisticsCode.toUpperCase(Locale.ROOT));
        if (service == null) {
            throw new IllegalArgumentException("不支持的物流公司编码: " + logisticsCode);
        }
        return service;
    }

}