package com.sundot.airport.common.service.portrait;

import com.sundot.airport.common.domain.portrait.IndicatorCalculateParams;
import com.sundot.airport.common.domain.portrait.ModularIndicatorResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;

/**
 * 模块化指标管理器
 * 管理所有模块的指标计算服务
 */
@Component
public class ModuleIndicatorManager {

    @Autowired
    private Set<ModuleIndicatorService> moduleIndicatorServices;

    private Map<String, ModuleIndicatorService> moduleServiceMap = new HashMap<>();

    @PostConstruct
    public void initModuleServiceMap() {
        for (ModuleIndicatorService service : moduleIndicatorServices) {
            moduleServiceMap.put(service.getModuleName(), service);
        }
    }

    /**
     * 计算指定模块的指标
     *
     * @param params      指标计算参数
     * @param moduleNames 模块名称列表
     * @return 模块化指标结果
     */
    public ModularIndicatorResult calculateModuleIndicators(IndicatorCalculateParams params, List<String> moduleNames) {
        ModularIndicatorResult result = new ModularIndicatorResult();

        if (moduleNames == null || moduleNames.isEmpty()) {
            // 计算所有模块的指标
            for (Map.Entry<String, ModuleIndicatorService> entry : moduleServiceMap.entrySet()) {
                Object moduleResult = entry.getValue().calculateIndicators(params);
                result.addModuleResult(entry.getKey(), moduleResult);
            }
        } else {
            // 计算指定模块的指标
            for (String moduleName : moduleNames) {
                ModuleIndicatorService service = moduleServiceMap.get(moduleName);
                if (service != null) {
                    Object moduleResult = service.calculateIndicators(params);
                    result.addModuleResult(moduleName, moduleResult);
                }
            }
        }

        return result;
    }

    /**
     * 计算所有模块的指标
     *
     * @param params 指标计算参数
     * @return 模块化指标结果
     */
    public ModularIndicatorResult calculateAllModuleIndicators(IndicatorCalculateParams params) {
        return calculateModuleIndicators(params, null);
    }
}