package com.fs.erp.service.impl;

import com.fs.erp.constant.ErpTypeConstant;
import com.fs.erp.domain.ErpOrder;
import com.fs.erp.domain.ErpRefundOrder;
import com.fs.erp.domain.ErpUser;
import com.fs.erp.dto.*;
import com.fs.erp.service.IErpOrderService;
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订单服务动态代理类
 * 通过ErpContextHolder获取当前ERP类型，实现多ERP系统无感切换
 */
@Service
@Primary
public class ErpOrderServiceProxy implements IErpOrderService {

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

    /**
     * 构造函数注入各种ERP实现
     */
    @Autowired
    public ErpOrderServiceProxy(
            @Qualifier("JSTErpOrderServiceImpl") IErpOrderService jstErpOrderService,
            @Qualifier("erpOrderServiceImpl") IErpOrderService gyErpOrderService) {
        erpOrderServiceMap.put(ErpTypeConstant.JST_ERP, jstErpOrderService);
        erpOrderServiceMap.put(ErpTypeConstant.GY_ERP, gyErpOrderService);
    }

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

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

    @Override
    public ErpOrderResponse addOrder(ErpOrder order) {
        return getCurrentErpService().addOrder(order);
    }

    @Override
    public ErpOrderResponse refundOrder(ErpRefundOrder order) {
        return getCurrentErpService().refundOrder(order);
    }

    @Override
    public ErpDeliverysResponse getDeliver(ErpDeliverysRequest param) {
        return getCurrentErpService().getDeliver(param);
    }

    @Override
    public ErpOrderQueryResponse getOrder(ErpOrderQueryRequert param) {
        return getCurrentErpService().getOrder(param);
    }

    @Override
    public BaseResponse refundUpdate(ErpRefundUpdateRequest param) {
        return getCurrentErpService().refundUpdate(param);
    }
}
