package com.prolog.eis.init;

import com.prolog.eis.constants.cache.EisCache;
import com.prolog.eis.constants.sys.SysParamConstants;
import com.prolog.eis.outbound_dispatch.DispatchStrategy;
import com.prolog.eis.service.core.OutboundService;
import com.prolog.eis.store_init.StoreInitStrategy;
import com.prolog.eis.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author dengj
 * @version 1.0
 * @date 2023/2/7 16:23
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class OutboundDispatch {

    private final OutboundService outboundService;

    private final Map<String, DispatchStrategy> dispatchStrategyMap;

    private final Map<String, StoreInitStrategy> storeInitStrategyMap;
    private final RedisTemplate redisTemplate;

    public void outbound() {
        String dispatchSwitch = String.valueOf(redisTemplate.opsForValue().get(SysParamConstants.SYSPRE_FIX + SysParamConstants.DISPATCH_SWITCH));
        if (dispatchSwitch.equals(SysParamConstants.DISPATCH_SWITCH_OFF)) {
            return;
        }
        for (Map.Entry<String, String> strategy : EisCache.OUTBOUND_DISPATCH_STRATEGY_MAP.entrySet()) {
            String key = strategy.getKey();
            String[] split = key.split("&");
            String billType = split[0];
            String warehouseArea = split[1];
            DispatchStrategy dispatchStrategy = dispatchStrategyMap.get(StringUtils.toFirstLow(strategy.getValue()));
            StoreInitStrategy storeInitStrategy = storeInitStrategyMap.get(StringUtils.toFirstLow(EisCache.OUTBOUND_STORE_STRATEGY_MAP.get(strategy.getValue())));
            try {
                outboundService.dispatch(billType, warehouseArea, dispatchStrategy, storeInitStrategy);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("出库调度失败：库区{}，业务类型{}库存缺货策略{} ，失败原因：" + e.getMessage(), warehouseArea,billType, e);
            }
        }

    }


}
