import 'dart:convert';

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/paddings.dart';
import 'package:fis_ui/values/spacings.dart';
import 'package:fis_ui/widgets/layout/button_group.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/managers/interfaces/remote_controller.dart';
import 'package:flyinsono/managers/interfaces/remote_maintenance.dart';
import 'package:flyinsono/views/common/device_live/device_live_list/controller.dart';
import 'package:flyinsono/views/common/device_live/device_live_list/formatters/ip_address_input_formatter.dart';
import 'package:get/get.dart';
import 'package:fis_common/logger/logger.dart';

class SystemSettingsDialog extends FStatefulWidget implements FPage {
  final String? deviceCode;
  SystemSettingsDialog({
    this.deviceCode,
  });
  @override
  String get pageName => 'SystemSettingsDialog';

  @override
  FState<SystemSettingsDialog> createState() => _SystemSettingsDialogState();
}

class _SystemSettingsDialogState extends FState<SystemSettingsDialog> {
  static TextStyle _textStyle = TextStyle(
    color: Colors.black,
    fontSize: FFontSizes.H6,
  );
  final remoteControllerManager = Get.find<IRemoteControllerManager>();
  final remoteMaintenanceManager = Get.find<IRemoteMaintenanceManager>();
  final controller = Get.find<DeviceLiveListController>();

  /// 是否需要获取系统设置全部数据
  bool isInitSystemSettings = true;

  /// 初始化loadding
  bool isLoadding = true;

  /// 页面loadding
  bool isPageLoadding = true;

  /// 是否显示DICOM-“存储”
  bool isShowDICOMStorage = false;

  /// 输入许可码
  String _applyLicense = '';

  /// 试用所选功能
  String _trySelectedFeature = '';

  ///保存中
  bool _isSaving = false;
  double _totalSaveTime = 0;

  late Map currentItem = {};
  late List currentItemGroups = [];
  late Map currentContent = {};
  late List currentContentList = [];
  late bool isOpenVstationEnable;

  @override
  FWidget build(BuildContext context) {
    return FSimpleDialog(
      contentPadding: EdgeInsets.symmetric(vertical: 25, horizontal: 25),
      title: FText(
        i18nBook.remoteControl.systemSettings.t,
        style: TextStyle(
          color: Colors.white,
          fontSize: 18,
        ),
      ),
      okString: i18nBook.common.confirm4Btn.t,
      onClose: () {
        _onSave('Exit');
        router.back();
      },
      cancelString: i18nBook.common.cancel.t,
      insetPadding: EdgeInsets.symmetric(vertical: 100),
      children: [
        FContainer(
          width: 850,
          height: 600,
          child: isLoadding
              ? _buildLoadding()
              : FStack(
                  children: [
                    FColumn(
                      children: [
                        /// 这是头部的DICOM和功能
                        FRow(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: controller.state.listPages.map((e) {
                            return FGestureDetector(
                              businessParent: this.widget,
                              name: 'SystemSettingsDialog',
                              onTap: () {
                                currentItem = e;
                                controller.state.systemSettingItem = e;
                                currentItemGroups = currentItem['Groups'];
                                controller.state.systemSettingContentItem =
                                    currentItemGroups[0];
                                currentContent = currentItemGroups[0];
                                currentContentList = currentContent['Items'];
                                setState(() {});
                              },
                              child: FMouseRegion(
                                cursor: SystemMouseCursors.click,
                                child: FContainer(
                                  padding: EdgeInsets.symmetric(
                                    horizontal: 15,
                                  ),
                                  child: FText(
                                    e['Name'] ?? '',
                                    style: TextStyle(
                                      color: currentItem['Name'] == e['Name']
                                          ? FTheme.ins.colorScheme.primary
                                          : Colors.black,
                                      fontSize: FFontSizes.H4,
                                    ),
                                  ),
                                ),
                              ),
                            );
                          }).toList(),
                        ),
                        FDivider(),
                        FExpanded(
                          child: FRow(
                            children: [
                              /// 这是类型下面的子集 例如DICOM 下面的常规和存储
                              FContainer(
                                width: 150,
                                child: FColumn(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: currentItemGroups.map((e) {
                                    return FGestureDetector(
                                      businessParent: this.widget,
                                      name: 'SystemSettingsDialog',
                                      onTap: () {
                                        if (currentContent != e) {
                                          currentContent = e;
                                          controller.state
                                              .systemSettingContentItem = e;
                                          currentContentList =
                                              currentContent['Items'];
                                        } else {
                                          return;
                                        }

                                        setState(() {});
                                      },
                                      child: FContainer(
                                        height: 40,
                                        width: 150,
                                        key: GlobalKey(debugLabel: e['Name']),
                                        alignment: Alignment.center,
                                        decoration: BoxDecoration(
                                          color: currentContent['Name'] ==
                                                  e['Name']
                                              ? FTheme.ins.colorScheme.primary
                                              : Colors.white,
                                        ),
                                        child: FText(
                                          e['Name'] ?? '',
                                          style: TextStyle(
                                            color: currentContent['Name'] ==
                                                    e['Name']
                                                ? Colors.white
                                                : Colors.black,
                                          ),
                                        ),
                                      ),
                                    );
                                  }).toList(),
                                ),
                              ),

                              /// 这是子集下面的页面
                              FExpanded(
                                child: FContainer(
                                  height: 600,
                                  margin: EdgeInsets.only(bottom: 15),
                                  decoration: BoxDecoration(
                                    border: Border(
                                      left: BorderSide(
                                        color: FTheme.ins.colorScheme.line,
                                        width: 0.5,
                                      ),
                                    ),
                                  ),
                                  child: FSingleChildScrollView(
                                    child: FContainer(
                                      margin: EdgeInsets.symmetric(
                                          horizontal: 30, vertical: 15),
                                      child: FColumn(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        mainAxisSize: MainAxisSize.max,
                                        children: currentContentList.map((e) {
                                          // 已安装可选功能 暂时通过 Details 为空判断
                                          if (e['Details'] == '')
                                            return _buildEnabledOptions(e);
                                          // DICOM文件格式设置
                                          else if (e['Key'] ==
                                              'DICOMFileFormatSetting')
                                            return _buildDICOMFileFormatSetting(
                                                e);
                                          else if (e['Key'] ==
                                              'DICOMEnableStorage')
                                            return _buildDICOMEnableStorage(e);
                                          else if (e['Key'] ==
                                              'StorageSCPSetting') {
                                            if (!isShowDICOMStorage)
                                              return FSizedBox();
                                            else
                                              return _buildStorageSCPSetting(e);
                                          } else if (e['Key'] == 'Features')
                                            return _buildFeatures(e['Items']);
                                          // 输入许可码
                                          else if (e['Key'] == 'InputLicense')
                                            return _buildInputLicense(e);
                                          // 试用可选功能
                                          else if (e['Key'] ==
                                              'StartTrialAllOption')
                                            return _buildStartTrialAllOption(e);

                                          /// 云服务选项
                                          else if (e['Key'] == 'VCloudOptions')
                                            return _buildVCloudOptions(e);

                                          /// 开启
                                          else if (e['Key'] == 'VstationEnable')
                                            return _buildVstationEnable(e);
                                          else if (e['Key'] == 'VstationConfig')
                                            return _buildVstationConfig(e);
                                          else
                                            return FText(
                                              '${e['Name']}',
                                              style: _textStyle,
                                            );
                                        }).toList(),
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                        FDivider(),
                        FContainer(
                          margin: EdgeInsets.only(top: 16),
                          child: FRow(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              FButtonGroup(
                                buttonPadding: FPaddings.SECONDARY_BUTTON,
                                spacing: FSpacings.L,
                                children: [
                                  _buildCommonButton(
                                    i18nBook.common.refresh.t,
                                    () async {
                                      await controller.sendCommandToDeviceAsync(
                                        deviceCode: widget.deviceCode ?? '',
                                      );
                                      isInitSystemSettings = true;
                                    },
                                  ),
                                  _buildCommonButton(i18nBook.common.save.t,
                                      () => _onSave('Update')),
                                  _buildCommonButton(
                                      i18nBook.remoteControl.saveAndExit.t, () {
                                    _onSave('UpdateAndExit');
                                    _isSaving = true;
                                    _totalSaveTime = 0;
                                    controller.busyHandle(
                                      _saveHandle,
                                      text: i18nBook.auth.saving.t,
                                    );
                                  }),
                                  _buildCancelButton(i18nBook.common.cancel.t,
                                      () {
                                    _onSave('Exit');
                                    router.back();
                                  }),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                    if (isPageLoadding) _buildLoadding()
                  ],
                ),
        ),
      ],
      isDefault: false,
    );
  }

  @override
  void dispose() {
    remoteControllerManager.onSendResultToClient
        .removeListener(_onSendResultToClient);
    remoteMaintenanceManager.onSystemSaveAndExit
        .removeListener(_onSystemSaveAndExit);
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    remoteMaintenanceManager.onSystemSaveAndExit
        .addListener(_onSystemSaveAndExit);

    /// 初始化置空
    controller.state.systemSettingContentItem = {};
    remoteControllerManager.onSendResultToClient
        .addListener(_onSendResultToClient);
  }

  FWidget _buildCancelButton(String buttonName, VoidCallback onPressed) {
    return FOutlinedButton(
      child: FText(buttonName),
      onPressed: () {
        onPressed.call();
      },
      businessParent: this.widget,
      name: buttonName,
      style: ElevatedButton.styleFrom(
        elevation: 0,
        padding: EdgeInsets.symmetric(
          vertical: 15,
          horizontal: 25,
        ),
      ),
    );
  }

  FWidget _buildCommonButton(
    String buttonName,
    VoidCallback onPressed,
  ) {
    if (isPageLoadding)
      return FElevatedButton(
        child: FText(buttonName),
        onPressed: null,
        businessParent: this.widget,
        name: buttonName,
        style: ElevatedButton.styleFrom(
          elevation: 0,
          backgroundColor: Colors.grey,
          padding: EdgeInsets.symmetric(
            vertical: 15,
            horizontal: 25,
          ),
        ),
      );
    return FElevatedButton(
      child: FText(buttonName),
      onPressed: () {
        onPressed.call();

        setState(() {});
      },
      businessParent: this.widget,
      name: buttonName,
      style: ElevatedButton.styleFrom(
        elevation: 0,
        padding: EdgeInsets.symmetric(
          vertical: 15,
          horizontal: 25,
        ),
      ),
    );
  }

  FWidget _buildDICOMEnableStorage(e) {
    isShowDICOMStorage = e['Value'];
    return FRow(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        FText(
          '${e['Name']}',
          style: _textStyle.copyWith(
            fontSize: FFontSizes.H4,
          ),
        ),
        FSwitch(
          value: e['Value'],
          onChanged: (value) {
            e['Value'] = value;
            isShowDICOMStorage = value;
            setState(() {});
          },
        )
      ],
    );
  }

  // DICOM文件格式设置
  FWidget _buildDICOMFileFormatSetting(e) {
    return FColumn(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        FText(
          '${e['Name']}',
          style: _textStyle.copyWith(
            fontSize: FFontSizes.H4,
          ),
        ),
        FSizedBox(
          height: 15,
        ),
        FColumn(
          children: (e['Items'] as List).map((context) {
            List<FSelectOptionModel> source = [];
            List? contextItem = context['Items'];
            String contextValue = context['Value'];
            for (int i = 0; i < (contextItem?.length ?? 0); i++) {
              source.add(
                FSelectOptionModel(
                  title: contextItem?[i],
                  value: i.toString(),
                ),
              );
            }
            return FContainer(
              margin: EdgeInsets.only(bottom: 5),
              child: FRow(
                children: [
                  FText(
                    '${context['Name']}',
                    style: _textStyle,
                  ),
                  FSizedBox(
                    width: 15,
                  ),
                  FExpanded(
                    child: FSelect<FSelectOptionModel, String>(
                      source: source,
                      fontFamily: FTheme.ins.localeSetting.fontFamily,
                      value: contextValue,
                      onSelectChanged: (value, index) {
                        context['Value'] = value ?? '';
                        print(currentItemGroups);
                      },
                      height: 30,
                      optionLabelExtractor: (data) => data.title,
                      optionValueExtractor: (data) => data.value,
                    ),
                  ),
                ],
              ),
            );
          }).toList(),
        )
      ],
    );
  }

  FWidget _buildFeatures(List e) {
    return FColumn(
      children: e.map((item) {
        return _buildEnabledOptions(item);
      }).toList(),
    );
  }

  // 可选功能
  FWidget _buildEnabledOptions(e) {
    return FContainer(
      padding: EdgeInsets.all(15),
      width: double.maxFinite,
      margin: EdgeInsets.only(bottom: 15),
      decoration: BoxDecoration(
        border: Border.all(
          color: FTheme.ins.colorScheme.line,
          width: 0.5,
        ),
        borderRadius: BorderRadius.all(Radius.circular(4)),
      ),
      child: FColumn(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          FText(
            e['Name'] ?? '',
            style: TextStyle(fontSize: 16),
          ),
          FText(e['Status'] ?? ''),
        ],
      ),
    );
  }

  FWidget _buildInputLicense(e) {
    return FColumn(
      key: UniqueKey(),
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        FContainer(
          margin: EdgeInsets.only(top: 5),
          child: FRow(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              FContainer(
                child: FText(
                  '${e['Name']}',
                  style: _textStyle,
                ),
              ),
              FSizedBox(
                width: 15,
              ),
              FExpanded(
                child: FBorderInput(
                  height: 36,
                  controller: TextEditingController(text: e['Value']),
                  borderColor: Color.fromRGBO(234, 234, 234, 1),
                  onChanged: (value) {
                    e['Value'] = value;
                    _applyLicense = value;
                  },
                ),
              ),
              FSizedBox(
                width: 15,
              ),
              _buildCommonButton(
                e['ApplyLicenseDescription'],
                () {
                  _onSaveApplyLicense();
                },
              )
            ],
          ),
        ),
      ],
    );
  }

  // 试用可选功能
  FWidget _buildStartTrialAllOption(e) {
    return FColumn(
      key: UniqueKey(),
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        FContainer(
          margin: EdgeInsets.only(top: 5),
          child: FRow(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              FContainer(
                child: FText(
                  '${e['Name']}',
                  style: _textStyle,
                ),
              ),
              FSizedBox(
                width: 15,
              ),
              FExpanded(
                child: FBorderInput(
                  height: 36,
                  controller: TextEditingController(text: e['Value']),
                  borderColor: Color.fromRGBO(234, 234, 234, 1),
                  onChanged: (value) {
                    e['Value'] = value;
                    _trySelectedFeature = value;
                  },
                ),
              ),
              FSizedBox(
                width: 15,
              ),
              _buildCommonButton(
                e['CommandDescription'],
                () {
                  _onSaveStartTrialAllOption();
                },
              )
            ],
          ),
        ),
        FText(
          i18nBook.remoteControl.isOptionalFeatureEnabled.t,
        ),
      ],
    );
  }

  FWidget _buildLoadding() {
    return FCenter(
      child: FContainer(
        padding: EdgeInsets.all(15),
        width: 55,
        height: 55,
        child: FCircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation(
            Colors.blueAccent,
          ),
        ),
      ),
    );
  }

  FWidget _buildStorageSCPSetting(e) {
    int index = 0;
    return FColumn(
      crossAxisAlignment: CrossAxisAlignment.start,
      key: UniqueKey(),
      children: [
        FText(
          '${e['Name']}',
          style: _textStyle.copyWith(
            fontSize: FFontSizes.H4,
          ),
        ),
        FSizedBox(
          height: 15,
        ),
        FColumn(
          children: (e['Items'] as List).map((context) {
            index++;
            String? contextValue = context['Value'];
            List<TextInputFormatter>? inputFormatters;
            if (index == 2) {
              inputFormatters = [IpAddressInputFormatter()];
            } else if (index == 3) {
              inputFormatters = [
                FilteringTextInputFormatter.allow(RegExp(r'[0-9]{0,5}')),
              ];
            } else {
              inputFormatters = null;
            }
            if (context['CommandDescription'] == null)
              return FRow(
                children: [
                  FContainer(
                    width: 150,
                    child: FText(
                      '${context['Name']}',
                      style: _textStyle,
                    ),
                  ),
                  FSizedBox(
                    width: 15,
                  ),
                  FExpanded(
                    child: FBorderInput(
                      height: 36,
                      borderColor: Color.fromRGBO(234, 234, 234, 1),
                      controller: TextEditingController(text: contextValue),
                      onChanged: (value) {
                        context['Value'] = value;
                      },
                      inputFormatters: inputFormatters,
                    ),
                  )
                ],
              );
            else
              return FContainer(
                margin: EdgeInsets.only(top: 5),
                child: FRow(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    FContainer(
                      child: FText(
                        '${context['Name']}',
                        style: _textStyle,
                      ),
                    ),
                    _buildCommonButton(
                      i18nBook.remoteControl.test.t,
                      () {
                        for (var item in e["Items"]) {
                          if ((item["Key"] == "DICOMSCPAddress" ||
                                  item["Key"] == "DICOMSCPPort") &&
                              (item["Value"] == null || item["Value"] == "")) {
                            PromptBox.toast(i18nBook.remoteControl.testFailed
                                .translate([
                              i18nBook.remoteControl.connectedStorage.t
                            ]));
                            return;
                          }
                        }
                        _onSave('TestDicomServer');
                      },
                    )
                  ],
                ),
              );
          }).toList(),
        )
      ],
    );
  }

  FWidget _buildVCloudOptions(e) {
    return FColumn(
      key: UniqueKey(),
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        FText(
          '${e['Name']}',
          style: _textStyle.copyWith(
            fontSize: FFontSizes.H4,
          ),
        ),
        FSizedBox(
          height: 15,
        ),
        FColumn(
          children: (e['Items'] as List).map((context) {
            bool? contextValue = context['Value'];

            if (contextValue != null)
              return FRow(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  FContainer(
                    child: FText(
                      '${context['Name']}',
                      style: _textStyle,
                    ),
                  ),
                  FContainer(
                    margin: EdgeInsets.only(right: 10),
                    child: FSwitch(
                      value: contextValue,
                      onChanged: (value) {
                        context['Value'] = value;
                        setState(() {});
                      },
                    ),
                  )
                ],
              );
            else
              return FContainer(
                margin: EdgeInsets.only(top: 5),
                child: FRow(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    FContainer(
                      child: FText(
                        '${context['Name']}',
                        style: _textStyle,
                      ),
                    ),
                    _buildCommonButton(
                      i18nBook.measure.clear.t,
                      () {
                        _onSave('ClearRemedicalCache');
                      },
                    )
                  ],
                ),
              );
          }).toList(),
        )
      ],
    );
  }

  FWidget _buildVstationConfig(e) {
    if (isOpenVstationEnable) {
      int index = 0;
      return FColumn(
        key: UniqueKey(),
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          FText(
            '${e['Name']}',
            style: _textStyle.copyWith(
              fontSize: FFontSizes.H4,
            ),
          ),
          FSizedBox(
            height: 15,
          ),
          FColumn(
            children: (e['Items'] as List).map((context) {
              index++;
              String? contextValue = context['Value'];
              TextEditingController? textEditingController =
                  TextEditingController(text: contextValue);
              if (context['CommandDescription'] == null)
                return FRow(
                  children: [
                    FContainer(
                      width: 150,
                      child: FText(
                        '${context['Name']}',
                        style: _textStyle,
                      ),
                    ),
                    FSizedBox(
                      width: 15,
                    ),
                    FExpanded(
                      child: FBorderInput(
                        height: 36,
                        key: UniqueKey(),
                        borderColor: Color.fromRGBO(234, 234, 234, 1),
                        controller: textEditingController,
                        inputFormatters: index <= 1
                            ? [IpAddressInputFormatter()]
                            : [
                                FilteringTextInputFormatter.allow(
                                    RegExp(r'[0-9]{0,5}')),
                              ],
                        onChanged: (value) {
                          context['Value'] = value;
                          // textEditingController.selection =
                          //     TextSelection.collapsed(
                          //         offset: value?.length ?? 0);
                        },
                      ),
                    )
                  ],
                );
              else
                return FContainer(
                  margin: EdgeInsets.only(top: 5),
                  child: FRow(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      FContainer(
                        child: FText(
                          '${context['Name']}',
                          style: _textStyle,
                        ),
                      ),
                      _buildCommonButton(
                        context['CommandDescription'],
                        () {
                          _onSave('TestVStation');
                        },
                      )
                    ],
                  ),
                );
            }).toList(),
          )
        ],
      );
    }
    return FSizedBox();
  }

  FWidget _buildVstationEnable(e) {
    isOpenVstationEnable = e['Value'];
    return FColumn(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        FRow(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            FContainer(
              child: FText(
                '${e['Name']}',
                style: _textStyle.copyWith(
                  fontSize: FFontSizes.H4,
                ),
              ),
            ),
            FContainer(
              margin: EdgeInsets.only(right: 10),
              child: FSwitch(
                value: e['Value'],
                onChanged: (value) {
                  e['Value'] = value;
                  setState(() {});
                },
              ),
            )
          ],
        ),
      ],
    );
  }

  /// 保存系统配置的
  _onSave(String actionType) {
    if (actionType != 'UpdateAndExit') {
      isPageLoadding = true;
    }
    Map settings = {};
    Map listPages = {};
    listPages['Groups'] = currentItemGroups;
    listPages['Key'] = currentItem['Key'];
    settings['ListPages'] = [listPages];
    settings['SelectedListPageKey'] = currentItem['Key'];
    settings['SelectedGroupKey'] = currentContent['Key'];
    controller.sendCommandToDeviceAsync(
      deviceCode: widget.deviceCode ?? '',
      actionType: actionType,
      settings: json.encode(settings),
    );
  }

  _onSaveApplyLicense() {
    controller.sendCommandToDeviceAsync(
      deviceCode: widget.deviceCode ?? '',
      actionType: 'ApplyLicense',
      settings: json.encode({'ApplyLicenseResult': _applyLicense}),
    );
  }

  _onSaveStartTrialAllOption() {
    controller.sendCommandToDeviceAsync(
      deviceCode: widget.deviceCode ?? '',
      actionType: 'StartTrialAllOption',
      settings: json.encode({'ApplyLicenseResult': _trySelectedFeature}),
    );
  }

  /// 获取系统设置
  _onSendResultToClient(Object a, SendResultToClientNotification e) async {
    try {
      await controller.getResultFromServerAsync(
        resultCode: e.resultCode,
        isInitSystemSettings: isInitSystemSettings,
      );

      if (isInitSystemSettings) {
        /// 刷新需要记住当前的位置，后端偷懒了，只能前端记住当前位置是哪里
        if (controller.state.systemSettingContentItem.isNotEmpty) {
          currentItem = controller.state.systemSettingItem;
          currentItemGroups = currentItem['Groups'];
          currentContent = controller.state.systemSettingContentItem;
        } else {
          currentItem = controller.state.listPages[0];
          controller.state.systemSettingItem = currentItem;
          currentItemGroups = currentItem['Groups'];
          currentContent = currentItemGroups[0];
        }
        currentContentList = currentContent['Items'];
        isLoadding = false;
      }
      isInitSystemSettings = false;
      isPageLoadding = false;
      setState(() {});
    } catch (e) {
      logger.e('_onSendResultToClient ex:', e);
    }
  }

  Future<void> _saveHandle() async {
    if (_isSaving) {
      await Future.delayed(Duration(milliseconds: 200));
      _totalSaveTime += 200;
      if (_totalSaveTime > 5000) {
        return;
      }
      return _saveHandle();
    } else {
      router.back();
      return;
    }
  }

  void _onSystemSaveAndExit(Object sender, bool e) {
    _isSaving = false;
  }
}
