import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_measure/view/measure/measure_images_bar.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/router.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/pages/live_course/entitys/patient_color.dart';
import 'package:flyinsono/pages/live_course/index.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/member_operates.dart';
import 'package:get/get.dart';
import 'package:fis_lib_media_rt/interface/index.dart';
import 'package:fis_lib_media_rt/widgets/index.dart';
import 'member_status.dart';
import 'share_dialog.dart';

class LiveCourseMobilePage extends FStatefulWidget implements FPage {
  @override
  String get pageName => "LiveCourseMobilePage";

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

class _LiveCourseMobileState extends FState<LiveCourseMobilePage> {
  final controller = Get.find<LiveCourseController>();
  static const double _memberListWidth = 180;
  final double _smallLiveViewHeight = 100;
  final TextStyle _memberTextStyle = TextStyle(color: Colors.white);
  final ScrollController scrollController = ScrollController();
  var manager = Get.find<ILiveConsultationManager>();
  @override
  void initState() {
    ///强制横屏
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
    super.initState();
  }

  @override
  void dispose() {
    // 强制竖屏
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
    Get.delete<LiveCourseController>();
    super.dispose();
  }

  @override
  FWidget build(BuildContext context) {
    return FContainer(
      color: Colors.black,
      child: FSafeArea(
        child: FRow(
          children: [
            _buildMembersView(),
            _buildMainLiveView(),
          ],
        ),
      ),
    );
  }

  FWidget _buildMembersView() {
    List<FWidget> children = [];
    var members = controller.state.liveCourseMembers;
    var teacher = members.firstWhereOrNull(
        (e) => e.id == controller.state.courseDetail?.teacherCode);
    if (teacher != null) {
      children.add(_buildSmailLiveView(teacher));
    }
    var localMember = members.firstWhereOrNull((e) => e.id == Store.user.code);
    if (localMember != null && localMember.id != teacher?.id) {
      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 FContainer(
      width: _memberListWidth,
      alignment: Alignment.topCenter,
      margin: EdgeInsets.only(top: 2),
      child: FAlwaysScrollListView(
        scrollController: scrollController,
        child: QuickFWidget(ScrollConfiguration(
          behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
          child: FListView(
            padding: EdgeInsets.only(right: 5),
            controller: scrollController,
            shrinkWrap: true,
            children: children,
          ),
        )),
      ),
    );
  }

  FWidget _buildMainLiveView() {
    if (controller.state.mainChannel == null) {
      return _shareContentTips();
    }
    var deviceMember = controller.state.liveCourseMembers.firstWhereOrNull(
        (element) => element.memberType == LiveMemberEnum.Device);
    double width = 1280;
    double height = 720;
    if (deviceMember != null && deviceMember.videoDeviceInfos != null) {
      var desktop = deviceMember.videoDeviceInfos!.firstWhereOrNull((element) =>
          element.videoDeviceSourceType == VideoDeviceSourceTypeEnum.Desktop);
      if (desktop != null) {
        width = desktop.outputWidth.toDouble();
        height = desktop.outputHeight.toDouble();
      }
    }
    return FExpanded(
      child: FStack(
        children: [
          if (controller.state.isLoadingDevice) ...[
            FPositioned(
              left: 0,
              top: 0,
              bottom: 0,
              right: 0,
              child: FContainer(
                alignment: Alignment.center,
                width: 40,
                height: 40,
                child: FCircularProgressIndicator(),
              ),
            )
          ] else ...[
            if (controller.state.isMergedMode) ...[
              QuickFWidget(
                FRTMergedChannelView(
                  controller.state.mainChannel! as IPlayChannel,
                  isSubView: false,
                  videoSize: Size(
                    deviceMember!.mergedVideoOutputWidth.toDouble(),
                    deviceMember.mergedVideoOutputHeight.toDouble(),
                  ),
                  viewSize: Size(
                    manager.getVideoDeviceInfoWidth(
                        videoDeviceInfos: deviceMember.videoDeviceInfos!),
                    manager.getVideoDeviceInfoHeight(
                        videoDeviceInfos: deviceMember.videoDeviceInfos!),
                  ),
                  viewAlignment: Alignment.topLeft,
                ),
              ),
            ] else ...[
              QuickFWidget(
                FRTDeviceChannelView(
                  viewSize: Size(width, height),
                  size: Size(width, height),
                  controller.state.mainChannel as IPlayChannel,
                ),
              ),
            ],
            _buildCourseTitle(),
            _buildWhiteBoard(),
          ],
          FPositioned(
            right: 10,
            top: 0,
            bottom: 0,
            child: FContainer(
              color: Colors.black.withOpacity(0.5),
              child: FColumn(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  _buildIconButton(Icons.close, () {
                    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();
                      },
                    );
                  }),
                  if (controller.state.mainChannel == null) ...[
                    _buildIconButton(Icons.screen_share_outlined,
                        controller.ultrasoundShare),
                  ],
                  if (controller.state.isDeviceShare) ...[
                    _buildIconButton(Icons.stop_screen_share_outlined,
                        () async {
                      await controller.stopDeviceShare();
                      setState(() {});
                    }),
                  ],
                  _buildIconButton(
                    Icons.share,
                    () {
                      var url = controller.state.courseDetail!.courseShareUrl;
                      router.dialog(() => ShareDialog(url ?? ''));
                    },
                  ),
                  _buildIconButton(Icons.delete, () {
                    controller.onClearCanavsHandler.emit(this, Store.user.code);
                  }),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  FWidget _buildSmailLiveView(FLiveCourseMember member) {
    return FContainer(
      decoration: BoxDecoration(
        color: Colors.grey[900],
        border: Border.all(color: Colors.grey[800]!),
      ),
      width: _memberListWidth,
      child: FColumn(
        children: [
          FContainer(
            margin: EdgeInsets.symmetric(horizontal: 10),
            child: FRow(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                _buildMemberName(member.name ?? ''),
                FIcon(
                  Icons.circle,
                  color: PatientColor.patientColors[member.index],
                  size: 14,
                ),
              ],
            ),
          ),
          FStack(
            children: [
              _buildLiveContent(member),
              MemberStatusView(member.memberStatus),
            ],
          ),
          MemberAudioOperates(
            RoomMember(
              member.id ?? '',
              mute: member.mute,
              videoOpend: member.videoOpend,
            ),
            channelInfo:
                (member.channelInfos == null || member.channelInfos!.isEmpty)
                    ? null
                    : PlayChannelInfo(member.channelInfos!.first),
            setAudioMute: (isMute, code) {
              controller.setAudioMute(isMute, code);
            },
            setMicrophone: (isMute) async {
              controller.setAudioOpend(isMute);
              return true;
            },
            setVideoOpend: (isOpened) async {
              setState(() {
                member.videoOpend = isOpened;
              });
              controller.setVideoOpend(isOpened);
              return true;
            },
          ),
        ],
      ),
    );
  }

  FWidget _buildMemberName(String name) {
    return FAlign(
      alignment: Alignment.center,
      child: FText(
        name,
        style: _memberTextStyle,
      ),
    );
  }

  FWidget _buildLiveContent(FLiveCourseMember member) {
    if (member.channelInfos == null || member.channelInfos!.isEmpty) {
      return _buildUserHeadImage(member.headImageToken ?? '');
    }
    var channel = member.channelInfos!.first;
    Widget channelView;
    var size = Size(_memberListWidth, _smallLiveViewHeight);
    if (channel is IPublishChannel) {
      channelView = FRTPublishPreviewView(
        channel,
        size: size,
      );
    } else {
      channelView = FRTPlayChannelView(
        channel as IPlayChannel,
        size: size,
      );
    }
    var child = QuickFWidget(
      Container(
        color: Colors.black,
        child: channelView,
      ),
    );
    if (!member.videoOpend) {
      return FStack(
        children: [
          child,
          _buildUserHeadImage(member.headImageToken ?? ''),
        ],
      );
    }
    return child;
  }

  FWidget _buildUserHeadImage(String headImageToken) {
    FWidget child;
    if (headImageToken.isEmpty) {
      child = FImage(
        image: AssetImage("assets/images/avatar_man.jpg"),
        fit: BoxFit.fill,
        height: _smallLiveViewHeight,
        width: _memberListWidth,
      );
    } else {
      child = FImage.network(
        headImageToken,
        fit: BoxFit.fill,
        height: _smallLiveViewHeight,
        width: _memberListWidth,
      );
    }
    return child;
  }

  FWidget _shareContentTips() {
    var teachMember = controller.state.liveCourseMembers.firstWhereOrNull(
        (e) => e.id == controller.state.courseDetail?.teacherCode);
    bool isTeacherLeft = teachMember?.memberStatus == MemberStatus.Left;
    return FExpanded(
      child: FStack(
        children: [
          FColumn(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              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.ultrasoundSharing.t,
                    Icons.screen_share_outlined,
                    onTap: controller.ultrasoundShare,
                  ),
                ],
              ),
            ],
          ),
          _buildCourseTitle(),
          FPositioned(
            right: 10,
            top: 5,
            child: _buildIconButton(Icons.close, () {
              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();
                },
              );
            }),
          )
        ],
      ),
    );
  }

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

  FWidget _iconTextButton(String text, IconData icon,
      {void Function()? onTap}) {
    return FMouseRegion(
      cursor: SystemMouseCursors.click,
      child: FGestureDetector(
        businessParent: widget,
        name: text,
        onTap: onTap,
        child: FContainer(
          width: 75,
          decoration: BoxDecoration(),
          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 _buildIconButton(IconData iconData, void Function() onPressed) {
    return FIconButton(
      businessParent: widget,
      name: "",
      onPressed: onPressed,
      icon: FIcon(
        iconData,
        color: Colors.white,
      ),
    );
  }

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