package com.sonic.common.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;

import java.util.Locale;

/**
 * 国际化工具类
 * @author code
 * @description 国际化工具
 */
@Component
public class MessageUtils {

    private static MessageSource messageSource;


    @Autowired
    public void setMessageSource(MessageSource messageSource) {
        MessageUtils.messageSource = messageSource;
    }

    /**
     * 获取单个国际化翻译值
     */
    public static String get(String msgKey) {
        try {
            String message = messageSource.getMessage(msgKey, null, LocaleUtils.getLocale());
            return message;
        } catch (Exception e) {
            e.printStackTrace();
            return msgKey;
        }
    }

    public static String get(String msgKey, Locale locale) {
        try {
            String message = messageSource.getMessage(msgKey, null, locale);
            return message;
        } catch (Exception e) {
            return msgKey;
        }
    }

    public static String getMessage(String code, Locale locale) {
        try {
            String message = messageSource.getMessage(code, null, locale);
            return message;
        } catch (Exception e) {
            return code;
        }
    }

    public static String getMessage(String code, Object[] args, Locale locale) {
        return messageSource.getMessage(code, args, locale);
    }

}
