import 'dart:convert';

import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.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/paddings.dart';
import 'package:fis_ui/values/spacings.dart';
import 'package:fis_ui/widgets/webview/webview.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/utils/webviewx.dart';
import 'package:flyinsono/managers/interfaces/entities/device_live_room.dart';
import 'package:flyinsono/managers/interfaces/remote_controller.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/live_consultation/widgets/custom_button.dart';
import 'package:flyinsono/views/desktop/remote_maintenance/widgets/apiinfo.dart';
import 'package:flyinsono/views/desktop/remote_maintenance/widgets/custom_button.dart';
import 'package:flyinsono/views/desktop/remote_maintenance/widgets/custom_value_button.dart';
import 'package:flyinsono/views/desktop/remote_maintenance/widgets/custom_value_select.dart';
import 'package:get/get.dart';
import 'package:webviewx/webviewx.dart';
import 'package:fis_common/index.dart';
import 'index.dart';
import 'widgets/hover_border_button.dart';
import 'widgets/remote_controller_parameters/first_page_parameters_view.dart';
import 'widgets/remote_controller_parameters/mode_select_view.dart';
import 'widgets/remote_controller_parameters/remote_controller_parameters_styles.dart';

class RemoteControllerPage extends FStatefulWidget implements FPage {
  final bool isPortrait;
  const RemoteControllerPage({
    Key? key,
    this.isPortrait = false,
  }) : super(key: key);

  @override
  FState<RemoteControllerPage> createState() => _FRemotecontrollerPageState();

  @override
  String get pageName => 'RemoteControllerPage';
}

class _FRemotecontrollerPageState extends FState<RemoteControllerPage> {
  final remoteControllerManager = Get.find<IRemoteControllerManager>();
  final controller = Get.find<RemoteControllerController>();
  final totalPageCount = 5;
  late WebViewXController webViewController;
  static const String _INT32_MAX = '2147483647';

  ///是否会诊中远程控制调参
  bool get _isLiveConsultationController =>
      controller.state.isLiveConsultationController;

  ///设备Code
  String get deviceCode => controller.state.deviceCode;

  ///是否竖屏
  bool _isPortrait = false;

  ///手机端选择的调节页面，0 为探头和应用，1为参数调节
  int? _mobileSelectedPageIndex;

  ///UI样式
  Color get _primaryColor => TuningParametersStyles.primaryColor;
  final TextStyle _texytStyle = TuningParametersStyles.texytStyle;

  ///常规装饰器
  final normalBoxDecoration = TuningParametersStyles.normalBoxDecoration;

  ///选中项装饰器
  final selectedBoxDecoration = TuningParametersStyles.selectedBoxDecoration;

  ///背景色
  Color get background => TuningParametersStyles.backgroundColor;
  final _probeTabsScrollController = ScrollController();
  final _applayDatasScrollController = ScrollController();
  final _modelTabsScrollController = ScrollController();
  @override
  void initState() {
    if (kIsMobile) {
      _isPortrait = widget.isPortrait;
      _mobileSelectedPageIndex = 0;
    }
    if (kIsMobile) {
      _setLandscapeMode();
    }
    if (_isLiveConsultationController) {
      ///会诊中调参维持心跳
      controller.remoteConnectHeartRateSendOnce();
      controller.startHeartbeat();
    }
    super.initState();
  }

  @override
  void dispose() {
    if (!_isLiveConsultationController) {
      // 强制竖屏
      _setPortraitMode();
    } else {
      SystemChrome.setPreferredOrientations(
          [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
    }
    controller.dispose();
    super.dispose();
  }

  @override
  FWidget build(BuildContext context) {
    ///横向布局
    var body = FContainer(
      color: background,
      child: FRow(
        children: [
          FFlexible(
            child: FColumn(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                if (!kIsMobile) ...[
                  FObx(() {
                    if (controller.state.deviceCode.isNullOrEmpty) {
                      ///会诊中进入房间，且直播页面尚未加载，则转圈等待加载直播画面
                      return FExpanded(
                        child: FContainer(
                          height: 100,
                          alignment: Alignment.center,
                          child: FCircularProgressIndicator(),
                        ),
                      );
                    }
                    return ModelSelectView();
                  }), //模式选择
                ],
                _buildDeviceLiveView(), //超声机直播视图
              ],
            ),
          ),
          _buildParameterAdjustmentView(),
        ],
      ),
    );

    ///手机端竖向布局
    if (_isPortrait && kIsMobile) {
      return _portraitLayout();
    }
    return body;
  }

  /// 设备直播视图
  FWidget _buildDeviceLiveView() {
    return FObx(() {
      if (controller.state.deviceExtendInfoDTO == null) {
        return FCenter(
          child: FContainer(
            width: 40,
            color: Colors.black,
            height: 40,
            child: FCircularProgressIndicator(),
          ),
        );
      }

      FWidget child =
          kIsMobile ? _buildMobileLiveWebview() : _buildLiveWebview();

      return FExpanded(
        child: FContainer(
          child: child,
        ),
      );
    });
  }

  /// PC 端直播 Webview
  FWidget _buildLiveWebview() {
    return FFutureBuilder<String>(
      future: DefaultAssetBundle.of(context)
          .loadString("assets/webview/device_live.html"),
      builder: (context, snapshot) {
        if (snapshot.connectionState != ConnectionState.done ||
            snapshot.data == null) {
          return const FCenter(
            child: FSizedBox(
              width: 20,
              height: 20,
              child: FCircularProgressIndicator(),
            ),
          );
        }
        return FLayoutBuilder(
          builder: (context, constraints) {
            print(
                'constraints:width:${constraints.maxWidth} height:${constraints.maxHeight}');
            final webview = FWebViewX(
              height: constraints.maxHeight,
              width: constraints.maxWidth,
              initialContent: snapshot.data!,
              initialSourceType: SourceType.html,
              javascriptMode: JavascriptMode.unrestricted,
              onWebViewCreated: (controller) {
                webViewController = controller;
              },
              ignoreAllGestures: controller.ignoreAllGestures,
              onPageFinished: (p0) {},
              dartCallBacks: {
                DartCallback(
                    name: "Dart_GetLiveData",
                    callBack: (_) {
                      var sourceDto =
                          controller.state.deviceExtendInfoDTO!.liveInfo!.dto!;
                      var deviceLiveRoom =
                          DeviceLiveRoom.fromJoinDeviceLiveRoomResult(
                        sourceDto,
                        enableCamera: false,
                        muteMode: true,
                      );
                      var jsonStr = jsonEncode(deviceLiveRoom.toJson());
                      return jsonStr;
                    }),
                WebviewXDartAsyncCallback(
                  controllerGetter: () => webViewController,
                  methods: {
                    "checkLiveState": (data) async {
                      final result = await controller.checkLiveDeviceState();
                      if (result == 2) {
                        // 更新直播信息，重载页面
                        Future.delayed(const Duration(milliseconds: 100), () {
                          webViewController.reload();
                        });
                      }
                      return result == 1;
                    },
                  },
                ),
              },
            );
            return _deviceNameWrapper(webview);
          },
        );
      },
    );
  }

  /// 移动端直播 Webview
  FWidget _buildMobileLiveWebview() {
    return FObx(() {
      if (controller.state.deviceExtendInfoDTO == null) {
        return FCenter(
          child: FContainer(
            width: 40,
            height: 40,
            child: FCircularProgressIndicator(),
          ),
        );
      }

      var livePanel = QuickFWidget(
        InAppWebView(
          initialFile: "assets/webview/device_live_m.html",
          initialOptions: InAppWebViewGroupOptions(
            crossPlatform: InAppWebViewOptions(
              transparentBackground: true,
              mediaPlaybackRequiresUserGesture: false,
              disableHorizontalScroll: true,
              disableVerticalScroll: true,
              allowFileAccessFromFileURLs: true,
              allowUniversalAccessFromFileURLs: true,
            ),
            ios: IOSInAppWebViewOptions(
              allowsInlineMediaPlayback: true,
            ),
            android: AndroidInAppWebViewOptions(
              allowFileAccess: true,
              allowContentAccess: true,
            ),
          ),
          onWebViewCreated: (c) {
            c.addJavaScriptHandler(
              handlerName: "Dart_GetLiveData",
              callback: (args) async {
                var liveInfo = controller.state.deviceExtendInfoDTO!.liveInfo!;
                var sourceDto = liveInfo.dto!;
                var deviceLiveRoom =
                    DeviceLiveRoom.fromJoinDeviceLiveRoomResult(
                  sourceDto,
                  enableCamera: false,
                  muteMode: true,
                );
                var jsonStr = jsonEncode(deviceLiveRoom.toJson());
                return jsonStr;
              },
            );
            c.addJavaScriptHandler(
              handlerName: "Dart_CheckLiveState",
              callback: (args) async {
                // controller.checkLiveDeviceState();
                final result = await controller.checkLiveDeviceState();
                if (result == 2) {
                  // 更新直播信息, 刷新页面
                  Future.delayed(const Duration(milliseconds: 100), () {
                    c.reload();
                  });
                }
                return result == 1;
              },
            );
          },
          onLoadStop: (c, url) async {},
          onConsoleMessage: (c, consoleMessage) {},
        ),
      );

      return FSafeArea(
        right: false,
        left: false,
        child: FStack(
          children: [
            livePanel,
            _buildMobileCloseButton(),
            _buildMobileSwitchPortraitLayout(),
          ],
        ),
      );
    });
  }

  ///右侧调整参数
  FWidget _buildParameterAdjustmentView() {
    double? width = kIsMobile ? 300 : 400;
    if (_isPortrait) {
      width = null;
    }
    return FSafeArea(
      left: false,
      child: FContainer(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          border: Border.all(
            color: Colors.grey,
            width: 1,
          ),
        ),
        margin: EdgeInsets.all(5),
        width: width,
        height: _isPortrait ? MediaQuery.of(context).size.height - 300 : null,
        child: FColumn(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (!kIsMobile) ...[
              _miniSpace(),
              _buildProbeAndApplicationTitle(),
              _miniSpace(),
            ] else ...[
              _buildMobileControllerTitle(),
            ], //探头和应用
            if (_mobileSelectedPageIndex == null ||
                _mobileSelectedPageIndex == 0) ...[
              _buidlProbeTabs(), //探头选择
              FSizedBox(height: kIsMobile ? 3 : FSpacings.L),
              FExpanded(
                child: FObx(() {
                  return FContainer(
                    width: double.infinity,
                    padding: EdgeInsets.only(left: FSpacings.M),
                    child: controller.state.isSensorDataAvailable
                        ? FCenter(
                            child: FText(
                              i18nBook.remoteControl.noSensorDetected.t,
                              style: TextStyle(color: Colors.white),
                            ),
                          )
                        : _buildApplayDatas(),
                  );
                }),
              ),
              _horDivider(),
            ],
            if (_mobileSelectedPageIndex == null ||
                _mobileSelectedPageIndex == 1) ...[
              FSizedBox(height: kIsMobile ? 3 : 10),
              if (!kIsMobile) ...[
                _buildParameterTuningTitle(),
                _miniSpace(),
              ], //参数调节标题
              _buildModelTabs(), //模式选择
              const FSizedBox(height: FSpacings.L),
              _buildParameter(),
            ],
            if (!kIsMobile) ...[
              _miniSpace(),
              _buildParameterPage(),
              _miniSpace(),
              _horDivider(),
              _miniSpace(),
              _buildExitButton(),
              _miniSpace(),
            ],
          ],
        ),
      ),
    );
  }

  /// 参数调节
  FWidget _buildParameter() {
    return FObx(() {
      if (controller.state.currentSelectedMode == '') {
        return FCenter(
          child: FText(
            i18nBook.remoteControl.unsupported3D4DRemoteControl.t,
            textAlign: TextAlign.center,
            style: TextStyle(color: Colors.white),
          ),
        );
      } else {
        return _buildParameterButtons();
      }
    });
  }

  FWidget _buildParameterPage() {
    return FObx(() {
      if (controller.state.currentSelectedMode == '') {
        return FSizedBox();
      } else {
        return _buildParametersPageIndex();
      }
    });
  }

  FWidget _miniSpace() {
    return const FSizedBox(height: 5);
  }

  FWidget _buidlProbeTabs() {
    return FObx(() {
      return FScrollbar(
        controller: _probeTabsScrollController,
        child: FSingleChildScrollView(
          controller: _probeTabsScrollController,
          scrollDirection: Axis.horizontal,
          child: FRow(
            children: controller.state.allProbeDatas
                .map(
                  (e) => CustomButton<Probe>(
                    onPressed: (value) async {
                      /// 这部分是探头的
                      await controller.referParameters(
                        argsParameterValue: e.name,
                        loopsParameterValue: '1',
                        pathParameterValue: 'Probe',
                        controllerType: ControlDeviceParameterEnum
                            .ExecuteProbeApplicationSetting,
                      );
                    },
                    text: e.name,
                    data: e,
                    stopEventHandler: controller.stopEventHandler,
                    isSelected: e.name == controller.state.currentProbe,
                    decoration:
                        TuningParametersStyles.unSelectedBottomBorderDecoration,
                    textColor: Colors.white,
                    selectedDecoration:
                        TuningParametersStyles.bottomBorderDecoration,
                    width: 80,
                    height: 40,
                  ),
                )
                .toList(),
          ),
        ),
      );
    });
  }

  FWidget _buildApplayDatas() {
    return FObx(
      () => FScrollbar(
        controller: _applayDatasScrollController,
        child: FSingleChildScrollView(
          controller: _applayDatasScrollController,
          child: FWrap(
            spacing: 10,
            runSpacing: 10,
            alignment: WrapAlignment.start,
            children: controller.state.allApplyDatas
                .map(
                  (e) => CustomButton<ApplicationInfo>(
                    onPressed: (value) async {
                      // 这部分是应用的
                      await controller.referParameters(
                        argsParameterValue: e.id,
                        loopsParameterValue: '1',
                        pathParameterValue: 'Application',
                        controllerType: ControlDeviceParameterEnum
                            .ExecuteProbeApplicationSetting,
                      );
                    },
                    stopEventHandler: controller.stopEventHandler,
                    selectedDecoration: selectedBoxDecoration,
                    width: 120,
                    height: 40,
                    decoration: normalBoxDecoration,
                    textColor: Colors.white,
                    text: e.name,
                    data: e,
                    isSelected: e.id == controller.state.currentApply,
                  ),
                )
                .toList(),
          ),
        ),
      ),
    );
  }

  FWidget _buildProbeAndApplicationTitle() {
    return FRow(
      children: [
        const FSizedBox(width: 5),
        FText(
          i18nBook.realTimeConsultation.probesAndApplications.t,
          style: _texytStyle,
        ),
        const FSizedBox(width: 5),
        FExpanded(child: FContainer()),
      ],
    );
  }

  FWidget _buildParameterTuningTitle() {
    return FRow(
      children: [
        const FSizedBox(width: 5),
        FText(
          i18nBook.remoteControl.parameterAdjustment.t,
          style: _texytStyle,
        ),
      ],
    );
  }

  List<ApiInfo> availableModeInfos() {
    List<ApiInfo> sortedNumbers =
        List.from(controller.state.availableModeInfos);
    sortedNumbers.sort((a, b) {
      int i = 0;
      while (i < a.description!.length && i < b.description!.length) {
        int diff = a.description!.codeUnitAt(i) - b.description!.codeUnitAt(i);
        if (diff != 0) {
          return diff;
        }
        i++;
      }
      // 如果前缀相同，可以按照字符串长度进行比较
      return a.description!.length - b.description!.length;
    });

    return sortedNumbers;
  }

  FWidget _buildModelTabs() {
    return FObx(() {
      controller.state.availableModeInfos = availableModeInfos();
      return FScrollbar(
        controller: _modelTabsScrollController,
        isAlwaysShown: true, // 设置为始终显示
        child: FSingleChildScrollView(
          controller: _modelTabsScrollController,
          scrollDirection: Axis.horizontal,
          child: FContainer(
            alignment: Alignment.centerLeft,
            child: FRow(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                ...controller.state.availableModeInfos
                    .map(
                      (e) => FContainer(
                        margin: EdgeInsets.only(
                          right: 10,
                        ),
                        child: CustomButton<ApiInfo>(
                          onPressed: (value) async {
                            await controller.referParameters(
                              argsParameterValue: '0',
                              loopsParameterValue: '1',
                              pathParameterValue:
                                  e.parentDescription! + '\\' + e.description!,
                            );
                            controller.state.currectPageIndex = 1;
                          },
                          stopEventHandler: controller.stopEventHandler,
                          decoration: TuningParametersStyles
                              .unSelectedBottomBorderDecoration,
                          width: 80,
                          height: 40,
                          textColor: _primaryColor,
                          selectedDecoration:
                              TuningParametersStyles.bottomBorderDecoration,
                          text: e.description ?? '',
                          data: e,
                          isSelected: e.displayValue == 'Checked',
                        ),
                      ),
                    )
                    .toList(),
                if (kIsMobile)
                  ...controller.state.allModes.map((e) {
                    print(e.description);
                    if (e.description == "CF" || e.description == "Freeze") {
                      return FContainer(
                        margin: EdgeInsets.only(
                          right: 10,
                        ),
                        child: CustomButton<ApiInfo>(
                          onPressed: (value) async {
                            await controller.referParameters(
                              argsParameterValue: e.valuesMapString == 'Toggle:'
                                  ? _INT32_MAX
                                  : '0',
                              pathParameterValue: e.parentDescription! +
                                  '\\' +
                                  _harmonicDescription(e.description!),
                              loopsParameterValue: '1',
                            );
                          },
                          isDecreaseAndIncrease: e.valuesMapString ==
                              'Toggle:0;Decrease:-1;Increase:1',
                          canExecute: e.canExecute ?? false,
                          text: e.description ?? '',
                          data: e,
                          isSelected: e.displayValue == 'Checked',
                          width: 80,
                          height: 35,
                          stopEventHandler: controller.stopEventHandler,
                          decoration: normalBoxDecoration,
                          textColor: Colors.white,
                          selectedDecoration: selectedBoxDecoration,
                        ),
                      );
                    }
                    return FSizedBox();
                  }).toList(),
              ],
            ),
          ),
        ),
      );
    });
  }

  String _harmonicDescription(String description) {
    if (description == 'HAR') {
      return 'Harmonic';
    } else {
      return description;
    }
  }

  FWidget _buildFirstParameterTuningView() {
    return FObx(
      () {
        if (controller.state.consultationCode.isNullOrEmpty &&
            controller.state.isLiveConsultationController) {
          return FSizedBox();
        }
        return FirstParametersViewPage();
      },
    );
  }

  FWidget _buildParametersPageIndex() {
    return FObx(
      () => FTablePagination(
        currListLength: controller.state.totalPage,
        color: Colors.white,
        mainAxisAlignment: MainAxisAlignment.center,
        currPageIndex: controller.state.currectPageIndex,
        pageSize: 1,
        onChangePage: (pageIndex, listLength) {
          controller.state.currectPageIndex = pageIndex;
        },
        totalItemNumText: i18nBook.common.ofTerm.translate(
          [
            controller.state.totalPage.toString(),
          ],
        ),
        previousFivePageText: i18nBook.common.previousFivePageText.t,
        nextFivePageText: i18nBook.common.nextFivePageText.t,
      ),
    );
  }

  FWidget _buildExitButton() {
    return FRow(
      children: [
        FExpanded(child: FSizedBox()),
        FContainer(
          alignment: Alignment.center,
          width: 120,
          height: 50,
          child: FCustomExitButton(
            i18nBook.remoteControl.exitTuning.t,
            Icons.exit_to_app,
            () {
              // if (FPlatform.isPureWeb && Store.app.enableNewTab) {
              //   html.window.close();
              //   return;
              // }
              controller.ignoreAllGestures = false;
              if (controller.state.isLiveConsultationController) {
                ///退出会诊调参
                remoteControllerManager.applyRemoteConnectionAsync(
                  deviceCode: controller.state.deviceCode,
                  controlType: ControlDeviceParameterEnum.End,
                  roomCode: controller.state.consultationCode,
                );
                router.back();
                return;
              }
              router.back();
            },
            normalColor: Colors.white,
          ),
        ),
        const FSizedBox(width: 5)
      ],
    );
  }

  ///水平分割线
  FWidget _horDivider() {
    return FDivider(
      height: 1,
      thickness: 1,
      color: Colors.grey[400],
    );
  }

  FWidget _buildSecondFunctionButtons() {
    if (controller.state.secondPageInfos.isEmpty) {
      return FExpanded(
        child: FContainer(
          decoration: TuningParametersStyles.transparentBorderDecoration,
        ),
      );
    }
    return FExpanded(
      child: FSingleChildScrollView(
        child: FColumn(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            FObx(
              () {
                return _buildFWrap(
                  controller.state.secondPageInfos.map((e) {
                    return CustomButton<ApiInfo>(
                      onPressed: (value) async {
                        await controller.referParameters(
                          argsParameterValue: e.valuesMapString == 'Toggle:'
                              ? _INT32_MAX
                              : value,
                          loopsParameterValue: '1',
                          pathParameterValue:
                              e.parentDescription! + '\\' + e.description!,
                        );
                      },
                      width: 100,
                      height: 40,
                      stopEventHandler: controller.stopEventHandler,
                      decoration: normalBoxDecoration,
                      selectedDecoration: selectedBoxDecoration,
                      textColor: Colors.white,
                      text: e.description?.split(':')[1] ?? '',
                      data: e,
                      isSelected: e.displayValue == 'Checked',
                    );
                  }).toList(),
                );
              },
            ),
            FSizedBox(
              height: 15,
            ),
            FObx(
              () {
                return _buildFWrap(
                  controller.state.secondPageSelectInfos.map((e) {
                    return CustomValueSelect(
                      data: e,
                      width: 100,
                      height: 40,
                      title: e.description?.split(':')[1] ?? '',
                      decoration: normalBoxDecoration,
                      textColor: Colors.white,
                      onChanged: (value) async {
                        print('下拉框的值');
                        await controller.referParameters(
                          argsParameterValue: value.toString(),
                          pathParameterValue:
                              e.parentDescription! + '\\' + e.description!,
                          loopsParameterValue: '1',
                          controllerType:
                              ControlDeviceParameterEnum.RunExecuteApi,
                        );
                      },
                    );
                  }).toList(),
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  String _judgeNumber(num) {
    if (num > 0) {
      return '1';
    } else if (num < 0) {
      return '-1';
    } else {
      return '1';
    }
  }

  FWidget _buildFWrap(List<FWidget> wrapList) {
    return FWrap(
      runSpacing: 10,
      spacing: 10,
      children: wrapList,
    );
  }

  FWidget _buildThirdFunctionButtons() {
    if (controller.state.thirdPageInfos.isEmpty) {
      return FExpanded(
        child: FContainer(
          decoration: TuningParametersStyles.transparentBorderDecoration,
        ),
      );
    }
    return FExpanded(
      child: FSingleChildScrollView(
        child: FObx(() {
          return FWrap(
            spacing: 10,
            runSpacing: 10,
            children: controller.state.thirdPageInfos.map(
              (e) {
                return CustomValueButton(
                  data: e,
                  consultationCode: controller.state.consultationCode,
                  title: e.description?.split(':')[1] ?? '',
                  onChange: (value) async {
                    await controller.referParameters(
                      argsParameterValue: _judgeNumber(value),
                      loopsParameterValue: value.abs().toString(),
                      pathParameterValue:
                          e.parentDescription! + '\\' + e.description!,
                    );
                  },
                  width: 100,
                  decoration: normalBoxDecoration,
                  textColor: Colors.white,
                );
              },
            ).toList(),
          );
        }),
      ),
    );
  }

  FWidget _buildForthFunctionButtons() {
    if (controller.state.forthPageInfos.isEmpty) {
      return FExpanded(
        child: FContainer(
          decoration: TuningParametersStyles.transparentBorderDecoration,
        ),
      );
    }
    return FExpanded(
      child: FSingleChildScrollView(
        child: FObx(
          () => FWrap(
            runSpacing: 10,
            spacing: 10,
            children: controller.state.forthPageInfos
                .map(
                  (e) => CustomValueButton(
                    decoration: normalBoxDecoration,
                    data: e,
                    consultationCode: controller.state.consultationCode,
                    title: _setTitle('SGC', e.description ?? ''),
                    width: 100,
                    onChange: (value) async {
                      await controller.referParameters(
                        argsParameterValue: _judgeNumber(value),
                        loopsParameterValue: value.abs().toString(),
                        pathParameterValue:
                            e.parentDescription! + '\\' + e.description!,
                      );
                    },
                    textColor: Colors.white,
                  ),
                )
                .toList(),
          ),
        ),
      ),
    );
  }

  String _setTitle(String typeName, String description) {
    return '$typeName-${description.split(':')[0]}';
  }

  FWidget _buildFifthFunctionButtons() {
    if (controller.state.fifthPageInfos.isEmpty) {
      return FExpanded(
        child: FContainer(
          decoration: TuningParametersStyles.transparentBorderDecoration,
        ),
      );
    }
    return FExpanded(
      child: FSingleChildScrollView(
        child: FObx(
          () => FWrap(
            runSpacing: 10,
            spacing: 10,
            children: controller.state.fifthPageInfos
                .map(
                  (e) => CustomValueButton(
                    decoration: normalBoxDecoration,
                    data: e,
                    title: _setTitle('TGC', e.description ?? ''),
                    width: 100,
                    onChange: (value) async {
                      await controller.referParameters(
                        argsParameterValue: _judgeNumber(value),
                        loopsParameterValue: value.abs().toString(),
                        pathParameterValue:
                            e.parentDescription! + '\\' + e.description!,
                      );
                    },
                    textColor: Colors.white,
                  ),
                )
                .toList(),
          ),
        ),
      ),
    );
  }

  FWidget _buildParameterButtons() {
    if (kIsMobile) {
      return FExpanded(
        child: FStack(
          children: [
            FPositioned(
              left: 0,
              top: 0,
              bottom: 0,
              right: 0,
              child: FObx(
                () =>
                    _buildButtonsContentView(controller.state.currectPageIndex),
              ),
            ),
            FPositioned(
              left: 0,
              top: 0,
              bottom: 0,
              child: FContainer(
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.white.withOpacity(0.2),
                ),
                child: FInkWell(
                  onTap: () {
                    if (controller.state.currectPageIndex > 1) {
                      controller.state.currectPageIndex--;
                    }
                  },
                  child: FIcon(
                    Icons.keyboard_arrow_left,
                    color: Colors.white,
                    size: 40,
                  ),
                ),
              ),
            ),
            FPositioned(
              right: 0,
              top: 0,
              bottom: 0,
              child: FContainer(
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.white.withOpacity(0.2),
                ),
                child: FInkWell(
                  onTap: () {
                    if (controller.state.currectPageIndex < 5) {
                      controller.state.currectPageIndex++;
                    }
                  },
                  child: FIcon(
                    Icons.keyboard_arrow_right,
                    color: Colors.white,
                    size: 40,
                  ),
                ),
              ),
            ),
          ],
        ),
      );
    } else {
      return FExpanded(
        child: FObx(() {
          var currectPageIndex = controller.state.currectPageIndex;
          return FRow(
            children: [
              FHoverBorderButton(
                icon: Icons.keyboard_arrow_left,
                onTap: () {
                  if (controller.state.currectPageIndex > 1) {
                    controller.state.currectPageIndex--;
                  }
                },
                boxDecoration: normalBoxDecoration,
              ),
              FExpanded(
                child: FColumn(
                  children: [
                    if (currectPageIndex == 1) ...[
                      _buildFirstParameterTuningView(),
                    ] else if (currectPageIndex == 2) ...[
                      _buildSecondFunctionButtons(),
                    ] else if (currectPageIndex == 3) ...[
                      _buildThirdFunctionButtons(),
                    ] else if (currectPageIndex == 4) ...[
                      _buildForthFunctionButtons(),
                    ] else if (currectPageIndex == 5) ...[
                      _buildFifthFunctionButtons(),
                    ],
                    if (kIsMobile) ...[
                      FText(
                        i18nBook.remoteControl.pagination.translate(
                            ['$currectPageIndex', '$totalPageCount']),
                        style: _texytStyle,
                      ),
                    ],
                  ],
                ),
              ),
              FHoverBorderButton(
                icon: Icons.keyboard_arrow_right,
                boxDecoration: normalBoxDecoration,
                onTap: () {
                  if (controller.state.currectPageIndex < 5) {
                    controller.state.currectPageIndex++;
                  }
                },
              ),
            ],
          );
        }),

        //可调节参数按钮
      );
    }
  }

  FWidget _buildMobileControllerTitle() {
    return FRow(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        _titleButton(i18nBook.realTimeConsultation.probesAndApplications.t,
            _mobileSelectedPageIndex == 0, () {
          if (_mobileSelectedPageIndex == 0) {
            return;
          }
          setState(() {
            _mobileSelectedPageIndex = 0;
          });
        }),
        _titleButton(i18nBook.remoteControl.parameterAdjustment.t,
            _mobileSelectedPageIndex == 1, () {
          if (_mobileSelectedPageIndex == 1) {
            return;
          }
          setState(() {
            _mobileSelectedPageIndex = 1;
          });
        }),
      ],
    );
  }

  FWidget _titleButton(String title, bool isSelected, void Function()? onTap) {
    return FGestureDetector(
      businessParent: widget,
      name: 'probe and application',
      child: FContainer(
        height: 35,
        alignment: Alignment.center,
        padding: EdgeInsets.symmetric(horizontal: 5),
        decoration: isSelected
            ? TuningParametersStyles.bottomBorderDecoration
            : TuningParametersStyles.unSelectedBottomBorderDecoration,
        child: FText(
          title,
          style: kIsMobile
              ? TextStyle(color: Colors.white, fontSize: 12)
              : TextStyle(color: Colors.white),
        ),
      ),
      onTap: onTap,
    );
  }

  FPositioned _buildMobileCloseButton() {
    return FPositioned(
      left: _isPortrait ? null : 10,
      right: _isPortrait ? 10 : null,
      top: 10,
      child: FInkWell(
        child: const FIcon(
          Icons.close,
          size: 28,
          color: Colors.white,
        ),
        onTap: () {
          router.back();
        },
      ),
    );
  }

  FPositioned _buildMobileSwitchPortraitLayout() {
    return FPositioned(
      left: 10,
      bottom: 10,
      child: FSafeArea(
        child: FInkWell(
          child: const FIcon(
            Icons.screen_rotation,
            size: 28,
            color: Colors.white,
          ),
          onTap: () {
            setState(() {
              _isPortrait = !_isPortrait;
            });
            if (_isPortrait) {
              _setPortraitMode();
            } else {
              _setLandscapeMode();
            }
          },
        ),
      ),
    );
  }

  FWidget _portraitLayout() {
    return FContainer(
      color: background,
      child: FColumn(
        children: [
          _buildDeviceLiveView(),
          _buildParameterAdjustmentView(),
        ],
      ),
    );
  }

  FWidget _deviceNameWrapper(FWidget webview) {
    return FStack(
      children: [
        webview,
        FSizedBox(
          height: FPaddings.SECONDARY_BUTTON,
          child: FCenter(
            child: FText(
              controller.state.deviceExtendInfoDTO!.dto.name ?? '',
              style: TextStyle(
                color: Colors.white,
                fontSize: FFontSizes.BODY,
              ),
            ),
          ),
        ),
      ],
    );
  }

  ///横屏
  void _setLandscapeMode() {
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
  }

  ///竖屏
  void _setPortraitMode() {
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
  }

  FWidget _buildButtonsContentView(int currectPageIndex) {
    Offset _startPosition = Offset(0, 0);
    double _distance = 0;
    return FGestureDetector(
      businessParent: widget,
      name: 'ButtonsContentView',
      onHorizontalDragDown: (details) {
        _startPosition = details.globalPosition;
      },
      onHorizontalDragUpdate: (details) {
        // 计算距离
        _distance = details.globalPosition.dx - _startPosition.dx;
      },
      onHorizontalDragEnd: (details) {
        print('_startPosition$_startPosition   _distance$_distance');
        if (_distance > 100) {
          Future.delayed(Duration(milliseconds: 200), () {
            if (controller.state.currectPageIndex > 1) {
              controller.state.currectPageIndex--;
            }
          });
        } else if (_distance < -100) {
          Future.delayed(Duration(milliseconds: 200), () {
            if (controller.state.currectPageIndex < 5) {
              controller.state.currectPageIndex++;
            }
          });
        }
      },
      child: FColumn(
        children: [
          if (currectPageIndex == 1) ...[
            _buildFirstParameterTuningView(),
          ] else if (currectPageIndex == 2) ...[
            _buildSecondFunctionButtons(),
          ] else if (currectPageIndex == 3) ...[
            _buildThirdFunctionButtons(),
          ] else if (currectPageIndex == 4) ...[
            _buildForthFunctionButtons(),
          ] else if (currectPageIndex == 5) ...[
            _buildFifthFunctionButtons(),
          ],
          if (kIsMobile) ...[
            FText(
              i18nBook.remoteControl.pagination
                  .translate(['$currectPageIndex', '$totalPageCount']),
              style: _texytStyle,
            ),
          ],
        ],
      ),
    );
  }
}
