package com.backendsys.utils.response;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Locale;

/**
 * 使用 ResultEnumService 获取枚举类的国际化消息
 */
@Service
public class ResultEnumService {

    @Autowired
    private MessageSource messageSource;

    @Value("${DEFAULT_LANGUAGE}")
    private String DEFAULT_LANGUAGE;

    /**
     * 如果枚举类没有设置国际化消息，返回默认值
     * com/backendsys/utils/response/ResultEnum.java
     * TOKEN_INVALID(441, "Token已失效，请重新登录"),
     * TOKEN_INVALID(441, "Token已失效，请重新登录", "result.token.invalid"),
     */
    public String getMessage(ResultEnum resultEnum, String lang) {
        String message_key = resultEnum.getMessageKey();
        if (message_key != null) {
            return messageSource.getMessage(message_key, null, new Locale(lang));
        } else {
            return resultEnum.getMessage();
        }
    }
    public String getMessage(ResultEnum resultEnum) {
        // 获取当前线程绑定的request对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 从 Headers 中获取 lang 值
        String lang = request.getHeader("lang");
        if (lang == null || lang.isEmpty()) lang = DEFAULT_LANGUAGE;

        String message_key = resultEnum.getMessageKey();
        if (message_key != null) {
            return messageSource.getMessage(message_key, null, new Locale(lang));
        } else {
            return resultEnum.getMessage();
        }
    }

}
