import 'dart:convert';

import 'package:ef/ef.dart';
import 'package:flutter/services.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:path/path.dart' as path;
import 'package:vbvs_app/language/AppLanguage.dart';

part 'language_controller.g.dart'; // 由json_serializable自动生成的部分

@JsonSerializable()
class LanguageModel {
  String? filename; // 语言文件名称
  String? language_name; // 语言名称
  bool? selected; // 是否选中
  String? language_code;//语言简称

  LanguageModel();

  factory LanguageModel.fromJson(Map<String, dynamic> json) {
    try {
      return _$LanguageModelFromJson(json);
    } catch (e) {
      return LanguageModel(); // 或者返回一个带有错误信息的特定实例
    }
  }

  Map<String, dynamic> toJson() => _$LanguageModelToJson(this);
}

class LanguageController extends GetControllerEx<LanguageModel> {
  LanguageController() {
    attr = GetModel(LanguageModel()).obs;
  }

  RxList languageList = [].obs;
  var selectLanguage = Rx<LanguageModel?>(null);


  Future<void> initLanuageList() async {
    try {
      String currentLanguageCode = AppLanguage().getCurrentLanguageCode();
      languageList.clear(); // 清空现有列表

      // 1. 获取 assets/langs/ 目录下所有 .json 文件
      final manifestContent = await rootBundle.loadString('AssetManifest.json');
      final Map<String, dynamic> manifestMap = json.decode(manifestContent);

      // 筛选出 langs 目录下的 .json 文件
      final langFiles = manifestMap.keys
          .where((String key) =>
              key.startsWith('assets/langs/') && key.endsWith('.json'))
          .toList();

      // 2. 遍历所有语言文件
      for (final filePath in langFiles) {
        try {
          // 加载 JSON 文件内容
          final jsonString = await rootBundle.loadString(filePath);
          final jsonMap = json.decode(jsonString);

          // 提取语言名称（假设 JSON 文件中有 "语言名称" 字段）
          final languageName = jsonMap['语言名称'] as String? ??
              path.basenameWithoutExtension(filePath);

          // 3. 构造 LanguageModel 并添加到列表
          final languageModel = LanguageModel()
            ..filename = path.basename(filePath) // 如 "zh-CN.json"
            ..language_name = languageName // 如 "简体中文"
            ..selected =
                (path.basename(filePath) == '$currentLanguageCode.json')
            ..language_code =
                path.basenameWithoutExtension(filePath); // 如 "zh-CN"
          if (languageModel.selected == true) {
            selectLanguage.value = languageModel;
          }
          languageList.add(languageModel);
        } catch (e) {
          print('加载语言文件失败: $filePath, 错误: $e');
        }
      }
      print("object");
    } catch (e) {
      print('初始化语言列表失败: $e');
      // 可选：添加默认语言（如英文）作为后备
      languageList.add(
        LanguageModel()
          ..filename = 'en-US.json'
          ..language_name = 'English'
          ..selected = true, // 默认语言为选中状态
      );
    }
  }

}
