package com.uas.finance;

import com.uas.finance.filter.AccessSignatureInterceptor;
import com.uas.finance.filter.SSOInterceptor;
import com.uas.finance.util.ContextUtils;
import com.uas.sso.web.AccountConfigurer;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.Properties;

/**
 * SSOconfig 配置
 *
 * @author hejq
 */
@Configuration
public class SSOConfiguration extends WebMvcConfigurerAdapter {

    @Autowired
    private SSOInterceptor ssoInterceptor;

    @Autowired
    private AccessSignatureInterceptor accessSignatureInterceptor;

    private Logger logger = Logger.getLogger(this.getClass());

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        /**
         * SSO过滤, 这个地方拦截配置
         */
        registry.addInterceptor(ssoInterceptor).addPathPatterns("/**").
                excludePathPatterns("/WEB-INF/**", "/**/static/**", "/sso/login/**", "/sso/login","/sso/logout/**", "/sso/register/**",
                        "/erp/**", "/sellerquota/erp/**", "/customer/erp/**", "/repayment/erp/**", "/login/**");

        /**
         * 拦截器配置
         */
        registry.addInterceptor(accessSignatureInterceptor).addPathPatterns("/erp/**", "/sellerquota/erp/**", "/customer/erp/**", "/repayment/erp/**");

    }

    @Bean
    @Profile("prod")
    public AccountConfigurer prodAccountConfigurer() {
        return accountConfigurer("prod");
    }

    @Bean
    @Profile("dev")
    public AccountConfigurer testAccountConfigurer() {
        return accountConfigurer("dev");
    }

    /**
     * 获取当前环境下的配置
     *
     * @param profile
     * @return
     */
    private AccountConfigurer accountConfigurer(String profile) {
        AccountConfigurer accountConfigurer = new AccountConfigurer();
        accountConfigurer.setApplicationContext(ContextUtils.getApplicationContext());
        Properties properties = new Properties();
        String configPath = profile + "/account.properties";
        logger.info("***: " + configPath);
        try {
            properties.load(this.getClass().getClassLoader().getResourceAsStream(configPath));
        } catch (Throwable e) {
            throw new IllegalStateException("配置加载失败" + configPath);
        }
        accountConfigurer.initProperties(properties);
        return accountConfigurer;
    }
}
