package cn.meowrain.aioj.backend.framework.core.designpattern.chains;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 公共责任链容器
 *
 * @param <T>
 */
@Component
@Slf4j
public class CommonChainContext<T> implements ApplicationContextAware, CommandLineRunner {

	private ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	private final Map<String, List<AbstractChianHandler<T>>> abstractChainHandlerMap = new HashMap<>();

	public void handler(String mark, T requestParam) {
		List<AbstractChianHandler<T>> merchantAdminAbstractChainHandlers = abstractChainHandlerMap.get(mark);
		if (merchantAdminAbstractChainHandlers == null || merchantAdminAbstractChainHandlers.isEmpty()) {
			throw new RuntimeException(String.format("[%s] Chain of Responsibility ID is undefined.", mark));
		}
		merchantAdminAbstractChainHandlers.forEach(h -> {
			h.handle(requestParam);
		});
	}

	@Override
	public void run(String... args) throws Exception {
		log.info("【责任链路初始化】开始加载并分组所有处理器...");
		applicationContext.getBeansOfType(AbstractChianHandler.class).values().forEach(handler -> {
			// 打印当前处理器的类名和它所属的 ChainMark
			String handlerName = handler.getClass().getSimpleName();
			String mark = handler.mark();
			log.info("    -> 发现处理器：{}，归属链路：{}", handlerName, mark);
			abstractChainHandlerMap.computeIfAbsent(handler.mark(), k -> new ArrayList<>()).add(handler);
		});

		// 步骤 2: 对每个链路中的处理器进行排序 (Sort 阶段)
		abstractChainHandlerMap.forEach((mark, handlers) -> {
			handlers.sort(Comparator.comparing(Ordered::getOrder));

			// 打印排序后的 Bean 列表
			String sortedList = handlers.stream()
				.map(h -> String.format("%s (Order:%d)", h.getClass().getSimpleName(), h.getOrder()))
				.collect(Collectors.joining(" -> "));

			log.info("    ✅ 链路 {} 排序完成：{}", mark, sortedList);
		});

		log.info("【责任链路初始化】所有处理器链已完全就绪。");
	}

}
