import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svga/flutter_svga.dart';
import 'package:yumi/shared/data_sources/sources/local/file_cache_manager.dart';
import 'package:yumi/shared/data_sources/sources/repositories/sc_config_repository_imp.dart';
import 'package:yumi/shared/data_sources/sources/repositories/sc_room_repository_imp.dart';
import 'package:yumi/shared/tools/sc_path_utils.dart';
import 'package:yumi/shared/tools/sc_gift_vap_svga_manager.dart';
import 'package:yumi/shared/data_sources/models/country_mode.dart';
import 'package:yumi/shared/business_logic/models/res/sc_banner_leaderboard_res.dart';
import 'package:yumi/shared/business_logic/models/res/country_res.dart';
import 'package:yumi/shared/business_logic/models/res/gift_res.dart';
import 'package:yumi/shared/business_logic/models/res/sc_index_banner_res.dart';
import 'package:yumi/shared/business_logic/models/res/sc_room_emoji_res.dart';

import '../../shared/data_sources/models/enum/sc_banner_type.dart';

class SCAppGeneralManager extends ChangeNotifier {
  List<CountryMode> countryModeList = [];
  Map<String, List<Country>> _countryMap = {};
  Map<String, Country> _countryByNameMap = {};
  bool _isFetchingCountryList = false;

  ///礼物
  List<SocialChatGiftRes> giftResList = [];
  Map<String, SocialChatGiftRes> _giftByIdMap = {};

  Map<String, List<SocialChatGiftRes>> giftByTab = {};
  Map<String, List<SocialChatGiftRes>> activityGiftByTab = {};

  ///选中的国家
  Country? selectCountryInfo;

  List<SocialChatGiftRes> activityList = [];

  SCAppGeneralManager() {
    fetchCountryList();
    giftList(); // 使用默认参数
    giftActivityList();
    // giftBackpack();
    // configLevel();
  }

  ///加载国家列表
  Future<void> fetchCountryList() async {
    if (_isFetchingCountryList) {
      return;
    }
    if (countryModeList.isNotEmpty) {
      clearCountrySelection();
      notifyListeners();
      return;
    }

    _isFetchingCountryList = true;
    try {
      await Future.delayed(Duration(milliseconds: 550));
      final result = await SCConfigRepositoryImp().loadCountry();
      _countryMap.clear();
      _countryByNameMap.clear();
      countryModeList.clear();

      for (final c in result.openCountry ?? const <Country>[]) {
        final prefix = c.aliasName?.substring(0, 1) ?? "";
        if (prefix.isNotEmpty) {
          final countryList = _countryMap[prefix] ?? <Country>[];
          countryList.add(c.copyWith());
          _countryMap[prefix] = countryList;
        }
        if ((c.countryName ?? "").isNotEmpty) {
          _countryByNameMap[c.countryName!] = c;
        }
      }

      _countryMap.forEach((k, v) {
        countryModeList.add(CountryMode(k, v));
      });

      ///排序
      countryModeList.sort((a, b) => a.prefix.compareTo(b.prefix));
      notifyListeners();
    } catch (_) {
      notifyListeners();
    } finally {
      _isFetchingCountryList = false;
    }
  }

  ///国家国家名称获取国家
  Country? findCountryByName(String countryName) {
    return _countryByNameMap[countryName];
  }

  ///选择国家
  Country? chooseCountry(int subIndex, int cIndex) {
    var selectCm = countryModeList[subIndex].prefixCountrys[cIndex];
    if (selectCountryInfo != null) {
      selectCountryInfo = null;
    } else {
      selectCountryInfo = selectCm;
    }
    return selectCountryInfo;
  }

  void updateCurrentCountry(Country? countryInfo) {
    selectCountryInfo = countryInfo;
    notifyListeners();
  }

  void clearCountrySelection() {
    selectCountryInfo = null;
  }

  void openDrawer(BuildContext context) {
    Scaffold.of(context).openDrawer();
  }

  void closeDrawer(BuildContext context) {
    Scaffold.of(context).closeDrawer();
  }

  void giftList({bool includeCustomized = true}) async {
    try {
      giftResList = await SCChatRoomRepository().giftList();
      giftByTab.clear();
      for (var gift in giftResList) {
        giftByTab[gift.giftTab];
        var gmap = giftByTab[gift.giftTab];
        gmap ??= [];
        gmap.add(gift);
        giftByTab[gift.giftTab!] = gmap;
        var gAllMap = giftByTab["ALL"];
        gAllMap ??= [];
        if (gift.giftTab != "NSCIONAL_FLAG" &&
            gift.giftTab != "ACTIVITY" &&
            gift.giftTab != "LUCKY_GIFT" &&
            gift.giftTab != "CP" &&
            gift.giftTab != "CUSTOMIZED" &&
            gift.giftTab != "MAGIC") {
          gAllMap.add(gift);
        }
        giftByTab["ALL"] = gAllMap;
        _giftByIdMap[gift.id!] = gift;
      }

      if (includeCustomized) {
        giftByTab["CUSTOMIZED"] ??= [];

        ///定制礼物需要一个占位符，显示规则的
        giftByTab["CUSTOMIZED"]?.insert(0, SocialChatGiftRes(id: "-1000"));
      } else {
        giftByTab.remove("CUSTOMIZED");
      }

      notifyListeners();

      ///先去预下载
      downLoad(giftResList);
    } catch (e) {}
  }

  void giftActivityList() async {
    try {
      activityList.clear();
      activityList = await SCChatRoomRepository().giftActivityList();
      activityGiftByTab.clear();
      for (var gift in activityList) {
        var gmap = activityGiftByTab["${gift.activityId}"];
        gmap ??= [];
        gmap.add(gift);
        activityGiftByTab["${gift.activityId}"] = gmap;
      }
      notifyListeners();
    } catch (e) {}
  }

  ///礼物背包
  void giftBackpack() async {
    try {
      var result = await SCChatRoomRepository().giftBackpack();
    } catch (e) {}
  }

  ///礼物id获取礼物
  SocialChatGiftRes? getGiftById(String id) {
    return _giftByIdMap[id];
  }

  void downLoad(List<SocialChatGiftRes> giftResList) {
    for (var gift in giftResList) {
      if (gift.giftSourceUrl != null) {
        if (SCPathUtils.getFileExtension(gift.giftSourceUrl!).toLowerCase() ==
            ".svga") {
          ///预解析
          if (!SCGiftVapSvgaManager().videoItemCache.containsKey(
            gift.giftSourceUrl,
          )) {
            SVGAParser.shared.decodeFromURL(gift.giftSourceUrl!).then((entity) {
              entity.autorelease = false;
              SCGiftVapSvgaManager().videoItemCache[gift.giftSourceUrl!] =
                  entity;
            });
          }
        } else {
          if ((gift.giftSourceUrl ?? "").isNotEmpty) {
            FileCacheManager.getInstance().getFile(url: gift.giftSourceUrl!);
          }
        }
      }
    }
  }

  List<SCIndexBannerRes> homeBanners = [];
  List<SCIndexBannerRes> exploreBanners = [];
  List<SCIndexBannerRes> roomBanners = [];
  List<SCIndexBannerRes> gameBanners = [];

  ///首页banner
  void loadMainBanner() async {
    try {
      var banners = await SCConfigRepositoryImp().getBanner();
      homeBanners.clear();
      roomBanners.clear();
      gameBanners.clear();
      exploreBanners.clear();
      for (var v in banners) {
        if ((v.displayPosition ?? "").contains(
          SCBannerType.EXPLORE_PAGE.name,
        )) {
          exploreBanners.add(v);
        }
        if ((v.displayPosition ?? "").contains(SCBannerType.ROOM.name)) {
          roomBanners.add(v);
        }

        if ((v.displayPosition ?? "").contains(SCBannerType.HOME_ALERT.name)) {
          homeBanners.add(v);
        }
        if ((v.displayPosition ?? "").contains(SCBannerType.GAME.name)) {
          gameBanners.add(v);
        }
      }
      notifyListeners();
    } catch (e) {}
  }

  Map<String, List<Emojis>> emojiByTab = {};

  ///emoji表情
  void emojiAll() async {
    var roomEmojis = await SCChatRoomRepository().emojiAll();
    for (var value in roomEmojis) {
      emojiByTab[value.groupName!] = value.emojis ?? [];
    }
    notifyListeners();
  }

  ///加载等级资源
  void configLevel() {
    SCConfigRepositoryImp().configLevel();
  }

  SCBannerLeaderboardRes? appLeaderResult;

  ///查询榜单前三名
  void appLeaderboard() async {
    try {
      appLeaderResult = await SCChatRoomRepository().appLeaderboard();
      notifyListeners();
    } catch (e) {}
  }
}
