package com.yd.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Locale;

/**
 * @description
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {

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

    public static ApplicationContext getApplicationContext() {
        return SpringContextUtil.applicationContext;
    }
    // 传入线程中
    @SuppressWarnings("unchecked")
	public static <T> T getBean(String beanName) {
        return (T) applicationContext.getBean(beanName);
    }
    public static <T> T getBean(Class<T> t) {
        return SpringContextUtil.applicationContext.getBean(t);
    }
 
    // 国际化使用
    public static String getMessage(String key) {
    	String message = null;
    	try {
    		Locale locale = new Locale("zh", "CN");
			message = applicationContext.getMessage(key, null,locale);
		} catch (Exception e) {
			e.getMessage();
		}
        return message;
    }
 
 
    /// 获取当前环境
    public static String getActiveProfile() {
        return applicationContext.getEnvironment().getActiveProfiles()[0];
    }
    /**
     * 是否为本地环境
     * @return
     */
    public static boolean isLocal() {
        return "LOCAL".equals(getEnvironmentName());
    }
    /**
     * 是否为DEV环境
     * @return
     */
    public static boolean isDev() {
        return "DEV".equals(getEnvironmentName());
    }
    /**
     * 是否为STAGE环境
     * @return
     */
    public static boolean isStage() {
        return "STAGE".equals(getEnvironmentName());
    }
    /**
     * 是否为PROD环境
     * @return
     */
    public static boolean isProd() {
        return "PROD".equals(getEnvironmentName());
    }
    /**
     * 获取环境名字
     */
    public static String getEnvironmentName() {
        return getActiveProfile().toUpperCase();
    }

}
