import 'package:fis_i18n/i18n.dart';
import 'package:fis_common/js_plateform/js_platform.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/widgets/webview/webview.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/services/entity/local_setting.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/managers/interfaces/entities/consultation_member.dart';
import 'package:flyinsono/managers/interfaces/entities/live_course_membel.dart';
import 'package:flyinsono/managers/interfaces/live_consultation.dart';
import 'package:flyinsono/managers/interfaces/live_course.dart';
import 'package:flyinsono/managers/interfaces/webview_controller.dart';
import 'package:flyinsono/managers/server_config_manager.dart';
import 'package:flyinsono/pages/live_course/widgets/expandable_container.dart';
import 'package:flyinsono/pages/live_course/widgets/expandable_toolbar.dart';
import 'package:flyinsono/pages/remote_controller/widgets/remote_controller_parameters/remote_controller_parameters_styles.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/live_consultation/entitys/play_channel.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/live_consultation/widgets/custom_button.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/live_consultation/widgets/member_operates.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/live_consultation/widgets/volume_slider.dart';
import 'package:get/get.dart';
import 'package:fis_common/index.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/live_consultation/state.dart';
import 'package:fis_lib_media_rt/widgets/index.dart';
import 'package:fis_lib_media_rt/interface/index.dart';
import 'package:webviewx/webviewx.dart';
import 'entitys/patient_color.dart';
import 'index.dart';
import 'widgets/live_course_mobile_page.dart';
import 'widgets/member_status.dart';
import 'widgets/normal_live_view.dart';
import 'widgets/set_style.dart';
import 'widgets/share_dialog.dart';

class LiveCoursePage extends FStatefulWidget implements FPage {
  const LiveCoursePage({Key? key}) : super(key: key);

  @override
  String get pageName => "LiveCoursePage";

  @override
  FState<FStatefulWidget> createState() {
    return LiveCoursePageState();
  }
}

class LiveCoursePageState extends FState<LiveCoursePage> {
  final normalBoxDecoration = BoxDecoration(
    border: Border.all(
      color: Colors.grey,
    ),
  );
  CameraStyleEnum _cameraStyleEnum = CameraStyleEnum.Right;
  final textStyle = TextStyle(color: Colors.white);
  final controller = Get.find<LiveCourseController>();
  final webviewControllerManager = Get.find<IWebviewControllerManager>();
  var manager = Get.find<ILiveConsultationManager>();
  static const double _memberWidth = 290;
  static const double _memberHeight = 210;
  double? _allHeight;
  bool _isShowToolbar = false;

  @override
  void initState() {
    controller.memberChange.addListener(_onMemberChange);
    super.initState();
  }

  @override
  void dispose() {
    controller.exitLiveCourse();
    controller.memberChange.removeListener(_onMemberChange);
    controller.onClearCanavsHandler.emit('', Store.user.code);
    webviewControllerManager.disposeWebviewController();
    Get.delete<LiveCourseController>();
    super.dispose();
  }

  @override
  FWidget build(BuildContext context) {
    if (kIsMobile) {
      return LiveCourseMobilePage();
    }
    return FContainer(
      color: TuningParametersStyles.backgroundColor,
      child: FRow(
        children: [
          if (_cameraStyleEnum == CameraStyleEnum.Left) ...[
            _buildMembersView(),
          ],
          FExpanded(
            child: FStack(
              children: [
                _buildMainLiveView(),
                if ([
                  CameraStyleEnum.BottomLeft,
                  CameraStyleEnum.BottomRight,
                  CameraStyleEnum.TopRight,
                  CameraStyleEnum.Topleft
                ].contains(_cameraStyleEnum)) ...[
                  FPositioned(
                    top: (_cameraStyleEnum == CameraStyleEnum.TopRight ||
                            _cameraStyleEnum == CameraStyleEnum.Topleft)
                        ? 0
                        : null,
                    bottom: (_cameraStyleEnum == CameraStyleEnum.BottomLeft ||
                            _cameraStyleEnum == CameraStyleEnum.BottomRight)
                        ? 0
                        : null,
                    left: (_cameraStyleEnum == CameraStyleEnum.BottomLeft ||
                            _cameraStyleEnum == CameraStyleEnum.Topleft)
                        ? 0
                        : null,
                    right: (_cameraStyleEnum == CameraStyleEnum.TopRight ||
                            _cameraStyleEnum == CameraStyleEnum.BottomRight)
                        ? 90
                        : null,
                    child: _buildTeachSmailLiveView(),
                  ),
                ],
                //TODO 将下面两个组件抽取成独立的 statefulWidget，避免每次刷新都会使得 _buildMembersView 和 _buildMessagePoolView 重新渲染
                FExpandableToolbar(
                  toolAreaChild: _buildToolbar(),
                  buttonAreaChild: _buildExitButton(),
                ),
                // _buildSwitchToolBar(),
                // if (_isShowToolbar) ...[
                //   _buildToolbar(),
                // ],
                // _buildExitButton(),
                // _buildStopShareButton(),
                _buildCourseTitle(),
              ],
            ),
          ),
          if (_cameraStyleEnum != CameraStyleEnum.Left) ...[
            _buildMembersView(),
          ],
        ],
      ),
      // child: FObx(() {
      //   // var isAssistants = controller.state.courseDetail?.assistants
      //   //         ?.any((element) => element.code == Store.user.code) ??
      //   //     false;
      //   // if (controller.state.pullUrl.isNotNullOrEmpty) {
      //   //   return NormalLiveView(
      //   //     controller.state.pullUrl!,
      //   //     onRecording: isAssistants ? controller.startRecording : null,
      //   //     onEndRecord: isAssistants ? controller.stopRecording : null,
      //   //   );
      //   // }
      //   return
      // }),
    );
  }

  FWidget _buildMainLiveView() {
    var mainChannel = controller.state.mainChannel;
    var teachMember = controller.state.liveCourseMembers.firstWhereOrNull(
        (e) => e.id == controller.state.courseDetail?.teacherCode);
    bool isTeacherLeft = teachMember?.memberStatus == MemberStatus.Left;
    FWidget child;
    if (mainChannel == null) {
      child = FCenter(
        child: FColumn(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (controller.state.isLocalDesktopShare) ...[
              FText(
                i18nBook.college.desktopShare.t,
                style: TextStyle(color: Colors.white),
              ),
            ] else ...[
              FText(
                isTeacherLeft
                    ? i18nBook.college.teacherAway.t
                    : i18nBook.college.selectLiveContent.t,
                style: TextStyle(color: Colors.white),
              ),
              const FSizedBox(height: 25),
              FRow(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  _iconTextButton(i18nBook.college.desktopSharing.t,
                      Icons.desktop_windows_outlined,
                      onTap: controller.desktopShare),
                  const FSizedBox(width: 50),
                  _iconTextButton(i18nBook.college.ultrasoundSharing.t,
                      Icons.screen_share_outlined,
                      onTap: controller.ultrasoundShare),
                ],
              ),
            ],
          ],
        ),
      );
    } else {
      FWidget channelView;
      FLiveCourseMember? device = controller.state.liveCourseMembers
          .firstWhereOrNull(
              (element) => element.memberType == LiveMemberEnum.Device);
      if (controller.state.isMergedMode) {
        if (device != null) {
          channelView = QuickFWidget(
            _buildMainViewInMergedMode(device),
          );
        } else {
          channelView = FSizedBox();
        }
      } else {
        Size viewSize = Size(1920, 1080);
        if (device != null &&
            device.videoDeviceInfos != null &&
            device.videoDeviceInfos!.isNotEmpty) {
          viewSize = Size(
            manager.getVideoDeviceInfoWidth(
                videoDeviceInfos: device.videoDeviceInfos!),
            manager.getVideoDeviceInfoHeight(
                videoDeviceInfos: device.videoDeviceInfos!),
          );
        }
        channelView = QuickFWidget(
          FRTDeviceChannelView(
            mainChannel as IPlayChannel,
            viewSize: viewSize,
          ),
        );
      }
      child = FStack(
        children: [
          FPositioned(
            child: QuickFWidget(channelView),
          ),
          _buildWhiteboardView(),
        ],
      );
    }
    return FContainer(
      width: double.infinity,
      color: Colors.black,
      child: child,
    );
  }

  FWidget _buildToolbar() {
    return FContainer(
      height: 80,
      width: double.infinity,
      alignment: Alignment.center,
      color: Colors.black.withOpacity(0.5),
      child: FRow(
        children: [
          FExpanded(
            child: FRow(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _iconTextButton(
                  i18nBook.measure.clear.t,
                  Icons.delete,
                  onTap: () {
                    controller.onClearCanavsHandler.emit(this, Store.user.code);
                    controller.sendInteractiveBoardData('', isClear: true);
                  },
                ),
                if (controller.state.courseDetail?.isSmallClass == false) ...[
                  _iconTextButton(i18nBook.college.styleSetting.t,
                      Icons.auto_awesome_mosaic_outlined, onTap: () {
                    router.dialog(
                      () => SetCammeraStyle((v) {
                        router.back();
                        setState(() {
                          _cameraStyleEnum = v;
                        });
                      }),
                    );
                  }),
                ],
                VolumeSlider(
                  child: _iconTextButton(
                      i18nBook.setting.speaker.t, Icons.volume_up_outlined),
                  onVolumeChanged: (v) {
                    controller.setVolume(v);
                  },
                ),
                _iconTextButton(i18nBook.college.share.t, Icons.share,
                    onTap: () {
                  var url = controller.state.courseDetail!.courseShareUrl;
                  router.dialog(() => ShareDialog(url ?? ''));
                }),
              ],
            ),
          ),
        ],
      ),
    );
  }

  FWidget _iconTextButton(String text, IconData icon,
      {void Function()? onTap}) {
    return FMouseRegion(
      cursor: SystemMouseCursors.click,
      child: FGestureDetector(
        businessParent: widget,
        name: text,
        onTap: onTap,
        child: FContainer(
          decoration: BoxDecoration(),
          alignment: Alignment.center,
          width: 75,
          child: FColumn(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              FIcon(
                icon,
                color: Colors.white,
              ),
              FSizedBox(height: 5),
              FText(
                text,
                style: TextStyle(color: Colors.white),
              ),
            ],
          ),
        ),
      ),
    );
  }

  FWidget _buildTeachSmailLiveView() {
    return FObx(() {
      var member = controller.state.liveCourseMembers
          .firstWhereOrNull((element) => element.isTeacher);
      return _buildSmailLiveView(member);
    });
  }

  FWidget _buildSmailLiveView(FLiveCourseMember? member) {
    return FContainer(
      width: _memberWidth,
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(
            width: 1.0,
            color: Colors.white,
          ),
        ),
      ),
      child: FColumn(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          FContainer(
            margin: EdgeInsets.symmetric(horizontal: 10),
            child: FRow(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                FText(
                  member?.name ?? '',
                  style: textStyle,
                ),
                FIcon(
                  Icons.circle,
                  color: PatientColor.patientColors[member?.index ?? 0],
                  size: 14,
                ),
              ],
            ),
          ),
          if (member == null) ...[
            FSizedBox(
              height: 190,
              child: FCenter(
                child: FSizedBox(
                  height: 36,
                  child: FCircularProgressIndicator(),
                ),
              ),
            ),
          ] else ...[
            _buildChannelItem(member),
          ],
          MemberAudioOperates(
            RoomMember(
              member == null ? "" : member.id!,
              mute: member?.mute ?? false,
              videoOpend: member?.videoOpend ?? true,
            ),
            channelInfo: (member == null || member.channelInfos == null)
                ? null
                : PlayChannelInfo(member.channelInfos!.first),
            setAudioMute: (isMute, code) {
              controller.setAudioMute(isMute, code);
            },
            setMicrophone: (isMute) async {
              controller.setAudioOpend(isMute);
              setState(() {});
              return true;
            },
            setVideoOpend: (isOpened) async {
              if (member != null) {
                setState(() {
                  member.videoOpend = isOpened;
                });
                controller.setVideoOpend(isOpened);
              }
              return true;
            },
          ),
        ],
      ),
    );
  }

  FWidget _buildChannelItem(FLiveCourseMember member) {
    var playChannelInfos = member.channelInfos;
    if (playChannelInfos == null) {
      return _buildUserHeadImage(member);
    }
    var channel = playChannelInfos.first;
    Widget channelView;
    if (channel is IPublishChannel) {
      channelView = FRTPublishPreviewView(
        channel,
      );
    } else {
      channelView = FRTPlayChannelView(
        channel as IPlayChannel,
      );
    }
    var child = QuickFWidget(
      Container(
        height: _memberHeight,
        width: _memberWidth,
        child: channelView,
      ),
    );
    if (member.videoOpend && member.memberStatus == MemberStatus.Joined) {
      return child;
    }
    return FStack(
      children: [
        child,
        _buildUserHeadImage(member),
      ],
    );
  }

  FWidget _buildUserHeadImage(FLiveCourseMember member) {
    var headImageToken = member.headImageToken ?? '';
    FWidget child;
    if (headImageToken.isEmpty) {
      child = FImage(
        image: AssetImage("assets/images/avatar_man.jpg"),
        fit: BoxFit.cover,
        height: _memberHeight,
      );
    } else {
      child = FImage.network(
        headImageToken,
        fit: BoxFit.fill,
        height: _memberHeight,
      );
    }
    return FStack(
      children: [
        FContainer(
          width: _memberWidth,
          child: child,
        ),
        MemberStatusView(member.memberStatus),
      ],
    );
  }

  FWidget _buildStudentSmailLiveView() {
    if (controller.state.liveCourseMembers.length <= 1) {
      return FSizedBox();
    }
    List<FLiveCourseMember> members = controller.state.liveCourseMembers
        .where((element) =>
            !element.isTeacher &&
            element.memberType != LiveMemberEnum.Device &&
            element.id.isNotNullOrEmpty)
        .toList();

    if (members.isEmpty) {
      return FSizedBox();
    }
    List<FWidget> children = [];
    var localMember = members.firstWhereOrNull(
        (e) => e.id == Store.user.code && e.id != controller.state.teacherCode);
    if (localMember != null) {
      children.add(_buildSmailLiveView(localMember));
    }
    //非本人的所有成员
    var otherMembers = members.where((e) =>
        e.id != Store.user.code &&
        e.id != controller.state.teacherCode &&
        e.memberType != LiveMemberEnum.Device);
    //已加入的成员
    var otherOnlineMembers =
        otherMembers.where((e) => e.memberStatus == MemberStatus.Joined);
    for (var m in otherOnlineMembers) {
      children.add(_buildSmailLiveView(m));
    }
    //未加入且未离开的成员
    var otherNotOnlineMembers = otherMembers.where((element) =>
        element.memberStatus != MemberStatus.Joined &&
        element.memberStatus != MemberStatus.Left);
    for (var m in otherNotOnlineMembers) {
      children.add(_buildSmailLiveView(m));
    }
    //已离开的成员
    var otherLeftMembers = otherMembers
        .where((element) => element.memberStatus == MemberStatus.Left);
    for (var m in otherLeftMembers) {
      children.add(_buildSmailLiveView(m));
    }
    return FColumn(
      children: children,
    );
  }

  FWidget _buildMessagePoolView() {
    return FObx(
      () {
        if (controller.state.courseCode.isNullOrEmpty) {
          return FContainer();
        }
        double height = 585;
        if (_allHeight != null && _allHeight! > 568) {
          var members = controller.state.liveCourseMembers
              .where((element) => element.memberType == LiveMemberEnum.User);
          if (members.length <= 1 || _allHeight! < 900) {
            height = _allHeight! - 313;
          } else {
            height = _allHeight! - 568;
          }
        }
        // final url =
        //     'http://localhost:5173/#/discussionBoard/${controller.state.courseCode}/${Store.user.token}/${i18nBook.locale.languageCode.toLowerCase()}';
        final url =
            '${ServerConfigManager.flyinsonoSchoolUrl}discussionBoard/${controller.state.courseCode}/${Store.user.token}/${i18nBook.locale.languageCode.toLowerCase()}';
        return FContainer(
          height: (_cameraStyleEnum != CameraStyleEnum.Left &&
                  _cameraStyleEnum != CameraStyleEnum.Right)
              ? MediaQuery.of(context).size.height - 61
              : height,
          decoration: normalBoxDecoration,
          child: FLayoutBuilder(
            key: UniqueKey(),
            builder: (context, constraints) {
              final webview = FWebViewX(
                height: constraints.maxHeight,
                width: constraints.maxWidth,
                initialContent: url,
                initialSourceType: SourceType.url,
                javascriptMode: JavascriptMode.unrestricted,
                ignoreAllGestures: false,
                onWebViewCreated: (controller) {
                  webviewControllerManager.initWebviewController(controller);
                },
              );
              return FContainer(
                height: MediaQuery.of(context).size.height,
                width: MediaQuery.of(context).size.width,
                child: webview,
              );
            },
          ),
        );
      },
    );
  }

  void _onMemberChange(Object sender, e) {
    setState(() {});
  }

  FWidget _buildMembersView() {
    return FContainer(
      width: _memberWidth,
      decoration: BoxDecoration(border: Border.all(color: Colors.white)),
      child: FLayoutBuilder(builder: (context, constraint) {
        _allHeight = constraint.maxHeight;
        return FColumn(
          children: [
            FExpanded(
              child: FListView(
                children: [
                  if (_cameraStyleEnum == CameraStyleEnum.Left ||
                      _cameraStyleEnum == CameraStyleEnum.Right) ...[
                    _buildTeachSmailLiveView(),
                  ],
                  _buildStudentSmailLiveView(),
                ],
              ),
            ),
            FContainer(
              decoration: BoxDecoration(
                border: Border(
                  top: BorderSide(
                    width: 1.0,
                    color: Colors.white,
                  ),
                ),
              ),
              child: FExpandableContainer(
                child: _buildMessagePoolView(),
                headerTitle: i18nBook.college.interactionArea.t,
              ),
            ),
          ],
        );
      }),
    );
  }

  FWidget _buildExitButton() {
    if (controller.state.isLocalDesktopShare ||
        controller.state.isDeviceShare) {
      return FContainer(
        width: 120,
        color: Colors.black.withOpacity(0.5),
        alignment: Alignment.centerRight,
        child: FCustomExitButton(
          i18nBook.college.stopSharing.t,
          Icons.stop,
          () async {
            final liveCourseManager = Get.find<ILiveCourseManager>();
            await liveCourseManager.setShareInLiveCourse(
              controller.state.courseCode,
              controller.state.isLocalDesktopShare
                  ? Store.user.code
                  : controller.state.deviceCode!,
              currentShareType: controller.state.isLocalDesktopShare
                  ? CourseShareType.Window
                  : CourseShareType.US,
              currentShareState: CourseShareStates.Closed,
            );
            controller.mediaController.stopScreenCapture();
            controller.state.mainChannel = null;
            setState(() {
              controller.state.isLocalDesktopShare = false;
              controller.state.isDeviceShare = false;
            });
          },
          normalColor: Colors.transparent,
        ),
      );
    }
    return FContainer(
      width: 120,
      color: Colors.black.withOpacity(0.5),
      alignment: Alignment.centerRight,
      child: FCustomExitButton(
        i18nBook.college.exitLive.t,
        Icons.exit_to_app,
        () {
          if ((FPlatform.isMacOS || FPlatform.isWindows) &&
              LocalSetting.ins.isUseSecondWindow!) {
            ///第二窗口直接关闭第二窗口
            JSPlateForm.closeSlaveWindow();
            return;
          }
          FConfirmAlert.show(
            context: Get.context!,
            title: i18nBook.common.tip.t,
            subTitle: i18nBook.common.leaveCurrentPage.t,
            businessParent: widget,
            confrimLabel: i18nBook.common.confirm.t,
            cancelLabel: i18nBook.common.cancel.t,
            onConfirm: () {
              controller.exitLiveCourse();
            },
          );
        },
        normalColor: Colors.transparent,
      ),
    );
  }

  FWidget _buildWhiteboardView() {
    var localMember = controller.state.liveCourseMembers
        .firstWhereOrNull((e) => e.id == Store.user.code);
    if (localMember == null) {
      return FSizedBox();
    }
    return FWhiteBoard(
      sendData: (value) {
        controller.sendInteractiveBoardData(value);
      },
      patientColor: PatientColor.patientColors[localMember.index],
      paintType: PaintType.curvedLine,
      userId: Store.user.code,
      onReceiveData: controller.onReceiveData,
      onClearCanavs: controller.onClearCanavsHandler,
      initData: controller.initBoardDatas ?? [],
    );
  }

  FWidget _buildCourseTitle() {
    return FPositioned(
      left: 10,
      top: 10,
      child: FText(
        controller.state.courseDetail?.name ?? '',
        style: TextStyle(color: Colors.grey[400], fontSize: 20),
      ),
    );
  }

  Widget _buildMainViewInMergedMode(FLiveCourseMember device) {
    return LayoutBuilder(builder: (context, constraint) {
      return Center(
        child: AspectRatio(
          aspectRatio: manager.getVideoDeviceInfoWidth(
                  videoDeviceInfos: device.videoDeviceInfos!) /
              manager.getVideoDeviceInfoHeight(
                  videoDeviceInfos: device.videoDeviceInfos!),
          child: FRTMergedChannelView(
            controller.state.mainChannel! as IPlayChannel,
            isSubView: false,
            mainViewContainerMaxSize: Size(
              constraint.maxWidth,
              constraint.maxHeight,
            ),
            videoSize: Size(
              device.mergedVideoOutputWidth.toDouble(),
              device.mergedVideoOutputHeight.toDouble(),
            ),
            viewSize: Size(
              manager.getVideoDeviceInfoWidth(
                  videoDeviceInfos: device.videoDeviceInfos!),
              manager.getVideoDeviceInfoHeight(
                  videoDeviceInfos: device.videoDeviceInfos!),
            ),
            viewAlignment: Alignment.topLeft,
          ),
        ),
      );
    });
  }
}
