import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:yumi/app/constants/sc_global_config.dart';
import 'package:yumi/shared/tools/sc_message_utils.dart';
import 'package:yumi/shared/tools/sc_room_utils.dart';
import 'package:yumi/shared/data_sources/sources/local/data_persistence.dart';
import 'package:yumi/main.dart';
import 'package:provider/provider.dart';
import 'package:yumi/app/routes/sc_fluro_navigator.dart';
import 'package:yumi/shared/business_logic/models/res/login_res.dart';
import 'package:yumi/modules/auth/login_route.dart';
import 'package:yumi/services/audio/rtc_manager.dart';
import 'package:yumi/services/audio/rtm_manager.dart';
import 'package:yumi/shared/data_sources/sources/local/floating_screen_manager.dart';

import '../../../tools/sc_heartbeat_utils.dart';
import '../../models/enum/sc_props_type.dart';

typedef UserManager = AccountStorage;

class AccountStorage {
  static AccountStorage? _instance;

  AccountStorage._internal();

  factory AccountStorage() {
    return _instance ??= AccountStorage._internal();
  }

  String token = "";
  SocialChatLoginRes? _currentUser;

  ///获取当前用户
  SocialChatLoginRes? getCurrentUser() {
    if (_currentUser != null) {
      return _currentUser;
    }
    var userJson = DataPersistence.getCurrentUser();
    if (userJson.isNotEmpty) {
      _currentUser = SocialChatLoginRes.fromJson(jsonDecode(userJson));
    }
    return _currentUser;
  }

  ///同步优化数据
  void setCurrentUser(SocialChatLoginRes user) {
    _currentUser = user;
    setToken(_currentUser!.token ?? "");
    String userJson = jsonEncode(_currentUser?.toJson());
    if (userJson.isNotEmpty) {
      DataPersistence.setCurrentUser(userJson);
    }
  }

  ///获取自己佩戴的头饰信息
  PropsResources? getHeaddress() {
    PropsResources? pr;
    _currentUser?.userProfile?.useProps?.forEach((value) {
      if (value.propsResources?.type == SCPropsType.AVATAR_FRAME.name) {
        ///判断有没有过期
        if (int.parse(value.expireTime ?? "0") >
            DateTime
                .now()
                .millisecondsSinceEpoch) {
          pr = value.propsResources;
        }
      }
    });
    return pr;
  }

  ///获取自己佩戴的气泡框
  PropsResources? getChatbox() {
    PropsResources? pr;
    _currentUser?.userProfile?.useProps?.forEach((value) {
      if (value.propsResources?.type == SCPropsType.CHAT_BUBBLE.name) {
        ///判断有没有过期
        if (int.parse(value.expireTime ?? "0") >
            DateTime
                .now()
                .millisecondsSinceEpoch) {
          pr = value.propsResources;
        }
      }
    });
    return pr;
  }

  ///获取自己佩戴的坐骑信息
  PropsResources? getMountains() {
    PropsResources? pr;
    _currentUser?.userProfile?.useProps?.forEach((value) {
      if (value.propsResources?.type == SCPropsType.RIDE.name) {
        ///判断有没有过期
        if (int.parse(value.expireTime ?? "0") >
            DateTime
                .now()
                .millisecondsSinceEpoch) {
          pr = value.propsResources;
        }
      }
    });
    return pr;
  }

  ///获取自己资料卡信息
  PropsResources? getDataCard() {
    PropsResources? pr;
    _currentUser?.userProfile?.useProps?.forEach((value) {
      if (value.propsResources?.type == SCPropsType.DATA_CARD.name) {
        ///判断有没有过期
        if (int.parse(value.expireTime ?? "0") >
            DateTime.now().millisecondsSinceEpoch) {
          pr = value.propsResources;
        }
      }
    });
    return pr;
  }

  String getToken() {
    if (token.isNotEmpty) {
      return token;
    }
    token = DataPersistence.getToken();
    return token;
  }

  void setToken(String tk) {
    token = tk;
    DataPersistence.setToken(token);
  }

  void _cleanUser() {
    token = "";
    _currentUser = null;
    DataPersistence.setToken("");
    DataPersistence.setCurrentUser("");
  }

  ///退出登录
  void logout(BuildContext context) {
    _cleanUser();
    SCHeartbeatUtils.cancelTimer();
    Provider.of<RtcProvider>(context, listen: false).exitCurrentVoiceRoomSession(true);
    Provider.of<RtmProvider>(context, listen: false).logout();
    SCNavigatorUtils.push(context, LoginRouter.login, clearStack: true);
    SCRoomUtils.closeAllDialogs();
    SCMessageUtils.redPacketFutureCache.clear();
    SCGlobalConfig.isEntryVehicleAnimation = true;
    SCGlobalConfig.isGiftSpecialEffects = true;
    SCGlobalConfig.isFloatingAnimationInGlobal = true;
    SCGlobalConfig.isLuckGiftSpecialEffects = true;
    OverlayManager().dispose();
  }
}
