import 'package:fis_common/event/event_type.dart';
import 'package:fis_common/index.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
// import 'package:fis_theme/theme.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/values/font_sizes.dart';
import 'package:fis_ui/values/spacings.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/managers/interfaces/entities/consultation_member.dart';
import 'package:flyinsono/managers/interfaces/live_consultation.dart';
import 'package:flyinsono/pages/main/home/controller.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/live_consultation/state.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/live_consultation/widgets/recording_mark.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/live_consultation/widgets/operate_dropdown_button.dart';
import 'package:get/get.dart';
import '../widgets/image_capture_list.dart';
import 'index.dart';
import 'widgets/custom_button.dart';
import 'widgets/live_consulation_mobile_page.dart';
import 'widgets/preview_member_calling_status.dart';
import 'widgets/preview_member_status.dart';
import 'package:fis_lib_media_rt/widgets/index.dart';
import 'package:fis_lib_media_rt/interface/index.dart';
import 'widgets/resizable_container.dart';
import 'widgets/retry_button.dart';
import 'widgets/video_loading.dart';
import 'package:fis_theme/theme.dart';

class LiveConsulationPage extends FisView<LiveConsultationController>
    implements FPage {
  LiveConsulationPage({Key? key}) : super(key: key);

  @override
  String get pageName => "LiveConsulationPage";

  @override
  FWidget build(BuildContext context) {
    return context.fResponsiveVoid(
      mobile: () => LiveConsulationMobilePage(this),
      desktop: () => _DesktopLayout(this),
    );
  }
}

class _DesktopLayout extends FStatefulWidget {
  ///父级节点
  final FPage businessParent;

  _DesktopLayout(this.businessParent);

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

class _DesktopLayoutState extends FState<_DesktopLayout> {
  final double _smallLivePreviewWidth = 250;
  final double _smallLivePreviewHeight = 190;
  // final double _smallLivePreviewOperateHeight = 193;
  final double _callingViewHeight = 25;
  final double _previewMemberHeadTitle = 30;
  final controller = Get.find<LiveConsultationController>();
  final EdgeInsetsGeometry _smallLivePreviewMargin = EdgeInsets.only(top: 5);
  final EdgeInsetsGeometry _smallLivePreviewMarginLast =
      EdgeInsets.only(top: 5, bottom: 5);
  final _smallLivePrevieWDecoration = BoxDecoration(
    border: Border.all(
      width: 1.5,
      color: Color.fromARGB(255, 55, 56, 57),
    ),
    borderRadius: BorderRadius.all(Radius.circular(5)),
    color: Color.fromARGB(255, 14, 16, 17),
  );
  final TextStyle _previewMemberTextStyle =
      TextStyle(color: Color.fromARGB(255, 219, 219, 219), height: 1);
  final ScrollController _scrollController = ScrollController();
  final manager = Get.find<ILiveConsultationManager>();
  double _smallLiveDeviceHeight = 190;
  double _smallLiveDeviceWidth = 250;

  /// 获取当前组件最大高度
  double get maxGroupHeight => Get.height - _smallLivePreviewHeight;

  /// 获取到数据事件通知
  FEventHandler<String>? onGetDataChanged = FEventHandler<String>();

  @override
  void initState() {
    super.initState();
  }

  @override
  FWidget build(BuildContext context) {
    return FContainer(
      color: Colors.grey[300],
      child: _desktopLayout(),
    );
  }

  FWidget _desktopLayout() {
    return FContainer(
      color: Color.fromARGB(255, 21, 25, 27),
      child: FStack(
        fit: StackFit.expand,
        children: [
          FRow(
            children: [
              //主区域
              _buildMainLiveContentView(),
              FContainer(
                width: 2,
                color: Color.fromARGB(255, 65, 65, 65),
              ),
              //右侧预览区域
              _buildSmallLiveView(),
            ],
          ),
          //录制Mark
          _buildRecordingMark(),
        ],
      ),
    );
  }

  ///主视图
  FWidget _buildMainLiveContentView() {
    return FExpanded(
      child: FContainer(
        color: Color.fromARGB(255, 0, 0, 0),
        child: FStack(
          fit: StackFit.expand,
          children: [
            FObx(() {
              if (!controller.state.isLoading &&
                  controller.state.showRetryButton) {
                return RetryButton(
                  onTap: controller.retryLoadDevice,
                );
              }

              if (controller.state.isLoading ||
                  controller.state.deviceDesktopChannel == null) {
                return QuickFWidget(VideoLoadingWidget());
              } else if (controller.state.isSwitchCameraDevice &&
                  !controller.state.isMergedMode) {
                return QuickFWidget(
                  FRTPlayChannelView(
                    controller.state.deviceCameraChannel!,
                    size: Size(1500, 900),
                  ),
                );
              } else {
                if (controller.state.isMergedMode) {
                  ConsultationMember device = controller
                      .state.memberStatus.values
                      .firstWhere((element) =>
                          element.memberType == LiveMemberEnum.Device);
                  return FColumn(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      FContainer(height: 1, color: Colors.black),
                      FExpanded(
                        child: QuickFWidget(
                          _buildMainViewInMergedMode(device),
                        ),
                      ),
                      FContainer(height: 1, color: Colors.black),
                    ],
                  );
                }
                ConsultationMember device = controller.state.memberStatus.values
                    .toList()
                    .firstWhere((element) =>
                        element.memberType == LiveMemberEnum.Device);
                return FColumn(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    FContainer(height: 1, color: Colors.black),
                    FExpanded(
                      child: QuickFWidget(
                        FRTDeviceChannelView(
                          viewSize: Size(
                            manager.getVideoDeviceInfoWidth(
                                videoDeviceInfos: device.videoDeviceInfos!),
                            manager.getVideoDeviceInfoHeight(
                                videoDeviceInfos: device.videoDeviceInfos!),
                          ),
                          controller.state.deviceDesktopChannel!,
                        ),
                      ),
                    ),
                    FContainer(height: 1, color: Colors.black),
                  ],
                );
              }
            }),
            FObx(() {
              if (!controller.state.isLoading &&
                  !controller.state.showRetryButton) {
                return _buildWhiteboardView();
              } else {
                return FSizedBox();
              }
            }),
            FPositioned(
              right: FSpacings.XXL,
              bottom: FSpacings.XXL,
              child: OperatesDropdownButton(
                onClearCanavsHandler: controller.onClearCanavsHandler,
              ),
            ),
            FAlign(
              alignment: Alignment.bottomLeft,
              child: ImageCaptureList(),
            ),
            FObx(() {
              if (controller.state.consultationDetail.expertUserCode ==
                  Store.user.code) {
                return FPositioned(
                  left: FSpacings.XXL,
                  bottom: FSpacings.XXL,
                  child: _buildWaitInLineForConsultation(),
                );
              } else {
                return FSizedBox();
              }
            }),
            _buildDeviceCameraView(),
            _buildConsultationInfo(),
          ],
        ),
      ),
    );
  }

  ///右侧预览直播摄像头预览
  FWidget _buildSmallLiveView() {
    return FObx(() {
      final memberLiveDatas = controller.state.memberStatus;
      List<ConsultationMember> consultationMembers = memberLiveDatas.values
          .toList()
          .where((element) =>
              element.memberType == LiveMemberEnum.User &&
              element.id != Store.user.code)
          .toList();
      consultationMembers.sort(((a, b) => a.sortLevel.compareTo(b.sortLevel)));
      List<FWidget> children = [];
      var selfMember = memberLiveDatas[Store.user.code];
      if (selfMember != null) {
        children.add(
          _buildLiveViewItem(
            selfMember,
            controller.whiteboardController.getColorByIndex(selfMember.index),
          ),
        );
      }
      for (int i = 0; i < consultationMembers.length; i++) {
        children.add(
          _buildLiveViewItem(
            consultationMembers[i],
            controller.whiteboardController
                .getColorByIndex(consultationMembers[i].index),
          ),
        );
      }
      if (Store.user.code ==
          controller.state.consultationDetail.expertUserCode) {
        children.add(_buildAddMemberButton());
      }
      return FConstrainedBox(
        constraints: BoxConstraints.expand(width: _smallLivePreviewWidth),
        child: FColumn(
          children: [
            FExpanded(
              child: FContainer(
                color: Colors.white.withOpacity(0.1),
                child: FAlwaysScrollListView(
                  scrollController: _scrollController,
                  child: QuickFWidget(ScrollConfiguration(
                    behavior: ScrollConfiguration.of(context)
                        .copyWith(scrollbars: false),
                    child: FListView(
                      padding: EdgeInsets.only(left: 5, right: 10),
                      controller: _scrollController,
                      shrinkWrap: true,
                      children: children,
                    ),
                  )),
                ),
              ),
            ),
            FContainer(
              height: 2,
              color: Color.fromARGB(255, 65, 65, 65),
            ),
            FContainer(
              margin: EdgeInsets.all(5),
              child: FGridView(
                shrinkWrap: true,
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  childAspectRatio: 3,
                  crossAxisSpacing: 5,
                  mainAxisSpacing: FSpacings.S,
                ),
                children: _buildOperateButtonsView(),
              ),
            ),
          ],
        ),
      );
    });
  }

  ///单个预览成员
  FWidget _buildLiveViewItem(
    ConsultationMember member,
    Color currectPatientColor,
  ) {
    bool isUserMember = member.memberType == LiveMemberEnum.User;
    return FContainer(
      decoration: _smallLivePrevieWDecoration,
      margin: EdgeInsets.only(top: 5),
      width: isUserMember ? _smallLivePreviewWidth : _smallLiveDeviceWidth,
      child: FStack(
        children: [
          _buildLiveViewContent(member),
          PreviewMemberStatus(member),
          FPositioned(
            top: 5,
            left: 5,
            width:
                isUserMember ? _smallLivePreviewWidth : _smallLiveDeviceWidth,
            child: FContainer(
              child: _buildMemberName(member),
            ),
          ),
          if (member.memberType == LiveMemberEnum.User) ...[
            _buildMemberIcon(currectPatientColor),
          ],
          if (member.memberType == LiveMemberEnum.User) ...[
            FPositioned(
              top: _smallLivePreviewHeight,
              width: _smallLivePreviewWidth,
              child: PreviewMemberCallingStatus(member),
            ),
          ] else ...[
            FPositioned(
              top: 0,
              right: 0,
              child: FRow(
                children: [
                  _buildSwitchButton(),
                  _buildMinimizeButton(),
                ],
              ),
            ),
          ],
        ],
      ),
    );
  }

  ///邀请新成员
  FWidget _buildAddMemberButton() {
    return FMouseRegion(
      cursor: SystemMouseCursors.click,
      child: FGestureDetector(
        name: "Add member",
        businessParent: this.widget.businessParent,
        onTap: () {
          controller.addMember();
        },
        child: FContainer(
          margin: _smallLivePreviewMarginLast,
          decoration: _smallLivePrevieWDecoration,
          height: _smallLivePreviewHeight,
          width: _smallLivePreviewWidth,
          child: FIcon(
            Icons.add,
            color: Colors.grey,
            size: 26,
          ),
        ),
      ),
    );
  }

  ///摄像头内容
  FWidget _buildLiveViewContent(ConsultationMember member) {
    return FObx(() {
      IChannel? channel = controller.getMemberPreviewChannel(member);
      var memberStatus = controller.state.memberStatus[member.id];
      bool videoOpend = true;
      if (memberStatus != null && !memberStatus.videoOpend) {
        videoOpend = false;
      }
      if (channel != null) {
        var isUserMember = member.memberType == LiveMemberEnum.User;
        double height;
        if (isUserMember) {
          height = _smallLivePreviewHeight + _callingViewHeight;
        } else {
          height = _smallLiveDeviceHeight + 10;
        }
        if (videoOpend) {
          return _buildChannel(isUserMember, height, channel);
        } else {
          return FStack(
            children: [
              _buildChannel(isUserMember, height, channel),
              _buildUserHeadImage(member),
            ],
          );
        }
      }
      return _buildUserHeadImage(member);
    });
  }

  FWidget _buildUserHeadImage(ConsultationMember member) {
    var headImageToken = member.headImageToken ?? '';
    var height = _smallLivePreviewHeight;
    var isUserMember = member.memberType == LiveMemberEnum.User;
    if (isUserMember) {
      height = _smallLivePreviewHeight + _callingViewHeight;
    }
    FWidget child;
    if (headImageToken.isEmpty) {
      child = FImage(
        image: AssetImage("assets/images/avatar_man.jpg"),
        fit: BoxFit.fill,
        height: height,
        width: _smallLivePreviewWidth,
      );
    } else {
      child = FImage.network(
        headImageToken,
        fit: BoxFit.fill,
        height: height,
        width: _smallLivePreviewWidth,
      );
    }
    return FContainer(
      height: height,
      padding: EdgeInsets.only(
        top: _previewMemberHeadTitle,
        bottom: isUserMember ? _callingViewHeight : 0,
      ),
      width: _smallLivePreviewWidth,
      child: child,
    );
  }

  ///右下角操作按钮
  List<FWidget> _buildOperateButtonsView() {
    final mediaQuery = MediaQuery.of(context);

    ///屏幕缩放比例
    final devicePixelRatio = mediaQuery.devicePixelRatio;
    final textStyle = TextStyle(
      fontSize: devicePixelRatio > 1 ? 10 : 13,
    );
    return <FWidget>[
      FAlign(
        alignment: Alignment.center,
        child: FObx(() {
          var state = controller.state;
          return FRow(
            children: [
              FText(
                i18nBook.measure.playLocationDurationLabel.t,
                style: TextStyle(fontSize: 14, color: Colors.grey[300]),
              ),
              FText(
                ' ${state.minute.padLeft2()}' +
                    ':' +
                    '${state.seconds.padLeft2()}',
                style: TextStyle(
                    letterSpacing: 2, fontSize: 14, color: Colors.grey[300]),
              ),
            ],
          );
        }),
      ),
      _buildLeaveConsulationBytton(),
      if ((FPlatform.isMacOS || FPlatform.isWindows)) ...[
        FElevatedButton(
          child: FObx(() {
            if (controller.state.isFullRecording &&
                !controller.state.isFullRecordingPause) {
              return FText(
                i18nBook.realTimeConsultation.pauseFullRecording.t,
                style: textStyle,
              );
            }
            if (controller.state.isFullRecording &&
                controller.state.isFullRecordingPause) {
              return FText(
                i18nBook.realTimeConsultation.continueFullRecording.t,
                style: textStyle,
              );
            }
            return FText(
              i18nBook.realTimeConsultation.fullRecording.t,
              style: textStyle,
            );
          }),
          onPressed: () {
            controller.onRecordingOperation();
          },
          businessParent: this.widget.businessParent,
          name: 'Start full recording',
        ),
      ],
      if ((FPlatform.isMacOS || FPlatform.isWindows)) ...[
        FObx(() {
          return controller.state.isFullRecording
              ? FElevatedButton(
                  child: FText(
                    i18nBook.realTimeConsultation.endRecording.t,
                    style: textStyle,
                  ),
                  onPressed: () {
                    controller.stopFullRecording();
                  },
                  businessParent: this.widget.businessParent,
                  name: 'Stop full recording',
                )
              : FContainer();
        }),
      ],
    ];
  }

  ///待会诊病人
  FWidget _buildWaitInLineForConsultation() {
    return FObx(() {
      final LiveConsulationState state = controller.state;
      var patients = state.waitInLineForConsulationPatients;
      if (patients.isEmpty) {
        return FSizedBox();
      }
      if (state.isEmergency) {
        return FSizedBox();
      }
      return FSelect<ConsultationPageDTO, String>(
        decoration: BoxDecoration(color: Colors.white),
        source: patients,
        width: 300,
        hintText: i18nBook.common.switchPatients.t,
        fontFamily: FTheme.ins.localeSetting.fontFamily,
        optionValueExtractor: (v) {
          return v.consultationCode ?? '';
        },
        optionLabelExtractor: (v) {
          var name = v.patientName ?? '';
          var status = i18nBook.realTimeConsultation.toBeStarted.t;
          if (v.consultationCode == controller.state.selectedConsultationCode) {
            status = i18nBook.realTimeConsultation.haveInHand.t;
          }
          return ' $name  $status';
        },
        onSelectChanged: (value, index) {
          if (state.selectedConsultationCode != value) {
            FConfirmAlert.show(
              context: Get.context!,
              title: i18nBook.common.tip.t,
              subTitle: i18nBook.remedical.confirmCloseCurrentConsultation.t,
              confrimLabel: i18nBook.common.confirm.t,
              cancelLabel: i18nBook.common.cancel.t,
              businessParent: this.widget.businessParent,
              onConfirm: () {
                controller.onSelectedPatientChange(value ?? '');
              },
              onCancel: () {
                setState(() {});
              },
            );
          }
        },
        value: patients.any((element) =>
                element.consultationCode == state.selectedConsultationCode)
            ? state.selectedConsultationCode
            : null,
      );
    });
  }

  FWidget _buildMemberName(ConsultationMember member) {
    return FText(
      member.name ?? '',
      style: _previewMemberTextStyle.copyWith(
        overflow: TextOverflow.ellipsis,
      ),
    );
  }

  FWidget _buildMemberIcon(Color currectPatientColor) {
    return FPositioned(
      top: 5,
      right: 5,
      child: FAlign(
        alignment: Alignment.centerRight,
        child: FIcon(
          Icons.circle,
          color: currectPatientColor,
          size: 14,
        ),
      ),
    );
  }

  FWidget _buildSwitchButton() {
    return FMouseRegion(
      cursor: SystemMouseCursors.click,
      child: FGestureDetector(
        name: 'switchPositionButton',
        businessParent: this.widget.businessParent,
        onTap: () {
          setState(() {
            controller.state.isSwitchCameraDevice =
                !controller.state.isSwitchCameraDevice;
          });
        },
        child: FContainer(
          padding: EdgeInsets.all(FSpacings.XS),
          child: FIcon(
            Icons.swap_horiz,
            color: Colors.white,
          ),
        ),
      ),
    );
  }

  FWidget _buildMinimizeButton() {
    return FMouseRegion(
      cursor: SystemMouseCursors.click,
      child: FGestureDetector(
        name: 'switchPositionButton',
        businessParent: this.widget.businessParent,
        onTap: () {
          controller.state.isShowDeviceCamera =
              !controller.state.isShowDeviceCamera;
          setState(() {});
        },
        child: FContainer(
          padding: EdgeInsets.all(FSpacings.XS),
          child: FIcon(
            Icons.minimize,
            color: Colors.white,
          ),
        ),
      ),
    );
  }

  FWidget _buildDeviceViewButton() {
    var isShowDevicePreviewInLeft = controller.state.isShowDevicePreviewInLeft;
    return FPositioned(
      top: 0,
      left: isShowDevicePreviewInLeft ? FSpacings.S : null,
      right: isShowDevicePreviewInLeft ? null : FSpacings.S,
      child: FMouseRegion(
        cursor: SystemMouseCursors.click,
        child: FGestureDetector(
          name: 'switchPositionButton',
          businessParent: this.widget.businessParent,
          onTap: () {
            controller.state.isShowDeviceCamera =
                !controller.state.isShowDeviceCamera;
          },
          child: FText(
            controller.state.isSwitchCameraDevice
                ? i18nBook.realTimeConsultation.devicePicture.t
                : i18nBook.realTimeConsultation.scanningTechnique.t,
            style: TextStyle(fontSize: FFontSizes.H4, color: Colors.grey[400]),
          ),
        ),
      ),
    );
  }

  FWidget _buildChannel(bool isUserMember, double height, IChannel channel) {
    Widget channelView;
    Size? size = isUserMember ? null : Size(_smallLiveDeviceWidth, height);
    if (channel is IPublishChannel) {
      channelView = FRTPublishPreviewView(
        channel,
        //size: size,
      );
    } else {
      channelView = FRTPlayChannelView(
        channel as IPlayChannel,
        // size: size,
      );
    }
    return QuickFWidget(
      Container(
        height: height,
        width: isUserMember ? _smallLivePreviewWidth : _smallLiveDeviceWidth,
        padding: EdgeInsets.only(
          top: _previewMemberHeadTitle + 1, //+1是防止有锯齿的缝隙
          bottom: isUserMember ? _callingViewHeight : 0,
        ),
        child: channelView,
      ),
    );
  }

  _buildRecordingMark() {
    return FObx(() {
      if (controller.state.isFullRecording &&
          !controller.state.isFullRecordingPause) {
        return FPositioned(
          left: FSpacings.XXL,
          top: FSpacings.XXL,
          child: RecordingMark(
            startTime: controller.state.vidCapturerStartTime,
          ),
        );
      }
      return FSizedBox();
    });
  }

  ///白板
  FWidget _buildWhiteboardView() {
    return FObx(() {
      final IPlayChannel? channel = controller.state.deviceDesktopChannel;
      if (channel == null) {
        return FSizedBox();
      }
      ConsultationMember device = controller.state.memberStatus.values
          .firstWhere((element) => element.memberType == LiveMemberEnum.Device);
      if (device.videoDeviceInfos == null) {
        return FSizedBox();
      }
      if (controller.state.initBoardDatas == null) {
        return FSizedBox();
      }
      return FOffstage(
        offstage: controller.state.isSwitchCameraDevice,
        child: FClipRRect(
          child: Center(
            child: AspectRatio(
              aspectRatio: manager.getVideoDeviceInfoWidth(
                      videoDeviceInfos: device.videoDeviceInfos!) /
                  manager.getVideoDeviceInfoHeight(
                      videoDeviceInfos: device.videoDeviceInfos!),
              child: FWhiteBoard(
                sendData: (value) {
                  controller.sendInteractiveBoardData(value);
                },
                patientColor: controller.currectColor(),
                paintType: controller.state.paintType,
                userId: Store.user.code,
                onReceiveData: Get.find<ILiveConsultationManager>()
                    .onWhiteboardDataReceive,
                onClearCanavs: controller.onClearCanavsHandler,
                initData: controller.state.initBoardDatas!,
              ),
            ),
          ),
        ),
      );
    });
  }

  ///超声机摄像头（扫查手法）
  FWidget _buildDeviceCameraView() {
    return FObx(() {
      ConsultationMember? consultationMember =
          controller.state.memberStatus.values.toList().firstWhereOrNull(
              (element) => element.memberType == LiveMemberEnum.Device);
      if (controller.state.isLoading || controller.state.showRetryButton) {
        return FSizedBox();
      }
      if (consultationMember == null ||
          consultationMember.videoDeviceInfos == null ||
          consultationMember.videoDeviceInfos!.firstWhereOrNull((element) =>
                  element.videoDeviceSourceType ==
                  VideoDeviceSourceTypeEnum.Camera) ==
              null) {
        return FSizedBox();
      }
      if (controller.state.isShowDeviceCamera) {
        return FPositioned(
          right: 0,
          top: 0,
          child: FObx(() {
            if (controller.state.isMergedMode &&
                controller.state.deviceDesktopChannel != null) {
              return _buildSmallLiveViewInMergedMode();
            }
            if (controller.state.deviceCameraChannel == null) {
              return QuickFWidget(VideoLoadingWidget());
            } else if (controller.state.isSwitchCameraDevice) {
              return _buildSmailDeviceView(
                  consultationMember, controller.state.deviceDesktopChannel!);
            }
            return _buildSmailCameraView(consultationMember);
          }),
        );
      } else {
        return _buildDeviceViewButton();
      }
    });
  }

  FWidget _buildLeaveConsulationBytton() {
    return FCustomExitButton(
      i18nBook.realTimeConsultation.exitConsultation.t,
      Icons.exit_to_app,
      () {
        FConfirmAlert.show(
          context: Get.context!,
          title: i18nBook.common.tip.t,
          subTitle: i18nBook.realTimeConsultation.confirmLeaveConsultation.t,
          confrimLabel: i18nBook.common.confirm.t,
          cancelLabel: i18nBook.common.cancel.t,
          businessParent: this.widget.businessParent,
          onConfirm: () {
            controller.sendInteractiveBoardData('', true);
            controller.onClearCanavsHandler.emit(this, Store.user.code);
            controller.leaveConsultation();
            try {
              final _navController = Get.find<HomeNavigatorController>();
              _navController.subBack();
            } catch (e) {}
          },
        );
      },
    );
  }

  FWidget _buildSmailDeviceView(
      ConsultationMember consultationMember, IPlayChannel channel) {
    return QuickFWidget(
      Obx(() {
        ConsultationMember device = controller.state.memberStatus.values
            .firstWhere(
                (element) => element.memberType == LiveMemberEnum.Device);
        Size viewSize = Size(
          manager.getVideoDeviceInfoWidth(
              videoDeviceInfos: device.videoDeviceInfos!),
          manager.getVideoDeviceInfoHeight(
              videoDeviceInfos: device.videoDeviceInfos!),
        );
        Size realSize = controller.mediaController.selectResolution(viewSize);
        return ResizableWidget(
          aspectRatio: realSize.width / realSize.height,
          extraTitleHeight: 30,
          child: Container(
            decoration: _smallLivePrevieWDecoration,
            margin: EdgeInsets.only(top: 5),
            child: Stack(
              children: [
                Container(
                  margin: EdgeInsets.only(top: 30),
                  child: FRTDeviceChannelView(
                    viewSize: Size(
                      manager.getVideoDeviceInfoWidth(
                          videoDeviceInfos: device.videoDeviceInfos!),
                      manager.getVideoDeviceInfoHeight(
                          videoDeviceInfos: device.videoDeviceInfos!),
                    ),
                    channel,
                  ),
                ),
                Align(
                  alignment: Alignment.topLeft,
                  child: Container(
                    padding: EdgeInsets.only(left: 5),
                    height: _previewMemberHeadTitle,
                    child: Row(
                      children: [
                        FTextTooltip(
                          position: DisplayPosition.bottom,
                          textStyle: TextStyle(
                            fontSize: 14,
                            color: Colors.white,
                          ),
                          height: 36,
                          message: consultationMember.name ?? '',
                          child: FContainer(
                            width: _smallLiveDeviceWidth - 40,
                            child: _buildMemberName(consultationMember),
                          ),
                          margin: EdgeInsets.all(0),
                          decoration: BoxDecoration(
                            color: Colors.black.withOpacity(1.0),
                            borderRadius: BorderRadius.circular(4),
                          ),
                        ),
                        _buildSwitchButton(),
                        _buildMinimizeButton(),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
          onResize: (size) {
            setState(() {
              _smallLiveDeviceHeight = size.height - 12;
              _smallLiveDeviceWidth = size.width;
            });
          },
          showInLeft: controller.state.isShowDevicePreviewInLeft,
          height: _smallLiveDeviceHeight + 12,
          width: _smallLiveDeviceWidth,
        );
      }),
    );
  }

  FWidget _buildSmailCameraView(ConsultationMember device) {
    if (device.videoDeviceInfos!.length < 2) {
      return QuickFWidget(VideoLoadingWidget());
    }
    final _aspectRatio = manager.getVideoDeviceInfoWidth(
            videoDeviceInfos: device.videoDeviceInfos!,
            videoDeviceSourceType: VideoDeviceSourceTypeEnum.Camera) /
        manager.getVideoDeviceInfoHeight(
            videoDeviceInfos: device.videoDeviceInfos!,
            videoDeviceSourceType: VideoDeviceSourceTypeEnum.Camera);
    return QuickFWidget(
      ResizableWidget(
        child: Container(
          decoration: _smallLivePrevieWDecoration,
          margin: EdgeInsets.only(top: 5),
          child: Stack(
            children: [
              Container(
                margin: EdgeInsets.only(top: 30),
                child: Obx(() {
                  return FRTPlayChannelView(
                    controller.state.deviceCameraChannel!,
                  );
                }),
              ),
              Align(
                alignment: Alignment.topRight,
                child: FContainer(
                  height: _previewMemberHeadTitle,
                  padding: EdgeInsets.only(left: 5),
                  color: Colors.black,
                  child: FRow(
                    children: [
                      FSizedBox(
                        width: _smallLiveDeviceWidth - 65,
                        child: FTextTooltip(
                          position: DisplayPosition.bottom,
                          textStyle: TextStyle(
                            fontSize: 14,
                            color: Colors.white,
                          ),
                          height: 36,
                          message: device.name ?? '',
                          child: _buildMemberName(device),
                          margin: EdgeInsets.all(0),
                          decoration: BoxDecoration(
                            color: Colors.black.withOpacity(1.0),
                            borderRadius: BorderRadius.circular(4),
                          ),
                        ),
                      ),
                      FExpanded(child: FSizedBox()),
                      _buildSwitchButton(),
                      _buildMinimizeButton(),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
        aspectRatio: _aspectRatio,
        extraTitleHeight: 30,
        onResize: (size) {
          setState(() {
            _smallLiveDeviceHeight = size.height;
            _smallLiveDeviceWidth = size.width;
          });
        },
        showInLeft: controller.state.isShowDevicePreviewInLeft,
        height: _smallLiveDeviceHeight,
        width: _smallLiveDeviceWidth,
      ),
    );
  }

  FWidget _buildSmallLiveViewInMergedMode() {
    return QuickFWidget(
      Container(
        decoration: _smallLivePrevieWDecoration,
        child: Obx(
          () {
            double aspectRatio = 1;
            ConsultationMember device = controller.state.memberStatus.values
                .firstWhere(
                    (element) => element.memberType == LiveMemberEnum.Device);
            if (controller.state.isSwitchCameraDevice) {
              aspectRatio = manager.getVideoDeviceInfoWidth(
                      videoDeviceInfos: device.videoDeviceInfos!) /
                  manager.getVideoDeviceInfoHeight(
                      videoDeviceInfos: device.videoDeviceInfos!);
            } else {
              aspectRatio = manager.getVideoDeviceInfoWidth(
                      videoDeviceInfos: device.videoDeviceInfos!,
                      videoDeviceSourceType: VideoDeviceSourceTypeEnum.Camera) /
                  manager.getVideoDeviceInfoHeight(
                      videoDeviceInfos: device.videoDeviceInfos!,
                      videoDeviceSourceType: VideoDeviceSourceTypeEnum.Camera);
            }
            return ResizableWidget(
              aspectRatio: aspectRatio,
              extraTitleHeight: 30,
              onResize: (size) {
                setState(() {
                  _smallLiveDeviceHeight = size.height;
                  _smallLiveDeviceWidth = size.width;
                });
              },
              showInLeft: controller.state.isShowDevicePreviewInLeft,
              height: _smallLiveDeviceHeight,
              width: _smallLiveDeviceWidth,
              child: Container(
                decoration: _smallLivePrevieWDecoration,
                margin: EdgeInsets.only(top: 5),
                child: Stack(
                  children: [
                    Container(
                      margin: EdgeInsets.only(top: 30),
                      child: Obx(() {
                        if (controller.state.isSwitchCameraDevice) {
                          return Center(
                            child: AspectRatio(
                              aspectRatio: aspectRatio,
                              child: FRTMergedChannelView(
                                isSubView: false,
                                videoSize: Size(
                                  device.mergedVideoOutputWidth.toDouble(),
                                  device.mergedVideoOutputHeight.toDouble(),
                                ),
                                viewSize: Size(
                                  manager.getVideoDeviceInfoWidth(
                                      videoDeviceInfos:
                                          device.videoDeviceInfos!),
                                  manager.getVideoDeviceInfoHeight(
                                      videoDeviceInfos:
                                          device.videoDeviceInfos!),
                                ),
                                viewAlignment: Alignment.topLeft,
                                controller.state.deviceDesktopChannel!,
                              ),
                            ),
                          );
                        }
                        if (device.videoDeviceInfos != null &&
                            device.videoDeviceInfos!.length > 1) {
                          return Center(
                            child: AspectRatio(
                              aspectRatio: aspectRatio,
                              child: FRTMergedChannelSubView(
                                  device: device,
                                  manager: manager,
                                  controller: controller),
                            ),
                          );
                        } else {
                          return Container();
                        }
                      }),
                    ),
                    Align(
                      alignment: Alignment.topRight,
                      child: FContainer(
                        height: _previewMemberHeadTitle,
                        padding: EdgeInsets.only(left: 5),
                        color: Colors.black,
                        child: FRow(
                          children: [
                            FSizedBox(
                              width: _smallLiveDeviceWidth - 65,
                              child: FTextTooltip(
                                position: DisplayPosition.bottom,
                                textStyle: TextStyle(
                                  fontSize: 14,
                                  color: Colors.white,
                                ),
                                height: 36,
                                message: device.name ?? '',
                                child: _buildMemberName(device),
                                margin: EdgeInsets.all(0),
                                decoration: BoxDecoration(
                                  color: Colors.black.withOpacity(1.0),
                                  borderRadius: BorderRadius.circular(4),
                                ),
                              ),
                            ),
                            FExpanded(child: FSizedBox()),
                            _buildSwitchButton(),
                            _buildMinimizeButton(),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildMainViewInMergedMode(ConsultationMember device) {
    return Obx(() {
      if (!controller.state.isSwitchCameraDevice) {
        return LayoutBuilder(builder: (context, constraint) {
          return Center(
            child: AspectRatio(
              aspectRatio: manager.getVideoDeviceInfoWidth(
                      videoDeviceInfos: device.videoDeviceInfos!) /
                  manager.getVideoDeviceInfoHeight(
                      videoDeviceInfos: device.videoDeviceInfos!),
              child: FRTMergedChannelView(
                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,
                controller.state.deviceDesktopChannel!,
              ),
            ),
          );
        });
      }
      if (device.videoDeviceInfos != null &&
          device.videoDeviceInfos!.length > 1) {
        return Center(
          child: AspectRatio(
              aspectRatio: manager.getVideoDeviceInfoWidth(
                      videoDeviceInfos: device.videoDeviceInfos!,
                      videoDeviceSourceType: VideoDeviceSourceTypeEnum.Camera) /
                  manager.getVideoDeviceInfoHeight(
                      videoDeviceInfos: device.videoDeviceInfos!,
                      videoDeviceSourceType: VideoDeviceSourceTypeEnum.Camera),
              child: FRTMergedChannelSubView(
                  device: device, manager: manager, controller: controller)),
        );
      } else {
        return Container();
      }
    });
  }

  FWidget _buildConsultationInfo() {
    Color color = Colors.grey;
    var textStyle = TextStyle(
      color: color,
    );
    return FPositioned(
      left: FSpacings.M,
      right: FSpacings.M,
      child: FObx(() {
        return FColumn(
          children: [
            FTitleField(
              i18nBook.realTimeConsultation.applicantMechanism.t,
              FText(
                controller.state.consultationDetail.applyOrganizationName ?? '',
                style: textStyle,
              ),
              isBold: false,
              titleColor: color,
              sizeBetween: 15,
            ),
            FTitleField(
              i18nBook.remedical.patientDisplayName.t,
              FText(
                controller.state.consultationDetail.patientName ?? '',
                style: textStyle,
              ),
              isBold: false,
              titleColor: color,
              sizeBetween: 15,
            ),
            FTitleField(
              i18nBook.user.ulrSoundsMachine.t,
              FText(
                controller.state.consultationDetail.displayName ?? '',
                style: textStyle,
              ),
              isBold: false,
              titleColor: color,
              sizeBetween: 15,
            ),
          ],
        );
      }),
    );
  }
}

/// 超声机合图模式下的子画面（摄像头画面）
class FRTMergedChannelSubView extends StatelessWidget {
  const FRTMergedChannelSubView({
    super.key,
    required this.device,
    required this.manager,
    required this.controller,
  });

  final ConsultationMember device;
  final ILiveConsultationManager manager;
  final LiveConsultationController controller;

  @override
  Widget build(BuildContext context) {
    if (device.isOldPlatform) {
      return FRTMergedChannelSubViewOldVersion(
        videoSize: Size(
          device.mergedVideoOutputWidth.toDouble(),
          device.mergedVideoOutputHeight.toDouble(),
        ),
        mainViewSize: Size(
          manager.getVideoDeviceInfoWidth(
              videoDeviceInfos: device.videoDeviceInfos!),
          manager.getVideoDeviceInfoHeight(
              videoDeviceInfos: device.videoDeviceInfos!),
        ),
        cameraViewSize: Size(
            manager.getVideoDeviceInfoWidth(
                videoDeviceInfos: device.videoDeviceInfos!,
                videoDeviceSourceType: VideoDeviceSourceTypeEnum.Camera),
            manager.getVideoDeviceInfoHeight(
                videoDeviceInfos: device.videoDeviceInfos!,
                videoDeviceSourceType: VideoDeviceSourceTypeEnum.Camera)),
        viewAlignment: Alignment.topLeft,
        controller.state.deviceDesktopChannel!,
      );
    } else {
      return FRTMergedChannelView(
        isSubView: true,
        videoSize: Size(
          device.mergedVideoOutputWidth.toDouble(),
          device.mergedVideoOutputHeight.toDouble(),
        ),
        viewSize: Size(
            manager.getVideoDeviceInfoWidth(
                videoDeviceInfos: device.videoDeviceInfos!,
                videoDeviceSourceType: VideoDeviceSourceTypeEnum.Camera),
            manager.getVideoDeviceInfoHeight(
                videoDeviceInfos: device.videoDeviceInfos!,
                videoDeviceSourceType: VideoDeviceSourceTypeEnum.Camera)),
        viewAlignment: Alignment.topRight,
        controller.state.deviceDesktopChannel!,
      );
    }
  }
}
