package com.ruoyi.i18n.utils;


import com.ruoyi.common.redis.service.RedisService;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

@Component
public class I18nUtils {

    /**
     * 国际化语言前缀
     */
    //private static String localeAttributeName = Constants.LOCALE_SESSION_ATTRIBUTE_NAME;
    private static String localeAttributeName ="";

    private static MessageSource messageSource;

    private static RedisService redisService;

    /**
     * 构建读取配置对象用于注入
     * @param messageSource
     */
    public I18nUtils(MessageSource messageSource,RedisService redisService) {
        I18nUtils.messageSource = messageSource;
        I18nUtils.redisService=redisService;
    }

    /**
     * 获取配置文件中key所对应的国际化语言
     * @param msgKey
     * @return
     */
    public static String getMessage(String msgKey) {
        return getMessage(msgKey, null);
    }

    /**
     * 获取配置文件中key所对应的国际化信息,存在占位符通过args数组进行数据填充
     * @param msgKey
     * @param args
     * @return
     */
    public static String getMessage(String msgKey,Object[] args) {
        try {
            return messageSource.getMessage(msgKey, args, getLocaleFromRedis());
        } catch (Exception e) {
            return msgKey;
        }
    }


    /**
     * 从redis中获取当前语言
     * @return
     */
    public static Locale getLocaleFromRedis(){
//        String token ="";
//        try {
//            token = TokenUtil.getToken(getRequest());
//        } catch (Exception e) {
//            return LocaleContextHolder.getLocale();
//        }
//        String lan=redisService.getCacheObject(localeAttributeName + token);
//        Locale locale=null;
//        if(StringUtils.isNotBlank(lan)){
//            String[] lans=lan.split("_");
//            locale = new Locale(lans[0], lans[1]);
//        }else{
//            locale=LocaleContextHolder.getLocale();//获取浏览器请求
//        }
        Locale locale=null;
        String[] lans = {"en","US"};
        locale = new Locale(lans[0], lans[1]);
        return locale;
    }

    /**
     * 获取请求属性
     * @return
     */
    public static ServletRequestAttributes getRequestAttributes()
    {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }

    /**
     * 获取请求request
     * @return
     */
    public static HttpServletRequest getRequest()
    {
        return getRequestAttributes().getRequest();
    }

}