package com.tofly.gpsboot.strategy.context;

import com.tofly.gpsboot.common.Constant;
import com.tofly.gpsboot.common.system.AuditTypeEnum;
import com.tofly.pojo.plan.dto.ReportAuditDto;
import com.tofly.gpsboot.exception.BusinessException;
import com.tofly.gpsboot.strategy.AuditStrategy;
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 AuditStrategyContext {
    /**
     * 使用线程安全的ConcurrentHashMap存储所有实现Strategy接口的Bean
     * key:beanName
     * value：实现Strategy接口Bean
     */
    private final Map<String, AuditStrategy> strategyMap = new ConcurrentHashMap<>();

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


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

    }
}
