package com.qaup.framework.config.properties;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;
import org.apache.commons.lang3.RegExUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import com.qaup.common.annotation.Anonymous;
import org.springframework.lang.NonNull;

/**
 * 设置Anonymous注解允许匿名访问的url
 * 
 * @author ruoyi
 */
@Configuration
public class PermitAllUrlProperties implements InitializingBean, ApplicationContextAware
{
    private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}");

    private ApplicationContext applicationContext;

    private List<String> urls = new ArrayList<>();

    public String ASTERISK = "*";

    @Override
    public void afterPropertiesSet()
    {
        // 智能选择RequestMappingHandlerMapping bean以避免Spring Boot 3.x中的多bean冲突
        RequestMappingHandlerMapping mapping;
        try {
            // 首先尝试通过bean名称获取主要的RequestMappingHandlerMapping
            mapping = (RequestMappingHandlerMapping) applicationContext.getBean("requestMappingHandlerMapping");
        } catch (Exception e) {
            // 如果通过名称获取失败，则获取所有RequestMappingHandlerMapping类型的bean
            Map<String, RequestMappingHandlerMapping> mappings = applicationContext.getBeansOfType(RequestMappingHandlerMapping.class);
            
            // 选择主要的RequestMappingHandlerMapping（排除Actuator的端点处理器）
            mapping = mappings.values().stream()
                    .filter(m -> {
                        String className = m.getClass().getName();
                        // 优先选择标准的RequestMappingHandlerMapping，排除Actuator相关的
                        return className.contains("RequestMappingHandlerMapping") 
                                && !className.contains("Endpoint")
                                && !className.contains("Actuator");
                    })
                    .findFirst()
                    .orElse(mappings.values().iterator().next());
        }
        
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();

        map.keySet().forEach(info -> {
            HandlerMethod handlerMethod = map.get(info);

            // 获取方法上边的注解 替代path variable 为 *
            Anonymous method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), Anonymous.class);
            Optional.ofNullable(method).ifPresent(anonymous ->
                Optional.ofNullable(info.getPathPatternsCondition())
                    .ifPresent(condition -> condition.getPatternValues()
                        .forEach(url -> urls.add(RegExUtils.replaceAll(url, PATTERN, ASTERISK))))
            );

            // 获取类上边的注解, 替代path variable 为 *
            Anonymous controller = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), Anonymous.class);
            Optional.ofNullable(controller).ifPresent(anonymous ->
                Optional.ofNullable(info.getPathPatternsCondition())
                    .ifPresent(condition -> condition.getPatternValues()
                        .forEach(url -> urls.add(RegExUtils.replaceAll(url, PATTERN, ASTERISK))))
            );
        });
    }

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

    public List<String> getUrls()
    {
        return urls;
    }

    public void setUrls(List<String> urls)
    {
        this.urls = urls;
    }
}
