import 'dart:convert';
import 'dart:ui';

import 'package:ef/ef.dart';
import 'package:flutter/services.dart';

class AppLanguage extends Translations {
  // 私有构造函数
  AppLanguage._internal();

  // 当前语言
  String _currentLanguageCode = 'zh_CN'; //

  // 单例实例
  static final AppLanguage _instance = AppLanguage._internal();

  factory AppLanguage() => _instance;

  // 缓存翻译数据
  final Map<String, Map<String, String>> _localizedValues = {};

  @override
  Map<String, Map<String, String>> get keys => _localizedValues;

  // 动态加载语言文件
  // Future<void> loadLanguage(String languageCode) async {
  //   if (_localizedValues.containsKey(languageCode)) {
  //     return; // 如果语言已经加载，无需重复加载
  //   }

  //   try {
  //     // 加载 JSON 文件
  //     final jsonString =
  //         await rootBundle.loadString('assets/langs/$languageCode.json');
  //     final Map<String, dynamic> jsonMap = json.decode(jsonString);

  //     // 扁平化 JSON 数据并存储到缓存
  //     _localizedValues[languageCode] = _flattenJson(jsonMap);

  //     // 通知 GetX 更新 keys
  //     // Get.forceAppUpdate();
  //     Get.appendTranslations(keys);

  //     _currentLanguageCode = languageCode;
  //     Get.updateLocale(Locale(languageCode));
  //   } catch (e) {
  //     print('Error loading $languageCode language file: $e');
  //   }
  // }

  Future<void> loadLanguage(String languageCode,
      {String project = 'th'}) async {
    try {
      final jsonString;
      // 加载 JSON 文件
      if (project == 'th') {
        jsonString =
            await rootBundle.loadString('assets/langs/$languageCode.json');
      } else if (project == 'mht') {
        jsonString =
            await rootBundle.loadString('assets/mhlangs/$languageCode.json');
      } else {
        jsonString =
            await rootBundle.loadString('assets/langs/$languageCode.json');
      }

      final Map<String, dynamic> jsonMap = json.decode(jsonString);

      // 扁平化 JSON 数据
      final Map<String, String> translations = _flattenJson(jsonMap);

      // 加载并设置翻译
      Get.clearTranslations(); // 清除之前加载的翻译，确保切换时不混乱
      Get.addTranslations({languageCode: translations});
      Get.updateLocale(Locale(languageCode)); // 切换语言

      _currentLanguageCode = languageCode; // 可选：记录当前语言码
    } catch (e) {
      print('Error loading $languageCode language file: $e');
    }
  }

  // 扁平化嵌套 JSON 数据
  Map<String, String> _flattenJson(Map<String, dynamic> json,
      [String prefix = '']) {
    final Map<String, String> flatMap = {};
    json.forEach((key, value) {
      final newKey = prefix.isEmpty ? key : '$prefix.$key';
      if (value is Map<String, dynamic>) {
        flatMap.addAll(_flattenJson(value, newKey));
      } else {
        flatMap[newKey] = value.toString();
      }
    });
    return flatMap;
  }

  // 清理语言缓存
  void clearLanguage(String languageCode) {
    _localizedValues.remove(languageCode);
  }

  // 获取当前使用的语言
  String getCurrentLanguageCode() {
    return _currentLanguageCode;
  }

  Locale get currentLocale {
    final parts = _currentLanguageCode.split('-');
    return Locale(parts[0], parts.length > 1 ? parts[1] : null);
  }

  bool isChinese() {
    return _currentLanguageCode == "zh_CN";
  }
}
