import 'package:agora_rtc_engine/agora_rtc_engine.dart';
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/ui_kit/widgets/room/room_menu_dialog.dart';
import 'package:yumi/ui_kit/widgets/room/room_msg_input.dart';
import 'package:provider/provider.dart';
import 'package:yumi/app_localizations.dart';
import 'package:yumi/ui_kit/components/text/sc_text.dart';
import 'package:yumi/shared/tools/sc_room_utils.dart';
import 'package:yumi/shared/data_sources/sources/local/user_manager.dart';
import 'package:yumi/services/audio/rtc_manager.dart';
import 'package:yumi/modules/gift/gift_page.dart';

import '../../../app/routes/sc_fluro_navigator.dart';
import '../../../modules/index/main_route.dart';
import '../../../services/audio/rtm_manager.dart';
import '../../components/sc_debounce_widget.dart';

class RoomBottomWidget extends StatefulWidget {
  @override
  _RoomBottomWidgetState createState() => _RoomBottomWidgetState();
}

class _RoomBottomWidgetState extends State<RoomBottomWidget> {
  int roomMenuStime1 = 0;

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.center,
      children: [
        Container(
          height: 55.w,
          margin: EdgeInsetsDirectional.only(start: 25.w),
          child: Row(
            children: [
              SCDebounceWidget(
                onTap: () {
                  if (SCRoomUtils.touristCanMsg(context)) {
                    Navigator.push(
                      context,
                      PopRoute(child: RoomMsgInput()),
                    );
                  }
                }, child: Image.asset(
                "sc_images/room/icon_room_input_t.png",
                width: 30.w,
                height: 30.w,
              ),
              ),
              Spacer(),
              Consumer<RtcProvider>(
                builder: (context, ref, child) {
                  return _mic1(ref);
                },
              ),
              SizedBox(width: 10.w),
              SCDebounceWidget(
                child: Image.asset(
                  "sc_images/room/sc_icon_botton_menu.png",
                  width: 30.w,
                  height: 30.w,
                  fit: BoxFit.contain,
                ),
                onTap: () {
                  SmartDialog.show(
                    tag: "showRoomMenuDialog",
                    alignment: Alignment.bottomCenter,
                    debounce: true,
                    animationType: SmartAnimationType.fade,
                    maskColor: Colors.transparent,
                    clickMaskDismiss: true,
                    builder: (_) {
                      return RoomMenuDialog(roomMenuStime1, (eTime) {
                        roomMenuStime1 = eTime;
                      });
                    },
                  );
                },
              ),
              SizedBox(width: 10.w),
              SCDebounceWidget(
                child: Selector<RtmProvider, int>(
                  selector: (c, p) => p.allUnReadCount,
                  shouldRebuild: (prev, next) => prev != next,
                  builder: (_, allUnReadCount, __) {
                    return allUnReadCount > 0
                        ? Badge(
                          backgroundColor: Colors.red,
                          label: text(
                            "${allUnReadCount > 99 ? "99+" : allUnReadCount}",
                            fontSize: 9.sp,
                            textColor: Colors.white,
                            fontWeight: FontWeight.w600,
                          ),
                          alignment: AlignmentDirectional.topEnd,
                          child: Image.asset(
                            "sc_images/room/sc_icon_botton_message.png",
                            width: 30.w,
                            height: 30.w,
                            fit: BoxFit.contain,
                          ),
                        )
                        : Image.asset(
                          "sc_images/room/sc_icon_botton_message.png",
                          width: 30.w,
                          height: 30.w,
                          fit: BoxFit.contain,
                        );
                  },
                ),
                onTap: () {
                  SCNavigatorUtils.push(
                    context,
                    "${SCMainRoute.message}?isFromRoom=true",
                  );
                },
              ),
              SizedBox(width: 15.w),
            ],
          ),
        ),
        PositionedDirectional(
          bottom: 8.w,
          child: SCDebounceWidget(
            onTap: () {
              SmartDialog.show(
                tag: "showGiftControl",
                alignment: Alignment.bottomCenter,
                maskColor: Colors.transparent,
                animationType: SmartAnimationType.fade,
                clickMaskDismiss: true,
                builder: (_) {
                  return GiftPage();
                },
              );
            },
            child: Image.asset(
              "sc_images/room/sc_icon_botton_gift.png",
              width: 45.w,
              height: 45.w,
              fit: BoxFit.contain,
            ),
          ),
        ),
      ],
    );
  }

  _mic1(RtcProvider provider) {
    ///默认不显示
    bool show = false;

    ///在麦上
    provider.roomWheatMap.forEach((k, v) {
      if (v.user?.id == AccountStorage().getCurrentUser()?.userProfile?.id) {
        show = true;
      }
    });

    return Visibility(
      visible: show,
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          setState(() {
            provider.isMic = !provider.isMic;

            ///没被禁麦才显示
            provider.roomWheatMap.forEach((k, v) {
              if (v.user?.id ==
                      AccountStorage().getCurrentUser()?.userProfile?.id &&
                  !provider.roomWheatMap[k]!.micMute!) {
                if (!provider.isMic) {
                  Provider.of<RtcProvider>(
                    context,
                    listen: false,
                  ).engine?.adjustRecordingSignalVolume(100);
                  Provider.of<RtcProvider>(
                    context,
                    listen: false,
                  ).engine?.setClientRole(
                    role: ClientRoleType.clientRoleBroadcaster,
                  );
                } else {
                  if (Provider.of<RtcProvider>(
                    context,
                    listen: false,
                  ).isMusicPlaying) {
                    Provider.of<RtcProvider>(
                      context,
                      listen: false,
                    ).engine?.adjustRecordingSignalVolume(0);
                  } else {
                    Provider.of<RtcProvider>(
                      context,
                      listen: false,
                    ).engine?.setClientRole(
                      role: ClientRoleType.clientRoleAudience,
                    );
                    Provider.of<RtcProvider>(
                      context,
                      listen: false,
                    ).engine?.muteLocalAudioStream(provider.isMic);
                  }
                }
              }
            });
          });
        },
        child: Padding(
          padding: EdgeInsets.only(right: 12.w),
          child: Container(
            width: 30.w,
            height: 30.w,
            alignment: Alignment.center,
            // decoration: BoxDecoration(
            //     color: Colors.white.withOpacity(0.2), shape: BoxShape.circle
            // ),
            child: Image.asset(
              "sc_images/room/${provider.isMic ? 'sc_icon_botton_mic_close' : 'sc_icon_botton_mic_open'}.png",
              width: 30.w,
              fit: BoxFit.fill,
              gaplessPlayback: true,
            ),
          ),
        ),
      ),
    );
  }
}
