import 'package:fis_i18n/i18n.dart';
import 'package:fis_lib_qrcode/qr_flutter.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/usual/tab_button.dart';
import 'package:fis_ui/usual/tab_button_group.dart';
import 'package:fis_ui/values/font_sizes.dart';
import 'package:fis_ui/values/spacings.dart';
import 'package:fis_ui/values/paddings.dart';
import 'package:fis_ui/widgets/layout/button_group.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/common_util.dart';
import 'package:flyinsono/common_business.dart';
import 'package:flyinsono/managers/interfaces/user_info.dart';
import 'package:flyinsono/managers/interfaces/webview_controller.dart';
import 'package:flyinsono/pages/auth/clause_view/state.dart';
import 'package:flyinsono/pages/auth/clause_view/view.dart';
import 'package:flyinsono/pages/setting/server_setting/widgets/exist_address_selected.dart';
import 'package:flyinsono/pages/upgrade/upgrade_widgets/upgrade_center.dart';
import 'package:flyinsono/pages/upgrade/upgrade_wrapper.dart';
import 'package:flyinsono/pages/user/user_center/controller.dart';
import 'package:flyinsono/rpc.dart';
import 'package:flyinsono/views/common/device_live/widgets/clause_page.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/widgets/simple_Info.dart';
import 'package:flyinsono/views/desktop/vbox_setting/view.dart';
import 'package:get/get.dart';
import 'package:fis_common/index.dart';
import '../hardware_detection/index.dart';
import 'index.dart';
import 'widgets/user_select.dart';

class UserSettingPage extends FisView<UserSettingController> implements FPage {
  static const C_TITLE_INTERVAL_WIDTH = 250.0;
  UserSettingPage({Key? key}) : super(key: key);
  @override
  String get pageName => "UserSettingPage";

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

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

  _DesktopLayout(this.businessParent, {Key? key}) : super(key: key);
  @override
  FState<_DesktopLayout> createState() => _DesktopLayoutState();
}

class _DesktopLayoutState extends FState<_DesktopLayout> {
  final controller = Get.put((UserSettingController()));
  final userInfoManager = Get.find<IUserInfoManager>();
  final fontStyle = TextStyle(
    fontSize: 14,
  );
  bool get isWindowsOrMacs => FPlatform.isMacOS || FPlatform.isWindows;
  FWidget _buildSettingBody = FSizedBox();
  String? _vBoxSettingPageUrl;
  @override
  FWidget build(BuildContext context) {
    return FContainer(
      padding: EdgeInsets.all(30),
      color: const Color.fromRGBO(234, 234, 234, 1),
      child: FColumn(
        mainAxisSize: MainAxisSize.max,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildSettingTabs(),
          FExpanded(
            child: FContainer(
              decoration: BoxDecoration(
                color: Colors.white,
              ),
              child: FObx(
                () {
                  switch (controller.state.settingTabIndex) {
                    case 0:
                      _buildSettingBody = _buildGeneralSettingBody();
                      break;
                    case 1:
                      _buildSettingBody = HardwareDetectionPage();
                      break;
                    case 2:
                      _buildSettingBody = _buildPersonalizationBody();
                      break;
                    case 3: //Todo:finlay windows魔盒配置页面加载
                      if (_vBoxSettingPageUrl.isNullOrEmpty) {
                        _buildSettingBody = FSizedBox();
                      } else {
                        _buildSettingBody = VBoxSettingPage(
                          url:
                              'http://${controller.state.vBoxSettingPageUrl}:80/#/?login=vbox',
                        );
                      }
                      break;
                    default:
                      _buildSettingBody = FCenter(
                        child: FText(i18nBook.user.underDevelopment.t),
                      );
                      break;
                  }
                  return _buildSettingBody;
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  void initState() {
    _vBoxSettingPageUrl = controller.state.vBoxSettingPageUrl;
    controller.onVBoxSettingPageUrlChange
        .addListener(_onVBoxSettingPageUrlChange);
    super.initState();
  }

  @override
  void dispose() {
    UpgradeWrapper.cancelUpdateOnDispose();
    controller.onVBoxSettingPageUrlChange
        .removeListener(_onVBoxSettingPageUrlChange);
    Future.delayed(const Duration(milliseconds: 100), () {
      final hardWareController = Get.find<HardwareDetectionController>();
      hardWareController.stopDetectingCamera();
    });
    super.dispose();
  }

  FWidget specialWidget(SimpleInfoItem data) {
    return FContainer(
      width: 300,
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(
            width: 0.5,
            color: FTheme.ins.colorScheme.line,
          ),
        ),
      ),
      child: FRow(
        children: [
          _buildImage(data.image ?? ""),
          FExpanded(
            child: FColumn(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                if (data.itemCode.isNotEmpty)
                  FText(data.name ?? "",
                      style: fontStyle, overflow: TextOverflow.ellipsis),
                if (data.role!.isNotEmpty)
                  FMaterialTooltip(
                    message: data.role!,
                    child: FText(data.role!,
                        style: fontStyle, overflow: TextOverflow.ellipsis),
                  ),
                if (data.des!.isNotEmpty)
                  FMaterialTooltip(
                    child: FText(
                      i18nBook.user.skilledAreaWithDevider.t +
                          data.des!.join(","),
                      style: fontStyle,
                      overflow: TextOverflow.ellipsis,
                    ),
                    message: data.des!.join(","),
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 关于杏聆荟
  List<FWidget> _aboutSettings() {
    return [
      _buildSettingItem(
        title: i18nBook.setting.productVersion.t,
        settingItemWidget: FRow(
          children: [
            FText(
              i18nBook.setting.currentVersion.t +
                  ":${UpgradeCenter.currentVersion}",
              style: TextStyle(
                fontSize: FFontSizes.H6,
              ),
            ),
            FSizedBox(
              width: 10,
            ),
            if (isWindowsOrMacs)
              FElevatedButton(
                businessParent: widget.businessParent,
                child: FText(i18nBook.setting.checkForUpdates.t),
                name: i18nBook.setting.checkForUpdates.t,
                onPressed: () async {
                  if (UpgradeCenter.isChecking) {
                    UpgradeCenter.isChecking = false;
                  }
                  await UpgradeWrapper.invokeUpgradeDirectly(
                    context,
                    true,
                    checkManually: true,
                  );
                },
              ),
            FSizedBox(
              width: 10,
            ),
          ],
        ),
        otherSettings: FContainer(
          padding: EdgeInsets.only(
            left: 30,
          ),
          child: FColumn(
            children: [
              FSizedBox(
                height: 10,
              ),
            ],
          ),
        ),
      ),
      if (isWindowsOrMacs) ...[
        _buildSettingItem(
          title: i18nBook.setting.runLog.t,
          settingItemWidget: FElevatedButton(
            businessParent: widget.businessParent,
            child: FText(i18nBook.setting.exportLog.t),
            name: i18nBook.setting.exportLog.t,
            onPressed: () {
              controller.exportLog();
            },
          ),
        ),
        FSizedBox(
          height: 10,
        ),
      ],

      //暂时注释，因为目前还没有官网
      // _buildSettingItem(
      //     title: i18nBook.setting.downloadMobileApp.t,
      //     isSpecial: true,
      //     isSpecialRight: false,
      //     settingItemWidget: FRow(
      //       children: [
      //         _buildMobileDownLoadQr('https://ios', 'iOS'),
      //         _buildMobileDownLoadQr('https://android', 'Android'),
      //       ],
      //     )),
      _buildSettingItem(
        title: i18nBook.user.accountCancellation.t,
        settingItemWidget: FElevatedButton(
          businessParent: widget.businessParent,
          child: FText(
            i18nBook.common.cancellation.t,
          ),
          name: i18nBook.common.cancellation.t,
          onPressed: () {
            Get.dialog(
              _buildClauseDialog(i18nBook.user.fisAccountCancellation.t),
              arguments: ClauseDocType.accountCancellation,
            );
          },
        ),
      ),
      if (Store.app.isOpenDebugBox) ...[
        _buildSettingItem(
          title: "Debug secret key:",
          isSpecial: true,
          settingItemWidget: FBorderInput(
            width: 300,
            onChanged: (v) {
              if (v == '0000000000') {
                controller.openConsole();
              }
            },
          ),
        ),
      ],
    ];
  }

  /// pc 端的弹框
  FWidget _buildClauseDialog(String title) {
    return FSimpleDialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
      bottomButton: FContainer(
        alignment: Alignment.center,
        padding: EdgeInsets.symmetric(vertical: 15),
        width: double.infinity,
        child: FButtonGroup(
            buttonPadding: FPaddings.SECONDARY_BUTTON,
            spacing: FSpacings.MINI_BUTTON,
            children: [
              FDelayedTiriggerButton(
                name: i18nBook.user.fisAccountCancellation.t,
                businessParent: widget.businessParent,
                style: ButtonStyle(
                  padding: MaterialStateProperty.all(
                    const EdgeInsets.symmetric(
                      vertical: 15,
                      horizontal: 25,
                    ),
                  ),
                ),
                onPressed: () {
                  final webviewControllerManager =
                      Get.find<IWebviewControllerManager>();
                  webviewControllerManager.webviewInteractiveController
                      ?.onDialogCreate();
                  // router.dialog(
                  //   () => PasswordValidationPage(),
                  // );
                  Get.find<UserCenterController>().commonUserLogOff();
                },
                child: FText(
                  i18nBook.common.cancellation.t,
                ),
              ),
              FOutlinedButton(
                name: "cancel",
                businessParent: widget.businessParent,
                onPressed: () => Get.back(),
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(
                    Colors.white,
                  ),
                  padding: MaterialStateProperty.all(
                    EdgeInsets.symmetric(
                      vertical: 15,
                      horizontal: 25,
                    ),
                  ),
                ),
                child: FText(
                  i18nBook.common.cancel.t,
                  style: TextStyle(
                    color: Color.fromRGBO(61, 146, 252, 1),
                  ),
                ),
              ),
            ]),
      ),
      onClose: router.back,
      title: FText(
        title,
        style: TextStyle(
          color: Colors.white,
        ),
      ),
      okString: i18nBook.common.confirm.t,
      cancelString: i18nBook.common.cancel.t,
      children: [
        FContainer(
          width: 800,
          height: 550,
          padding: EdgeInsets.only(
            // top: 5,
            // bottom: 0,
            right: 15,
            left: 15,
          ),
          child: ClauseViewPage(),
        ),
      ],
    );
  }

  ///个性化设置--会诊设置
  List<FWidget> _buildConsultationSettingsBody() {
    return [
      _buildSettingItem(
        title: i18nBook.setting.myAssistant.t,
        settingItemWidget: _buildpersonalizationSelect(
          controller.state.assistantList,
          i18nBook.setting.chooseAssistant.t,
          true,
          controller.state.bindingAssistant,
        ),
        otherSettings: FContainer(
          margin: EdgeInsets.only(
              left: i18nBook.isCurrentChinese ? 120 : 200, top: 10),
          child: FText(
            i18nBook.setting.chooseAssistantTip.t,
            style: TextStyle(
              fontSize: FFontSizes.SMALL,
              color: FTheme.ins.colorScheme.textTips,
            ),
          ),
        ),
        isSpecialRight: false,

        /// TODO:[Gavin] 多语言-UI-整合
        titleWidth: i18nBook.isCurrentChinese ? 120 : 200,
      ),
      FSizedBox(height: 20),
      _buildSettingItem(
        title: i18nBook.setting.assistantPhysician.t,
        settingItemWidget: _buildpersonalizationSelect(
          controller.state.certifiedPhysicianList,
          i18nBook.setting.chooseAssistantPhysician.t,
          false,
          controller.state.bindingAssistantPhysician,
        ),
        otherSettings: FContainer(
          margin: EdgeInsets.only(
              left: i18nBook.isCurrentChinese ? 120 : 200, top: 10),
          child: FText(
            i18nBook.setting.chooseAssistantPhysicianTip.t,
            style: TextStyle(
              fontSize: FFontSizes.SMALL,
              color: FTheme.ins.colorScheme.textTips,
            ),
          ),
        ),
        isSpecialRight: false,

        /// TODO:[Gavin] 多语言-UI-整合
        titleWidth: i18nBook.isCurrentChinese ? 120 : 200,
      ),
    ];
  }

  /// 通用设置
  FWidget _buildGeneralSettingBody() {
    return FSingleChildScrollView(
      child: FContainer(
        padding: EdgeInsets.only(bottom: 15),
        child: FColumn(
          mainAxisSize: MainAxisSize.max,
          children: [
            _buildMoudleItem(
              title: i18nBook.setting.currency.t,
              moudleSetting: _generalSettings(),
            ),
            _buildMoudleItem(
              title: i18nBook.setting.networkSettings.t,
              moudleSetting: _networkSettings(),
            ),

            ///Todo:finlay
            if ((CartSystemPlatform.isCartSystemVersion) || kDebugMode) ...[
              _buildMoudleItem(
                title: i18nBook.common.report.t,
                moudleSetting: [
                  _buildSettingItem(
                    settingItemWidget: FElevatedButton(
                      businessParent: widget.businessParent,
                      child: FText(i18nBook.remoteControl.printerSettings.t),
                      name: i18nBook.remoteControl.printerSettings.t,
                      onPressed: () {
                        controller.onPrinterSettingsClick();
                      },
                    ),
                    title: i18nBook.remoteControl.printerSettings.t,
                  ),
                ],
              ),
              // _buildMoudleItem(
              //   //Todo:finlay  网络配置工具
              //   title: i18nBook.setting.networkConnectionUtility.t,
              //   moudleSetting: [
              //     _buildSettingItem(
              //       settingItemWidget: FElevatedButton(
              //         businessParent: widget.businessParent,
              //         child: FText(i18nBook.setting.configuration.t),
              //         name: i18nBook.setting.wiredNetworkConnection.t,
              //         onPressed: () {
              //           controller.onNetworkSettingsClick();
              //         },
              //       ),
              //       title: i18nBook.setting.wiredNetworkConnection.t,
              //     ),
              //     _buildSettingItem(
              //       settingItemWidget: FElevatedButton(
              //         businessParent: widget.businessParent,
              //         child: FText(i18nBook.setting.configuration.t),
              //         name: i18nBook.setting.wirelessNetworkConnection.t,
              //         onPressed: () {
              //           controller.onNetworkWifiSetting();
              //         },
              //       ),
              //       title: i18nBook.setting.wirelessNetworkConnection.t,
              //     ),
              //     _buildSettingItem(
              //       settingItemWidget: FElevatedButton(
              //         businessParent: widget.businessParent,
              //         child: FText(i18nBook.common.refresh.t),
              //         name: i18nBook.setting.refreshDNS.t,
              //         onPressed: () {
              //           FConfirmAlert.show(
              //             context: Get.context!,
              //             title: i18nBook.common.tip.t,
              //             subTitle: i18nBook.setting.confirmDNSRefresh.t,
              //             confrimLabel: i18nBook.common.confirm.t,
              //             cancelLabel: i18nBook.common.cancel.t,
              //             businessParent: widget.businessParent,
              //             onConfirm: () async {
              //               controller.flushDNS();
              //             },
              //           );
              //         },
              //       ),
              //       title: i18nBook.setting.refreshDNS.t,
              //     ),
              //   ],
              // ),
            ],
            _buildMoudleItem(
              title: i18nBook.setting.aboutFlyinsono.t,
              isShowLine: false,
              moudleSetting: _aboutSettings(),
            ),
          ],
        ),
      ),
    );
  }

  FWidget _buildImage(String? isImage) {
    var child;
    isImage!.isEmpty
        ? child = FImage.asset(
            'assets/images/avatar_man.png',
            width: 50,
            height: 50,
            fit: BoxFit.cover,
          )
        : child = FImage.network(
            isImage,
            width: 50,
            height: 50,
            fit: BoxFit.cover,
          );
    return FContainer(
      margin: EdgeInsets.only(
        right: 15,
      ),
      child: FClipRRect(
        borderRadius: BorderRadius.circular(
          25,
        ),
        child: child,
      ),
    );
  }

  FWidget _buildMoudleItem({
    required String title,
    List<FWidget>? moudleSetting,
    bool? isShowLine = true,
  }) {
    List<FWidget> moudleSettingList = [
      FText(
        title,
        style: TextStyle(
          fontSize: FFontSizes.H4,
          fontWeight: FontWeight.bold,
        ),
      ),
    ];
    moudleSettingList.addAll(moudleSetting ?? []);
    return FContainer(
      width: double.infinity,
      margin: EdgeInsets.only(
        top: 30,
        left: 30,
      ),
      decoration: BoxDecoration(
        border: isShowLine!
            ? Border(
                bottom: BorderSide(color: FTheme.ins.colorScheme.line),
              )
            : Border(),
      ),
      child: FColumn(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: moudleSettingList,
      ),
    );
  }

  ///创建个性化设置Widget
  FWidget _buildPersonalizationBody() {
    return FSingleChildScrollView(
      child: FColumn(
        mainAxisSize: MainAxisSize.max,
        children: [
          _buildMoudleItem(
            title: i18nBook.setting.consultationSettings.t,
            moudleSetting: _buildConsultationSettingsBody(),
            isShowLine: false,
          ),
        ],
      ),
    );
  }

  ///个性化设置的下拉框
  FWidget _buildpersonalizationSelect(
    List<SimpleInfoItem> sourseList,
    String hintText,
    bool isAssistant,
    String? selectedCode,
  ) {
    // String? selectedCode;
    // selectedCode = controller.setselectedCode(isAssistant, sourseList);
    if (selectedCode.isNullOrEmpty) {
      if (isAssistant) {
        controller.state.myAssistantName =
            i18nBook.realTimeConsultation.notSet.t;
      } else {
        controller.state.assistantPhysicianName =
            i18nBook.realTimeConsultation.notSet.t;
      }
    } else {
      userInfoManager.getUserByCode(selectedCode!).then((value) {
        if (isAssistant) {
          controller.state.myAssistantName =
              value.displayName ?? i18nBook.realTimeConsultation.notSet.t;
        } else {
          controller.state.assistantPhysicianName =
              value.displayName ?? i18nBook.realTimeConsultation.notSet.t;
        }
      });
    }
    return FRow(
      children: [
        FContainer(
            width: 220,
            height: 30,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              border: Border.all(
                color: Colors.grey[200]!, // 边框颜色
                width: 1, // 边框宽度
                style: BorderStyle.solid, // 边框样式
              ),
            ),
            margin: EdgeInsets.symmetric(horizontal: 10),
            child: FObx(
              () {
                String name = isAssistant
                    ? controller.state.myAssistantName
                    : controller.state.assistantPhysicianName;
                return FText(name);
              },
            )),
        FPrelayoutButtonWrapper(
          possibleValues: [
            i18nBook.common.add.t,
            i18nBook.upload.selectAgain.t
          ],
          child: FElevatedButton(
            style: ButtonStyle(
              padding: MaterialStatePropertyAll(EdgeInsets.all(0)),
            ),
            child: FText(selectedCode.isNullOrEmpty
                ? i18nBook.common.add.t
                : i18nBook.upload.selectAgain.t),
            onPressed: () {
              router.dialog(
                () => FUserSelect(
                  selectedCode,
                  sourseList,
                  (value) {
                    selectedCode = value?.itemCode;
                    if (isAssistant) {
                      setState(() {});
                    } else {
                      setState(() {});
                    }

                    if (isAssistant) {
                      controller.state.bindingAssistant = value?.itemCode ?? '';
                    } else {
                      controller.state.bindingAssistantPhysician =
                          value?.itemCode ?? '';
                    }
                    controller.updateMyOrganizationAssistant(
                        controller.state.bindingAssistant,
                        controller.state.bindingAssistantPhysician);
                  },
                  (keyword, pageIndex) async {
                    return userInfoManager.getUserPages(
                      organizationCode: Store.user.rootOrganizationCode!,
                      roleCodes: isAssistant
                          ? [RoleType.expertAssistant]
                          : [RoleType.certifiedPhysician],
                      keyword: keyword,
                      pageIndex: pageIndex,
                    );
                  },
                ),
              );
            },
            businessParent: this.widget.businessParent,
            name: hintText,
          ),
        ),
      ],
    );
  }

  FWidget _buildSettingItem({
    required String title,
    required FWidget settingItemWidget,
    FWidget? otherSettings,
    bool? isSpecial = false,
    bool isSpecialRight = true,
    double? titleWidth = UserSettingPage.C_TITLE_INTERVAL_WIDTH,
  }) {
    return FContainer(
      margin: isSpecial!
          ? EdgeInsets.symmetric(vertical: 30)
          : EdgeInsets.symmetric(vertical: 5),
      child: FColumn(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          FRow(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              FContainer(
                width: titleWidth,
                child: FText(
                  title,
                  style: TextStyle(
                    fontSize: FFontSizes.H6,
                  ),
                ),
              ),
              if (isSpecialRight)
                FSizedBox(
                  width: 30,
                ),
              settingItemWidget,
            ],
          ),
          otherSettings ?? FSizedBox(),
        ],
      ),
    );
  }

  /// 通用设置
  FWidget _buildSettingTabs() {
    return FObx(
      () => FTabButtonGroup(
        [
          FTabButton(
            businessParent: widget.businessParent,
            name: "generalSettings",
            tabTitle: i18nBook.setting.generalConfiguration.t,
            index: 0,
            activeIndex: controller.state.settingTabIndex,
            onCallbackTap: () {
              controller.state.settingTabIndex = 0;
            },

            /// TODO:[Gavin] 多语言-UI-整合
            width: i18nBook.isCurrentChinese ? 120 : 200,
          ),
          FTabButton(
            businessParent: widget.businessParent,
            name: "checkReport",
            tabTitle: i18nBook.setting.detectionAssistant.t,
            index: 1,
            activeIndex: controller.state.settingTabIndex,
            onCallbackTap: () async {
              if (CartSystemPlatform.isCartSystemVersion) {
                rpc.platform.stopPreview();
              }
              controller.state.settingTabIndex = 1;
            },

            /// TODO:[Gavin] 多语言-UI-整合
            width: i18nBook.isCurrentChinese ? 120 : 200,
          ),
          _isBuildPersonalizationTab(),

          ///Todo:finlay  推车加载超声机设置页面
          if (CartSystemPlatform.isCartSystemVersion || kDebugMode)
            FTabButton(
              businessParent: widget.businessParent,
              name: i18nBook.setting.vBoxSetting.t,
              tabTitle: i18nBook.setting.vBoxSetting.t,
              index: 3,
              activeIndex: controller.state.settingTabIndex,
              onCallbackTap: () {
                if (UpgradeCenter.isChecking) {
                  //isChecking会导致webview的交互被禁用，设置为false解决超声机设置页面无法交互的问题
                  UpgradeCenter.isChecking = false;
                }
                try {
                  final hardWareController =
                      Get.find<HardwareDetectionController>();
                  hardWareController.stopDetectingCamera();
                } catch (e) {
                  logger.w("Stop camera detecting while load sonopost live");
                }
                rpc.platform.searchvBox();
                controller.state.settingTabIndex = 3;
                controller.busy = true;
                Future.delayed(Duration(milliseconds: 30), () {
                  if (controller.busy) {
                    controller.busy = false;
                  }
                });
              },
              width: i18nBook.isCurrentChinese ? 120 : 200,
            )
        ],
      ),
    );
  }

  /// 通用
  List<FWidget> _generalSettings() {
    return [
      // if (isWindowsOrMacs && !CartSystemPlatform.isCartSystemVersion)
      //   _buildSettingItem(
      //     title: i18nBook.setting.startUpAutomatically.t,
      //     settingItemWidget: FObx(
      //       () => FSwitch(
      //         value: controller.state.isAutoStartUp,
      //         onChanged: (value) {
      //           controller.onChangeAutoStartUp(value);
      //         },
      //       ),
      //     ),
      //   ),
      _buildSettingItem(
        title: i18nBook.setting.autoPopupLabel.t,
        settingItemWidget: FObx(
          () => FSwitch(
            value: controller.state.isAutoPopupReportTag,
            onChanged: (value) {
              controller.onChangeAutoPopupReportTag(value);
            },
          ),
        ),
        otherSettings: FText(
          i18nBook.setting.automaticallyPopupTag.t,
          textAlign: TextAlign.left,
          style: TextStyle(
            fontSize: FFontSizes.SMALL,
            color: FTheme.ins.colorScheme.textTips,
          ),
        ),
      ),
      if (!CartSystemPlatform.isCartSystemVersion)
        _buildSettingItem(
          title: i18nBook.setting.enableSecondWindow.t,
          settingItemWidget: FObx(() => FRow(
                children: [
                  FSwitch(
                    value: controller.state.isUseSecondWindow,
                    onChanged: (value) {
                      controller.onChangeUseSecondWindow(value);
                    },
                  ),
                  controller.state.secondWindowOpening
                      ? FRow(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            FContainer(
                              width: 12,
                              height: 12,
                              child: FCircularProgressIndicator(
                                strokeWidth: 1,
                                valueColor: AlwaysStoppedAnimation(Colors.grey),
                              ),
                            ),
                            FSizedBox(
                              width: 5,
                            ),
                            FText(
                              i18nBook.setting.switching.t,
                              style: TextStyle(
                                  fontSize: FFontSizes.SMALL,
                                  color: Colors.grey,
                                  height: 1),
                            ),
                          ],
                        )
                      : FContainer(),
                ],
              )),
          otherSettings: FText(
            i18nBook.setting.secondWindowConfigStatement.t,
            textAlign: TextAlign.left,
            style: TextStyle(
              fontSize: FFontSizes.SMALL,
              color: FTheme.ins.colorScheme.textTips,
            ),
          ),
        ),
      _buildSettingItem(
        title: i18nBook.common.language.t,
        isSpecial: true,
        settingItemWidget: FSelect<FSelectModel, String>(
          source: [
            FSelectModel(code: 'zh', name: '简体中文'),
            FSelectModel(code: 'en', name: 'English'),
            FSelectModel(code: 'ru', name: 'русский язык'),
            FSelectModel(code: 'es', name: 'Español'),
            FSelectModel(code: 'ro', name: 'Română'),
          ],
          fontFamily: FTheme.ins.localeSetting.fontFamily,
          value: controller.state.currLanguage,
          height: 34,
          optionLabelExtractor: (data) => data.name,
          optionValueExtractor: (data) => data.code,
          onSelectChanged: controller.onLanguageSelected,
        ),
      ),
      _buildSettingItem(
        title: i18nBook.live.maxViewCountOfDeviceLive.t,
        settingItemWidget: FObx(() {
          final curr = Store.user.deviceLiveMaxCount.toDouble();
          const max = 6;
          return FRow(
            children: [
              FSlider(
                value: curr,
                min: 1,
                max: max.toDouble(),
                divisions: max - 1,
                onChanged: (double value) {
                  Store.user.deviceLiveMaxCount = value.toInt();
                },
              ),
              const FSizedBox(width: FSpacings.M),
              FText(
                curr.toString(),
                style: const TextStyle(fontSize: FFontSizes.BODY),
              ),
            ],
          );
        }),
      ),
    ];
  }

  ///获取我的助理用户和助理医师信息
  Future<void> _getMyAssistantAndAssistantPhysician() async {
    await controller.getMyAssistantAndAssistantPhysician();
    setState(() {});
  }

  ///是否显示个性化设置
  FWidget _isBuildPersonalizationTab() {
    if (controller.state.isPersonalSettingAuth)
      return FTabButton(
        businessParent: widget.businessParent,
        name: "personalization",
        tabTitle: i18nBook.setting.personalization.t,
        index: 2,
        activeIndex: controller.state.settingTabIndex,
        onCallbackTap: () {
          controller.state.settingTabIndex = 2;
          _getMyAssistantAndAssistantPhysician();
        },

        /// TODO:[Gavin] 多语言-UI-整合
        width: i18nBook.isCurrentChinese ? 120 : 200,
      );
    return FSizedBox();
  }

  /// 网络设置
  List<FWidget> _networkSettings() {
    return [
      _buildSettingItem(
        title: i18nBook.setting.selectServer.t,
        isSpecial: true,
        settingItemWidget: FRow(
          children: [
            FObx(
              () => ExistAddressSelected(
                controller.state.serverList,
                (data) {
                  if (data.fullAddress != controller.state.currServer) {
                    controller.makeSureChangedNetwork(data.fullAddress);
                  }
                },
                (data) {
                  controller.onAddressOptionDeleted(data);
                  setState(() {});
                },
                controller.state.currServer,
                isShowTitle: false,
                width: 250,
                height: 35,
                isNeedChangeConfirm: true,
              ),
            ),
            FSizedBox(
              width: 10,
            ),
            FElevatedButton(
              businessParent: widget.businessParent,
              child: FText(i18nBook.setting.addServer.t),
              name: i18nBook.setting.addServer.t,
              onPressed: () {
                controller.onNetworkSettingClick();
              },
            ),
          ],
        ),
      ),
    ];
  }

  void _onVBoxSettingPageUrlChange(Object sender, String e) {
    _vBoxSettingPageUrl = e;
    print(_vBoxSettingPageUrl);
    if (_vBoxSettingPageUrl.isNullOrEmpty) {
      setState(() {
        _buildSettingBody = FSizedBox();
      });
    } else {
      controller.busy = false;
      setState(() {
        _buildSettingBody = VBoxSettingPage(
          url: 'http://${_vBoxSettingPageUrl!}:80/#/?login=vbox',
        );
      });
    }
  }
}

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

  _MobileLayout(this.businessParent, {Key? key}) : super(key: key);
  @override
  FState<_MobileLayout> createState() => _MobileLayoutState(businessParent);
}

class _MobileLayoutState extends FState<_MobileLayout> {
  ///父级节点
  final FPage businessParent;
  _MobileLayoutState(this.businessParent);

  /// 全局路由实例
  @override
  FWidget build(BuildContext context) {
    return FScaffold(
      resizeToAvoidBottomInset: false,
      appBar: _buildAboutFisAppBar(),
      body: FColumn(
        children: [
          SelectRow(
            title: i18nBook.auth.privacyPolicy2.t,
            hintText: i18nBook.isCurrentRussian ? '' : i18nBook.common.view.t,
            onClick: () {
              Get.to(
                () => ClausePage(title: i18nBook.auth.privacyPolicy.t),
                arguments: ClauseDocType.privacyPolicy,
                transition: Transition.rightToLeft,
                duration: ClauseViewPage.C_TRANSITION_DURATION,
              );
            },
          ),
          SelectRow(
            title: i18nBook.auth.userAgreement2.t,
            hintText: i18nBook.isCurrentRussian ? '' : i18nBook.common.view.t,
            onClick: () {
              Get.to(
                () => ClausePage(title: i18nBook.auth.userAgreement.t),
                arguments: ClauseDocType.userAgreement,
                transition: Transition.rightToLeft,
                duration: ClauseViewPage.C_TRANSITION_DURATION,
              );
            },
          ),
          SelectRow(
            title: i18nBook.setting.currentVersion.t,
            hintText: i18nBook.common.Select.t,
            value: UpgradeCenter.currentVersion,
            onClick: () => CommonUtil.debounce(
              () {
                UpgradeWrapper.invokeUpgradeDirectly(
                  context,
                  true,
                  checkManually: true,
                );
              },
            ),
          ),
          SelectRow(
            title: i18nBook.user.accountCancellation.t,
            hintText: '',
            value: '',
            onClick: () => _openAccountCancellation(),
          ),
          FExpanded(
            child: FContainer(),
          ),
          FText(
            "${i18nBook.common.vinnoTechnology.t}\n@2017 Vinno Corporation. All rights reserved.\n${i18nBook.common.suICPNo.t}",
            style: TextStyle(color: Colors.grey, fontSize: 14, height: 1.5),
            textAlign: TextAlign.center,
          ),
          FSizedBox(height: 20),
        ],
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    UpgradeWrapper.cancelUpdateOnDispose();
  }

  void _openAccountCancellation() {
    Get.to(
      () => _buildClausePage(
        i18nBook.user.fisAccountCancellation.t,
        FContainer(
          padding: EdgeInsets.symmetric(vertical: 5, horizontal: 15),
          child: FDelayedTiriggerButton(
            name: i18nBook.user.fisAccountCancellation.t,
            businessParent: businessParent,
            style: ButtonStyle(
              padding: MaterialStateProperty.all(
                const EdgeInsets.symmetric(
                  vertical: 15,
                  horizontal: 25,
                ),
              ),
            ),
            onPressed: () {
              final webviewControllerManager =
                  Get.find<IWebviewControllerManager>();
              webviewControllerManager.webviewInteractiveController
                  ?.onDialogCreate();
              Get.find<UserCenterController>().commonUserLogOff();
              // Get.to(
              //   PasswordValidationPage(),
              // );
            },
            child: FText(
              i18nBook.common.cancellation.t,
            ),
          ),
        ),
      ),
      arguments: ClauseDocType.accountCancellation,
      transition: Transition.rightToLeft,
      duration: ClauseViewPage.C_TRANSITION_DURATION,
    );
  }

  /// 手机端的页面
  FWidget _buildClausePage(String title, FWidget button) {
    return FScaffold(
      appBar: FAppBar(
        title: FText(title),
        backgroundColor: FTheme.ins.colorScheme.primary,
        elevation: 0,
        leading: FIconButton(
          icon: FIcon(Icons.close_rounded),
          onPressed: () {
            router.back();
          },
          businessParent: this.businessParent,
          name: "Close",
        ),
      ),
      body: FSafeArea(
        child: FColumn(
          children: [
            FExpanded(
              child: ClauseViewPage(),
            ),
            FContainer(
              height: 60,
              alignment: Alignment.center,
              child: button,
            )
          ],
        ),
      ),
    );
  }

  _buildAboutFisAppBar() {
    return FAppBar(
      title: FText(
        i18nBook.setting.aboutFlyinsono.t,
        style: TextStyle(fontSize: 16, color: Colors.white),
      ),
      elevation: 0,
      centerTitle: true,
      leading: FIconButton(
        name: "back",
        businessParent: businessParent,
        icon: FIcon(
          Icons.arrow_back_ios_new,
          size: 20,
        ),
        onPressed: () {
          router.back();
        },
      ),
    );
  }
}
