package com.xxx.base.springframework.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;

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

@Slf4j
@Configuration
public class PathLocaleResolver implements LocaleResolver {

    private static final String ADMIN_DEFAULT_LANGUAGE = "zh_CN";

    private static final String DEFAULT_LANGUAGE = "idn";

    @Autowired
    private HttpServletRequest request;

    public Locale getLocal() {
        return resolveLocale(request);
    }

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String lang = request.getParameter("lang");
        if (StringUtils.isNotBlank(lang)) {
            if (StringUtils.equals(lang, ADMIN_DEFAULT_LANGUAGE)) {
                return Locale.SIMPLIFIED_CHINESE;
            }

            return new Locale(lang);
        }

        String path = request.getRequestURI();
        if (StringUtils.contains(path, "/admin/")) {
            return Locale.SIMPLIFIED_CHINESE;
        }
        return new Locale(DEFAULT_LANGUAGE);
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
        // 可选：根据业务逻辑保存到 Session 或 Cookie
    }
}