import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:yumi/shared/business_logic/models/res/login_res.dart';
import 'package:provider/provider.dart';
import 'package:yumi/app_localizations.dart';
import 'package:yumi/shared/data_sources/sources/local/data_persistence.dart';
import 'package:yumi/shared/data_sources/sources/local/user_manager.dart';
import 'package:yumi/modules/wallet/wallet_route.dart';
import 'package:yumi/modules/room/voice_room_route.dart';
import 'package:yumi/services/audio/rtc_manager.dart';
import 'package:yumi/services/auth/user_profile_manager.dart';
import 'package:yumi/ui_kit/components/sc_float_ichart.dart';
import 'package:yumi/ui_kit/components/text/sc_text.dart';
import 'package:yumi/ui_kit/components/sc_tts.dart';
import 'package:yumi/app/constants/sc_global_config.dart';
import 'package:yumi/app/routes/sc_fluro_navigator.dart';
import 'package:yumi/shared/tools/sc_lk_dialog_util.dart';


typedef SCRoomUtils = SCChatRoomHelper;

class SCChatRoomHelper {
  static Map<String, SocialChatUserProfile> roomUsersMap = {};

  static void goRoom(String roomId,
      BuildContext context, {
        bool needOpenRedenvelope = false,
        bool fromFloting = false,
        String redPackId = "",
      }) {
    if (Provider
        .of<RealTimeCommunicationManager>(context, listen: false)
        .currenRoom != null) {
      if (SCFloatIchart().isShow()) {
        ///房间最小化了
        if (Provider
            .of<RealTimeCommunicationManager>(
          context,
          listen: false,
        )
            .currenRoom
            ?.roomProfile
            ?.roomProfile
            ?.id ==
            roomId) {
          SCRoomUtils.openCurrentRoom(
            context,
            needOpenRedenvelope: needOpenRedenvelope,
            redPackId: redPackId,
          );
        } else {
          showEnterRoomConfirm(
            roomId,
            context,
            needOpenRedenvelope: needOpenRedenvelope,
            fromFloting: fromFloting,
            redPackId: redPackId,
          );
        }
      } else {
        if (Provider
            .of<RealTimeCommunicationManager>(
          context,
          listen: false,
        )
            .currenRoom
            ?.roomProfile
            ?.roomProfile
            ?.id ==
            roomId) {

        } else {
          showEnterRoomConfirm(
            roomId,
            context,
            needOpenRedenvelope: needOpenRedenvelope,
            fromFloting: fromFloting,
            redPackId: redPackId,
          );
        }
      }
    } else {
      showEnterRoomConfirm(
        roomId,
        context,
        needOpenRedenvelope: needOpenRedenvelope,
        fromFloting: fromFloting,
        redPackId: redPackId,
      );
    }
  }

  static void openCurrentRoom(BuildContext context, {
    bool needOpenRedenvelope = false,
    String? redPackId,
  }) {
    SCFloatIchart().remove();
    Provider.of<RealTimeCommunicationManager>(context, listen: false)
        .loadRoomInfo(
      Provider
          .of<RealTimeCommunicationManager>(
        context,
        listen: false,
      )
          .currenRoom
          ?.roomProfile
          ?.roomProfile
          ?.id ??
          "",
    );
    Provider.of<SocialChatUserProfileManager>(context, listen: false)
        .fetchUserProfileData();
    Provider.of<RealTimeCommunicationManager>(context, listen: false)
        .retrieveMicrophoneList();
    Provider
        .of<RealTimeCommunicationManager>(context, listen: false)
        .closeFullGame = true;
    SCNavigatorUtils.push(
      context,
      '${VoiceRoomRoute.voiceRoom}?id=${Provider
          .of<RealTimeCommunicationManager>(context, listen: false)
          .currenRoom
          ?.roomProfile
          ?.roomProfile
          ?.id}',
    );

  }

  static double getCurrenProgress(int currentEnergy,
      int maxEnergy,
      double maxWidth,) {
    var progress = (currentEnergy / maxEnergy);
    var curren = progress * maxWidth;
    if (curren > maxWidth) {
      return maxWidth;
    } else {
      return curren;
    }
  }

  static void goRecharge(BuildContext context) {
    SmartDialog.dismiss(tag: "showGoToRecharge");
    SmartDialog.show(
      tag: "showGoToRecharge",
      alignment: Alignment.center,
      animationType: SmartAnimationType.fade,
      builder: (_) {
        return Container(
          width: ScreenUtil().screenWidth * 0.75,
          height: 120.w,
          padding: EdgeInsets.symmetric(horizontal: 10.w),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(12.w)),
          ),
          child: Column(
            children: [
              SizedBox(height: 8.w),
              Row(
                children: [
                  Spacer(),
                  GestureDetector(
                    child: Icon(
                      Icons.close,
                      color: Colors.black,
                      size: 20.w,
                    ),
                    onTap: () {
                      SmartDialog.dismiss(tag: "showGoToRecharge");
                    },
                  ),
                  SizedBox(width: 10.w),
                ],
              ),
              Row(
                children: [
                  Expanded(
                    child: text(
                      SCAppLocalizations.of(
                        context,
                      )!.insufhcientGoldsGoToRecharge,
                      textColor: Colors.black,
                      textAlign: TextAlign.center,
                      fontSize: 13.sp,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ],
              ),
              SizedBox(height: 10.w),
              GestureDetector(
                child: Container(
                  alignment: Alignment.center,
                  height: 38.w,
                  width: 125.w,
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [
                        Color(0xFFFEB219),
                        Color(0xFFFF9326),
                      ],
                    ),
                    borderRadius: BorderRadius.all(Radius.circular(8.w)),
                  ),
                  child: text(
                    SCAppLocalizations.of(context)!.goToRecharge,
                    textColor: Colors.white,
                    fontSize: 13.sp,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                onTap: () {
                  closeAllDialogs();
                  SCNavigatorUtils.push(
                    context,
                    WalletRoute.recharge,
                    replace: false,
                  );
                },
              ),
            ],
          ),
        );
      },
    );
  }

  static int getRandomInt(int min, int max) {
    final random = Random();
    return min + random.nextInt(max - min + 1);
  }

  ///房间游客是否可以发消息
  static bool touristCanMsg(BuildContext context) {
    ///游客可以发送文字
    if (Provider
        .of<RealTimeCommunicationManager>(
      context,
      listen: false,
    )
        .currenRoom
        ?.roomProfile
        ?.roomSetting
        ?.touristMsg ??
        false) {} else {
      if (Provider.of<RealTimeCommunicationManager>(context, listen: false)
          .isTourists()) {
        SCTts.show(SCAppLocalizations.of(context)!.touristsCannotSendMessages);
        return false;
      }
    }
    return true;
  }

  static void roomSCGlobalConfig(String roomId) {
    SCGlobalConfig.isGiftSpecialEffects = DataPersistence.getBool(
      "${AccountStorage()
          .getCurrentUser()
          ?.userProfile
          ?.account}-GiftSpecialEffects",
      defaultValue: true,
    );
    SCGlobalConfig.isEntryVehicleAnimation = DataPersistence.getBool(
      "${AccountStorage()
          .getCurrentUser()
          ?.userProfile
          ?.account}-EntryVehicleAnimation",
      defaultValue: true,
    );
    SCGlobalConfig.isFloatingAnimationInGlobal = DataPersistence.getBool(
      "${AccountStorage()
          .getCurrentUser()
          ?.userProfile
          ?.account}-FloatingAnimationInGlobal",
      defaultValue: true,
    );
    SCGlobalConfig.isLuckGiftSpecialEffects = DataPersistence.getBool(
      "${AccountStorage()
          .getCurrentUser()
          ?.userProfile
          ?.account}-LuckGiftSpecialEffects",
      defaultValue: true,
    );
    DataPersistence.setLastTimeRoomId(roomId);
  }

  static void closeAllDialogs() async {
    // 循环检查并关闭弹窗，直到不存在任何弹窗
    while (SmartDialog.checkExist(
      dialogTypes: {SmartAllDialogType.custom, SmartAllDialogType.attach},
    )) {
      SmartDialog.dismiss();
      await Future.delayed(const Duration(milliseconds: 50));
    }
  }


}
