package com.ym.im.config;

import com.ym.im.util.MessageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

import javax.annotation.PostConstruct;
import java.util.Locale;

/**
 * @author 陈俊雄
 * @date 2019/5/31
 **/
@Configuration
public class LocaleConfig {
    @Autowired
    private WebMvcProperties webMvcProperties;

    @PostConstruct
    public void init() {
        // 初始化多语言工具类
        MessageUtils.setMessageSource(messageSource());
        Locale.setDefault(webMvcProperties.getLocale());
    }

    @Bean
    public MessageSource messageSource() {
        final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setDefaultEncoding("UTF-8");
        messageSource.setUseCodeAsDefaultMessage(true);
        messageSource.setBasenames("static.i18n.error", "static.i18n.message");
        return messageSource;
    }

    /**
     * validation注解返回异常消息多语言配置
     *
     * @return LocalValidatorFactoryBean
     */
    @Bean
    public LocalValidatorFactoryBean localValidatorFactoryBean() {
        LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
        bean.setValidationMessageSource(messageSource());
        return bean;
    }
}
