package com.tofly.gpsboot.strategy.context;

import com.tofly.gpsboot.common.Constant;
import com.tofly.gpsboot.common.system.ReportTypeEnum;
import com.tofly.pojo.plan.dto.ReportAuditDto;
import com.tofly.gpsboot.exception.BusinessException;
import com.tofly.gpsboot.strategy.ReportStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * <p>
 * 策略管理 服务实现类
 * </p>
 *
 * @author Zev
 * @since 2021-03-20
 */
@Component
public class ReportStrategyContext {
    /**
     * 使用线程安全的ConcurrentHashMap存储所有实现Strategy接口的Bean
     * key:beanName
     * value：实现Strategy接口Bean
     */
    private final Map<String, ReportStrategy> strategyMap = new ConcurrentHashMap<>();

    /**
     * 注入所有实现了Strategy接口的Bean
     *
     * @param strategyMap
     */
    @Autowired
    public ReportStrategyContext(Map<String, ReportStrategy> strategyMap) {
        this.strategyMap.clear();
        strategyMap.forEach(this.strategyMap::put);
    }


    /**
     * 上报处理(支持单个及批量)
     *
     * @param dto                  上报数据
     * @param templateServiceType 服务类型
     * @throws BusinessException 相关业务异常说明
     */
    public void report(String templateServiceType, ReportAuditDto dto) throws BusinessException {
        ReportStrategy reportStrategy = strategyMap.get(ReportTypeEnum.getCodeForInjectionServerType(templateServiceType));
        if(null == reportStrategy){
            throw new BusinessException(Constant.SERVICE_POLICY_NOT_INJECTED_CODE,Constant.SERVICE_POLICY_NOT_INJECTED);
        }
        reportStrategy.report(dto);
    }
}
