package com.ruoyi.interfaces.workflow;

/**
 * @author LinQiLong
 * @date 2025/7/15 16:48
 */

import com.ruoyi.interfaces.domain.MdModelStep;
import com.ruoyi.interfaces.workflow.executor.StepExecutor;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

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

/**
 * 步骤执行器工厂
 */
@Component
public class ExecutorFactory implements ApplicationContextAware {

    // 步骤类型到执行器的映射
    private final Map<MdModelStep.StepType, StepExecutor> executorMap = new HashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 从Spring容器中获取所有StepExecutor实现
        Map<String, StepExecutor> executors = applicationContext.getBeansOfType(StepExecutor.class);

        // 建立步骤类型到执行器的映射
        for (StepExecutor executor : executors.values()) {
            MdModelStep.StepType supportedType = executor.getSupportedStepType();
            if (supportedType != null) {
                executorMap.put(supportedType, executor);
            }
        }
    }

    /**
     * 根据步骤类型获取执行器
     *
     * @param stepType 步骤类型
     * @return 对应的执行器实例
     */
    public StepExecutor getExecutor(MdModelStep.StepType stepType) {
        StepExecutor executor = executorMap.get(stepType);
        if (executor == null) {
            throw new UnsupportedOperationException("不支持的步骤类型: " + stepType);
        }
        return executor;
    }

}
