package org.example.Utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.MissingResourceException;
import java.util.ResourceBundle;

@Component
public class LanguageUtil {
    private static final Logger log = LoggerFactory.getLogger(LanguageUtil.class);



    static final String DEFAULT_LANGUAGE = "Language_CN";

    // 保留原有静态变量名（必须与其他代码使用的名称一致）
    public static String Fail;
    public static String InvalidParameter;
    public static String InvalidSql;
    public static String LoadFailed;
    public static String NameOrPwdError;
    public static String ServerError;
    public static String WrongOldPwd;
    public static String Success;
    public static String NoAuthory;
    public static String WrongInterfaceName;
    public static String WrongMainCfg;
    public static String DifferentPwd;
    public static String FileExistCover;
    public static String NoneSelected;
    public static String ErrorReason;
    public static String WrongPhoneNumber;
    public static String WrongVCode;
    public static String Wrong;
    public static String NotNull;
    public static String LimitOfTheNumber;
    public static String IllegalOperation;

    @Autowired
    private WebConfigUtil webConfigUtil;

    // 资源束缓存（静态成员）
    private static ResourceBundle lrm;
    // 临时存储当前语言（静态，供全局使用）
    private static String currentLanguage;

    // Spring初始化后执行
    @PostConstruct
    public void init() {
        // 初始化当前语言（从WebConfigUtil获取默认值）
        currentLanguage = webConfigUtil.getLanguage();
        if (currentLanguage == null || currentLanguage.trim().isEmpty()) {
            currentLanguage = DEFAULT_LANGUAGE;
        }
        // 加载默认语言资源
        reloadResourceBundle();
        // 初始化静态变量（首次加载默认语言）
        refreshStaticFields();
    }

    // 新增：动态设置语言（接收BaseImpl传递的lg参数）
    public static void setCurrentLanguage(String lg) {
        // 根据lg参数确定目标语言资源名
        String targetLanguage;
        switch (lg.toLowerCase()) {
            case "en":
                targetLanguage = "Language_EN";
                break;
            case "cn":
            default:
                targetLanguage = DEFAULT_LANGUAGE;
                break;
        }

        // 语言未变更则无需处理
        if (targetLanguage.equals(currentLanguage)) {
            return;
        }

        // 更新语言并重新加载资源
        currentLanguage = targetLanguage;
        reloadResourceBundle();
        // 刷新静态变量值（关键：保证其他代码使用的静态变量是最新语言）
        refreshStaticFields();
    }

    // 新增：重新加载资源束
    private static void reloadResourceBundle() {
        try {
            // 资源文件包路径（请根据实际项目结构修改，确保与LanguageCN.class同包）
            String namespace = LanguageCN.class.getPackage().getName();
            String baseName = namespace + "." + currentLanguage;

            // 重新加载资源文件（覆盖原有缓存）
            lrm = ResourceBundle.getBundle(baseName);
            log.debug(String.valueOf("语言资源加载成功：" + baseName));
        } catch (Exception e) {
            // 加载失败时fallback到默认语言
            String defaultBaseName = LanguageCN.class.getPackage().getName() + "." + DEFAULT_LANGUAGE;
            lrm = ResourceBundle.getBundle(defaultBaseName);
            log.debug(String.valueOf("语言资源加载失败，使用默认：" + defaultBaseName));
            log.error("Exception caught", e);
        }
    }

    // 新增：刷新静态变量（保证其他代码访问的是最新语言文案）
    private static void refreshStaticFields() {
        Fail = GetString("Fail");
        InvalidParameter = GetString("InvalidParameter");
        InvalidSql = GetString("InvalidSql");
        LoadFailed = GetString("LoadFailed");
        NameOrPwdError = GetString("NameOrPwdError");
        ServerError = GetString("ServerError");
        WrongOldPwd = GetString("WrongOldPwd");
        Success = GetString("Success");
        NoAuthory = GetString("NoAuthory");
        WrongInterfaceName = GetString("WrongInterfaceName");
        WrongMainCfg = GetString("WrongMainCfg");
        DifferentPwd = GetString("DifferentPwd");
        FileExistCover = GetString("FileExistCover");
        NoneSelected = GetString("NoneSelected");
        ErrorReason = GetString("ErrorReason");
        WrongPhoneNumber = GetString("WrongPhoneNumber");
        WrongVCode = GetString("WrongVCode");
        Wrong = GetString("Wrong");
        NotNull = GetString("NotNull");
        LimitOfTheNumber = GetString("LimitOfTheNumber");
        IllegalOperation = GetString("IllegalOperation");
    }

    // 原有方法：获取多语言文本
    public static String GetString(String key) {
        try {
            return lrm.getString(key);
        } catch (MissingResourceException e) {
            return key; // 找不到时返回key，方便排查
        }
    }
}

// 保留原有辅助类（用于获取资源文件包路径）
class LanguageCN {}
