package com.fs.erp.service.impl;

import com.fs.erp.constant.ErpTypeConstant;
import com.fs.erp.domain.ErpGoods;
import com.fs.erp.dto.*;
import com.fs.erp.service.IErpGoodsService;
import com.fs.erp.utils.ErpContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * ERP商品服务动态代理类
 * 通过ThreadLocal存储当前ERP类型，实现多ERP系统无感切换
 */
@Service
@Primary
public class ErpGoodsServiceProxy implements IErpGoodsService {

    /**
     * 存储所有实现的ERP服务
     */
    private final Map<String, IErpGoodsService> erpGoodsServiceMap = new HashMap<>();

    /**
     * 构造函数注入各种ERP实现
     */
    @Autowired
    public ErpGoodsServiceProxy(
            @Qualifier("JSTErpGoodsServiceImpl") IErpGoodsService jstErpGoodsService,
            @Qualifier("erpGoodsServiceImpl") IErpGoodsService gyErpGoodsService) {
        erpGoodsServiceMap.put(ErpTypeConstant.JST_ERP, jstErpGoodsService);
        erpGoodsServiceMap.put(ErpTypeConstant.GY_ERP, gyErpGoodsService);
    }

    /**
     * 获取当前应该使用的ERP服务实现
     * @return 对应ERP类型的服务实现
     */
    private IErpGoodsService getCurrentErpService() {
        String erpType = ErpContextHolder.getErpType();

        IErpGoodsService service = erpGoodsServiceMap.get(erpType);
        if (service == null) {
            throw new IllegalStateException("未找到ERP类型 [" + erpType + "] 的实现");
        }
        return service;
    }

    @Override
    public BaseResponse addGoods(ErpGoods goods) {
        return getCurrentErpService().addGoods(goods);
    }

    @Override
    public ErpGoodsQueryResponse getGoods(ErpGoodsQueryRequert param) {
        return getCurrentErpService().getGoods(param);
    }

    @Override
    public ErpGoodsStockQueryResponse getGoodsStock(ErpGoodsStockQueryRequert param) {
        return getCurrentErpService().getGoodsStock(param);
    }
}
