import 'dart:async';

import 'package:fis_common/index.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/values/font_sizes.dart';
import 'package:fis_ui/widgets/progressbar/progress_indicator.dart';
import 'package:fis_ui/widgets/progressbar/progressbar.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/managers/interfaces/entities/install_printer_driver_state.dart';
import 'package:flyinsono/managers/interfaces/entities/printer_drive.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/printer_translate.dart';
import 'package:flyinsono/views/common/device_live/device_live_list/state.dart';
import 'package:flyinsono/views/common/device_live/device_live_list/widgets/using_cloud_driven.dart';
import 'package:flyinsono/views/desktop/device_live/device_live_list/widgets/management_dialog.dart';
import 'package:get/get.dart';
import 'install_printer_end.dart';
import 'package:fis_theme/theme.dart';

class PrinterSettingsDialog extends FStatefulWidget implements FPage {
  ///远程维护设备编码
  final String? deviceCode;
  bool? localSetting;
  PrinterSettingsDialog({required this.deviceCode, this.localSetting = false});
  @override
  String get pageName => 'PrinterSettingsDialog';

  @override
  FState<PrinterSettingsDialog> createState() => _PrinterSettingsDialogState();
}

class _PrinterSettingsDialogState extends FState<PrinterSettingsDialog> {
  final controller = Get.find<DeviceLiveListController>();
  final remoteControllerManager = Get.find<IRemoteControllerManager>();
  final remoteMaintenanceManager = Get.find<IRemoteMaintenanceManager>();
  int step = 0;
  String ipAddress = '';
  String portNumber = '';
  bool isErrorIp = false;
  String currentPrinterName = i18nBook.remoteControl.addPrinter.t;
  String searchPrint = i18nBook.remoteControl.searchPrinter.t;
  double? searchPrinterProgress; // 搜索打印机的进度
  int? installPrinterProgress = 0; // 安装打印机的进度
  int installPrinter = 0; // 安装打印机的状态
  List<FSelectOptionModel> pageOrientationList = []; // 纸张方向
  List<FSelectOptionModel> pageSizeList = []; // 纸张尺寸
  String? pageOrientation;
  String? pageSize;
  String installPrinterDriver = i18nBook.remoteControl.pushDriver.t;
  String testPrinter = '';
  bool isPrinterLoadding = true;
  bool _isInitIp = true; // 是否初始化ip地址
  ///是否处于安装中
  bool _installing = false;

  ///是否安装失败
  bool _isInstallFail = false;

  int _radioValue = 0; // 搜索打印机的模式

  /// 安装打印机的状态

  late final DeviceLiveListController _controller;
  late final DeviceExtendInfoDTO _dto;
  late TextEditingController portNumberController =
      TextEditingController(text: portNumber);

  late DevicePrinterParameterDTO? currentPrinter;

  /// 判断是否使用正常搜索模式
  late bool isNormalSearchType = _radioValue == 0;

  /// 获取已经安装的打印机信息列表
  List<DevicePrinterParameterDTO> getInstalledPrintersList = [
    DevicePrinterParameterDTO(
        name: i18nBook.remoteControl.addPrinter.t, installPrinterProgress: -1),
  ];

  List<DevicePrinterParameterDTO> getSearchPrintersList = [];
  bool get isOnline => _dto.isOnline == true;

  ///是否远程维护的打印驱动管理
  bool get isRemoteMaintenance => widget.deviceCode.isNotNullOrEmpty;

  /// 是否是保存按钮
  /// 第四步并且已经已经安装好云驱动了
  bool get _isShowSaveButtom =>
      step == 4 && installPrinter == 2 && isRemoteMaintenance;
  bool get _isShowDeleteButtom =>
      step == 0 && currentPrinterName != i18nBook.remoteControl.addPrinter.t;
  bool get _isShowCloseButtom =>
      step == 3 && searchPrint == i18nBook.remoteControl.cancelSearch.t;
  bool get _isShowPreviousStepButtom =>
      step != 0 &&
      !_isShowSaveButtom &&
      ((widget.deviceCode.isNullOrEmpty &&
              searchPrinterProgress != null &&
              searchPrint != i18nBook.remoteControl.cancelSearch.t) ||
          widget.deviceCode.isNotNullOrEmpty);

  /// 是否展示下一步
  bool get _isShowNextStepButtom =>
      step < 3 || // 小于第三步 搜索打印机驱动
      (step == 3 &&
          (searchPrinterProgress != null &&
              searchPrint != i18nBook.remoteControl.cancelSearch.t)); // 搜索完成

  @override
  FWidget build(BuildContext context) {
    return FSimpleDialog(
      insetPadding: kIsMobile
          ? EdgeInsets.symmetric(horizontal: 15)
          : EdgeInsets.symmetric(horizontal: 40.0, vertical: 24.0),
      contentPadding:
          EdgeInsets.symmetric(vertical: 25, horizontal: kIsMobile ? 10 : 25),
      title: FText(
        i18nBook.remoteControl.printerSettings.t,
        style: TextStyle(
          color: Colors.white,
          fontSize: 18,
        ),
      ),
      okString: i18nBook.common.confirm4Btn.t,
      onClose: () {
        router.back();
      },
      cancelString: i18nBook.common.cancel.t,
      children: [
        FContainer(
          width: kIsMobile ? MediaQuery.of(context).size.width : 600,
          height: kIsMobile ? 400 : 300,
          child: isPrinterLoadding
              ? _buildLoadding()
              : FColumn(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.center,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    if (step == 0) FExpanded(child: _buildStepOne()),
                    if (step == 1) FExpanded(child: _buildStepTwo()),
                    if (step == 2) FExpanded(child: _buildStepThree()),
                    if (step == 3) FExpanded(child: _buildStepFour()),
                    if (step == 4) FExpanded(child: _buildStepFive()),
                    if (step == 5)
                      FExpanded(
                          child: InstallPrinterEnd(currentPrinter!.name!)),
                    if (step != 5) ...[
                      FContainer(
                        padding: EdgeInsets.symmetric(
                            horizontal: kIsMobile ? 10 : 100),
                        child: FRow(
                          children: [
                            FExpanded(child: _buildButtomGroup()),
                          ],
                        ),
                      ),
                    ],
                  ],
                ),
        )
      ],
      isDefault: false,
    );
  }

  @override
  void dispose() {
    remoteControllerManager.onDevicePrinterResult
        .removeListener(_onDevicePrinterResult);
    remoteMaintenanceManager.onInstallPrinterDriverChange
        .addListener(_onInstallPrinterDriverChange);
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _controller = Get.find<DeviceLiveListController>();
    remoteMaintenanceManager.onInstallPrinterDriverChange
        .addListener(_onInstallPrinterDriverChange);
    remoteControllerManager.onDevicePrinterResult
        .addListener(_onDevicePrinterResult);
  }

  FWidget _buildButtomGroup() {
    return FRow(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        if (_isShowPreviousStepButtom)
          _buildCommonButton(
              i18nBook.remoteControl.previousStep.t, _onPreviousStep),
        if (_isShowNextStepButtom)
          _buildCommonButton(i18nBook.remoteControl.nextStep.t, _onNextStep),
        if (_isShowDeleteButtom && !widget.localSetting!)
          _buildCommonButton(i18nBook.measure.threeDdelete.t, _onDelete),
        if (_isShowSaveButtom)
          _buildCommonButton(i18nBook.common.save.t, _onSave),
        if (_isShowCloseButtom)
          _buildCommonButton(i18nBook.common.close.t, () {
            router.back();
          }),
      ],
    );
  }

  void _cancelSearch() {
    step -= 2;
    ipAddress = '';
    portNumber = '';
    portNumberController.text = '';
    _setDevicePrinterAsync(
      deviceCode: widget.deviceCode,
      isNormalSearchType: isNormalSearchType,
      isCancel: true,
    );
  }

  void _initIpAndProt() {
    _isInitIp = true;
    isErrorIp = false;
    ipAddress = '';
    portNumber = '';
    portNumberController.text = '';
  }

  FWidget _buildCommonButton(String buttonName, VoidCallback onPressed) {
    return FContainer(
      width: kIsMobile ? 110 : 150,
      margin: EdgeInsets.symmetric(
        horizontal: 5,
      ),
      child: FElevatedButton(
        child: FText(buttonName),
        onPressed: () {
          onPressed.call();
        },
        businessParent: this.widget,
        name: buttonName,
        style: ElevatedButton.styleFrom(
          elevation: 0,
          padding: EdgeInsets.symmetric(
            vertical: kIsMobile ? 10 : 15,
            horizontal: 5,
          ),
        ),
      ),
    );
  }

  /// 下拉单选框
  FWidget _buildFSelect({
    List<FSelectOptionModel>? sourceList,
    String? selectValue,
    ValueCallback? onChange,
  }) {
    var value = sourceList
        ?.firstWhereOrNull((element) => element.value == selectValue)
        ?.value;
    final select = FSelect<FSelectOptionModel, String>(
      source: sourceList ?? [],
      fontFamily: FTheme.ins.localeSetting.fontFamily,
      value: value,
      height: 36,
      width: 400,
      textColor: Colors.black,
      optionLabelExtractor: (data) => data.title,
      optionValueExtractor: (data) => data.value,
      onSelectChanged: (value, index) {
        onChange?.call(value);
      },
    );

    return select;
  }

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

  /// 打印机驱动 列表
  List<FWidget> _buildPrinterInstalled(
    List<DevicePrinterParameterDTO> devicePrinterParameterList, [
    ValueCallback? useCloudDriver,
  ]) {
    return devicePrinterParameterList
        .map(
          (e) => _buildPrintItem(
            printName: e.name,
            icon: e.installPrinterProgress == -1 ? Icons.add : null,
            isSelected: e.name == currentPrinterName,
            devicePrinterParameter: e,
            useCloudDriver: (value) => useCloudDriver?.call(value),
          ),
        )
        .toList();
  }

  FWidget _buildPrintInput({
    required String inputTitle,
    required ValueCallback onChanged,
    TextEditingController? textController,
  }) {
    textController?.selection = TextSelection.fromPosition(
      TextPosition(
        offset: textController.text.length,
      ),
    );
    return FColumn(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        FText(inputTitle),
        FBorderInput(
          height: 36,
          borderColor: FTheme.ins.colorScheme.line,
          onChanged: onChanged,
          controller: textController,
        ),
      ],
    );
  }

  FWidget _buildPrintItem({
    IconData? icon,
    String? printName,
    bool? isSelected = false,
    DevicePrinterParameterDTO? devicePrinterParameter,
    ValueCallback? useCloudDriver,
  }) {
    return FInkWell(
      onTap: () {
        currentPrinterName = printName ?? '';
        useCloudDriver?.call(devicePrinterParameter);
        setState(() {});
      },
      child: FContainer(
        width: 120,
        height: 120,
        decoration: BoxDecoration(
          border: isSelected!
              ? null
              : Border.all(
                  color: Colors.black,
                  width: 0.5,
                ),
          color: isSelected ? FTheme.ins.colorScheme.primary : Colors.white,
          borderRadius: BorderRadius.all(
            Radius.circular(4),
          ),
        ),
        child: FCenter(
          child: FColumn(
            children: [
              FSizedBox(
                height: 15,
              ),
              FIcon(
                icon ?? Icons.print_outlined,
                size: 50,
                color: isSelected ? Colors.white : Colors.black,
              ),
              FContainer(
                padding: EdgeInsets.symmetric(horizontal: 15),
                child: FText(
                  printName ?? '',
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: isSelected ? Colors.white : Colors.black,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  FWidget _buildRowSelect(
    String title,
    List<FSelectOptionModel<dynamic>>? sourceList,
    String? value,
    ValueCallback? onChange,
  ) {
    return FRow(
      children: [
        FContainer(
          child: FText(title),
          width: 100,
        ),
        FExpanded(
          child: _buildFSelect(
            sourceList: sourceList,
            selectValue: value,
            onChange: onChange,
          ),
        ),
      ],
    );
  }

  /// 第五步 更改打印机的配置 测试打印机
  FWidget _buildStepFive() {
    return FColumn(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        FText(i18nBook.remoteControl.printer.t + ' ${currentPrinter?.name}'),
        FSizedBox(
          height: 20,
        ),
        if (installPrinter == 0)
          FColumn(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              FText(
                i18nBook.remoteControl.cloudDriverNotInstalled.t,
                style: TextStyle(
                  color: Colors.orangeAccent,
                  fontSize: FFontSizes.BODY,
                ),
              ),
              FSizedBox(
                height: 20,
              ),
              FRow(
                children: [
                  if (!widget.localSetting!)
                    _buildCommonButton(i18nBook.remoteControl.useCloudDriver.t,
                        () {
                      if (kIsMobile) {
                        _openMobilePrinter();
                        return;
                      }
                      _openPrinter();
                    }),
                  if (!widget.localSetting!)
                    FSizedBox(
                      width: 20,
                    ),
                  if (!kIsMobile && widget.deviceCode.isNullOrEmpty) ...[
                    _buildCommonButton(i18nBook.common.installLocalDriver.t,
                        () {
                      remoteMaintenanceManager.chooseLocalDrive();
                    }),
                  ],
                ],
              ),
              FSizedBox(
                height: 20,
              ),
            ],
          ),
        if (installPrinter == 1)
          FColumn(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              FText(installPrinterDriver),
              FContainer(
                child: FProgeressbar(
                  percentage: (installPrinterProgress ?? 0) / 100,
                  lineHeight: 20.0,
                  animation: true,
                  animationDuration: 100,
                  animateFromLastPercentage: true,
                  alignment: MainAxisAlignment.spaceBetween,
                  child: FText(
                    _getProgressDisplay((installPrinterProgress ?? 0) / 100),
                    textAlign: TextAlign.center,
                    style: TextStyle(fontSize: 16, color: Colors.white),
                  ),
                  backgroundColor: Colors.black26,
                  progressBarColor: Colors.blue,
                ),
                height: 35,
              ),
            ],
          ),
        if (installPrinter == 2 && !isRemoteMaintenance)
          FColumn(
            children: [
              FSizedBox(
                height: 15,
              ),
              FCenter(
                child: FIcon(
                  Icons.print_outlined,
                  size: 120,
                  color: Colors.black,
                ),
              ),
              FContainer(
                padding: EdgeInsets.symmetric(horizontal: 15),
                child: FText(
                  currentPrinterName,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Colors.black,
                  ),
                ),
              ),
              FElevatedButton(
                child: FText(i18nBook.college.printTestPage.t),
                onPressed: () {
                  remoteMaintenanceManager.printTestPage(currentPrinterName);
                },
                businessParent: this.widget,
                name: 'print test',
              )
            ],
          ),
        if (installPrinter == 2 && isRemoteMaintenance)
          FColumn(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              _buildRowSelect(
                i18nBook.remoteControl.paperSize.t,
                pageSizeList,
                pageSize,
                (value) {
                  pageSize = value;
                },
              ),
              FSizedBox(
                height: 20,
              ),
              _buildRowSelect(
                i18nBook.remoteControl.paperOrientation.t,
                pageOrientationList,
                pageOrientation,
                (value) {
                  pageOrientation = value;
                },
              ),
              FSizedBox(
                height: 15,
              ),
              FText.rich(
                TextSpan(
                  text: i18nBook.remoteControl.testPrinter.t,
                  style: TextStyle(
                    fontFamily: FTheme.ins.localeSetting.fontFamily,
                    color: FTheme.ins.colorScheme.primary,
                    fontSize: FFontSizes.BODY,
                  ),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () async {
                      _onTestPrinter();
                    },
                ),
              ),
              if (testPrinter.isNotEmpty)
                FContainer(
                  alignment: Alignment.centerLeft,
                  child: FText(
                    testPrinter,
                    textAlign: TextAlign.left,
                    style: TextStyle(color: FTheme.ins.colorScheme.primary),
                  ),
                )
            ],
          ),
        if (_installing) ...[
          FRow(
            children: [
              FExpanded(
                child: FContainer(
                  child: FLinearProgressIndicator(),
                  height: 35,
                ),
              ),
              FSizedBox(
                width: 15,
              ),
            ],
          ),
        ] else if (_isInstallFail) ...[
          FText(i18nBook.common.installFailed.t),
        ],
        FExpanded(
          child: FSizedBox(),
        ),
      ],
    );
  }

  /// 第四步
  FWidget _buildStepFour() {
    return FColumn(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        FText(searchPrint),
        FSizedBox(
          height: 20,
        ),
        FRow(
          children: [
            FExpanded(
              child: FContainer(
                child: FLinearProgressIndicator(
                  value: searchPrinterProgress,
                ),
                height: 35,
              ),
            ),
            FSizedBox(
              width: 15,
            ),
            if (widget.deviceCode.isNullOrEmpty && searchPrinterProgress == 100)
              _buildCommonButton(
                i18nBook.common.search.t,
                _onSearchOrCancelSearchPrinter,
              ),
            if (widget.deviceCode.isNotNullOrEmpty)
              _buildCommonButton(
                searchPrinterProgress != 100
                    ? i18nBook.common.cancel.t
                    : i18nBook.common.search.t,
                _onSearchOrCancelSearchPrinter,
              ),
          ],
        ),
        FSizedBox(
          height: 20,
        ),
        FWrap(
          spacing: 5,
          runAlignment: WrapAlignment.start,
          runSpacing: 5,
          children: _buildPrinterInstalled(
            getSearchPrintersList,
            (value) {
              _getPrinterSetting(value);

              /// 初始化安装云驱动的状态
              installPrinter = 0;
              controller.findPrintDriverDatas(
                  keyWord: currentPrinter?.brand ?? '');
            },
          ),
        ),
        FExpanded(
          child: FSizedBox(),
        ),
      ],
    );
  }

  /// 第一步
  FWidget _buildStepOne() {
    return FColumn(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        FText(i18nBook.remoteControl.installedPrinters.t),
        FSizedBox(
          height: 20,
        ),
        FExpanded(
          child: FListView(
            shrinkWrap: true,
            children: [
              FWrap(
                spacing: 5,
                runAlignment: WrapAlignment.start,
                runSpacing: 5,
                children: _buildPrinterInstalled(
                  getInstalledPrintersList,
                  (value) {
                    _getPrinterSetting(value);
                  },
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 第三步
  FWidget _buildStepThree() {
    return FColumn(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        FText(i18nBook.remoteControl.enterPrinterHostnameOrIpAddress.t),
        FSizedBox(
          height: 20,
        ),
        FExpanded(
          child: _buildPrintInput(
            inputTitle: i18nBook.remoteControl.hostnameOrIpAddress.t,
            onChanged: (value) {
              ipAddress = value;
              portNumber = value;
              portNumberController.text = value;

              setState(() {});
            },
          ),
        ),
        FExpanded(
          child: _buildPrintInput(
            inputTitle: i18nBook.remoteControl.portName.t,
            textController: portNumberController,
            onChanged: (value) {
              portNumber = value;
              portNumberController.text = value;
              setState(() {});
            },
          ),
        ),
        if (isErrorIp)
          FSizedBox(
            child: FText(
              i18nBook.remoteControl.invalidIpAddressPleaseEnterAgain.t,
              style: TextStyle(
                color: Colors.red,
              ),
            ),
          ),
        FExpanded(
          child: FSizedBox(),
        ),
      ],
    );
  }

  /// 第二步
  FWidget _buildStepTwo() {
    final List<Map<String, dynamic>> options = [
      {'label': i18nBook.remoteControl.searchAvailablePrinters.t, 'value': 0},
      {'label': i18nBook.remoteControl.addPrinterUsingTcpIp.t, 'value': 1},
    ];

    return FColumn(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        FText(i18nBook.remoteControl.addPrinter.t),
        FSizedBox(
          height: 20,
        ),
        ...options
            .map((option) => FRow(
                  children: [
                    FRadio(
                      value: option['value'],
                      groupValue: _radioValue,
                      onChanged: (value) {
                        setState(() {
                          _radioValue = value;
                          isNormalSearchType = _radioValue == 0;
                        });
                      },
                    ),
                    FInkWell(
                      child: FContainer(
                        width: kIsMobile
                            ? (MediaQuery.of(context).size.width - 100)
                            : 500,
                        child: FText(option['label']),
                      ),
                      onTap: () {
                        setState(() {
                          _radioValue = option['value'];
                          isNormalSearchType = _radioValue == 0;
                        });
                      },
                    ),
                  ],
                ))
            .toList(),
        FExpanded(
          child: FSizedBox(),
        ),
      ],
    );
  }

  void _getPrinterSetting(DevicePrinterParameterDTO? value) {
    currentPrinter = value;
    ipAddress = currentPrinter?.iPAddress ?? '';
    portNumber = currentPrinter?.iPAddress ?? '';
    pageOrientation = currentPrinter?.pageOrientation;
    pageSize = currentPrinter?.pageSize;
    List<FSelectOptionModel> currentPageOrientationList = [];
    List<FSelectOptionModel> currentPageSizeList = [];
    currentPrinter?.pageOrientationList?.forEach((element) {
      currentPageOrientationList.add(
        FSelectOptionModel(
            title: PrinterTranslate.translate(element), value: element),
      );
    });
    pageOrientationList = currentPageOrientationList;
    currentPrinter?.pageSizeList?.forEach((element) {
      currentPageSizeList.add(
        FSelectOptionModel(
            title: PrinterTranslate.translate(element), value: element),
      );
    });
    pageOrientationList = currentPageOrientationList;
    pageSizeList = currentPageSizeList;
  }

  String _getProgressDisplay(double exportState) {
    if (exportState == 1.0) {
      return "100%";
    }
    return (exportState * 100).toStringAsPrecision(2) + "%";
  }

  bool _isValidIP(String ip) {
    RegExp regExp = RegExp(
      r"([1-9]?\d|1\d{2}|2[0-4]\d|25[0-5])(\.([1-9]?\d|1\d{2}|2[0-4]\d|25[0-5])){3}$",
      caseSensitive: false,
      multiLine: false,
    );
    return regExp.hasMatch(ip);
  }

  /// 删除
  void _onDelete() async {
    List<DevicePrinterParameter> parameterLists = [
      DevicePrinterParameter(
        setPrinterEnum: DevicePrinterParameterEnum.PrinterName,
        parameterValue: currentPrinterName,
      ),
    ];

    await _controller.setDevicePrinterAsync(
      deviceCode: widget.deviceCode,
      setPrinterEnum: DevicePrinterEnum.DeletePrinter,
      parameters: parameterLists,
    );
  }

  /// 获取打印机设置
  void _onDevicePrinterResult(
      Object a, DevicePrinterResultNotification e) async {
    /// 第一步获取已经安装的打印机
    if (e.setPrinterEnum == DevicePrinterEnum.GetInstalledPrinters) {
      var devicePrinterList = e.devicePrinterList;
      if (e.deviceCode.isNotNullOrEmpty) {
        devicePrinterList = await controller
            .getDevicePrintersForUploadAsync(e.deviceCode ?? '');
      }

      getInstalledPrintersList.insertAll(
        0,
        [
          ...devicePrinterList!,
        ],
      );
      isPrinterLoadding = false;

      /// 第二步搜索打印机
    } else if (e.setPrinterEnum == DevicePrinterEnum.SearchPrinter) {
      var devicePrinterList = e.devicePrinterList;
      if (e.deviceCode.isNotNullOrEmpty) {
        devicePrinterList = await controller
            .getDevicePrintersForUploadAsync(e.deviceCode ?? '');
      }
      getSearchPrintersList = devicePrinterList ?? [];
      searchPrint = i18nBook.remoteControl.searchCompleted.t;
      if (devicePrinterList?.length == 0) {
        searchPrint =
            i18nBook.remoteControl.searchCompletedNoPrintersAvailable.t;
      }
      searchPrinterProgress = 100;

      /// 删除打印机
    } else if (e.setPrinterEnum == DevicePrinterEnum.DeletePrinter) {
      if (e.remoteDeviceState == RemoteDeviceStateEnum.Success) {
        getInstalledPrintersList.remove(currentPrinter);
        currentPrinterName = i18nBook.remoteControl.addPrinter.t;
        currentPrinter = null;
      } else {
        PromptBox.toast(i18nBook.remedical.deleteFailed.t);
      }
    } else if (e.setPrinterEnum == DevicePrinterEnum.InstallPrinterProgress) {
      List<DevicePrinterParameterDTO> devicePrinterList = [];
      if (e.deviceCode.isNotNullOrEmpty) {
        devicePrinterList = await controller
            .getDevicePrintersForUploadAsync(e.deviceCode ?? '');
      }
      installPrinterProgress = devicePrinterList.first.installPrinterProgress;

      /// 下载驱动成功，安装打印机中
      if (installPrinterProgress == 100) {
        installPrinterDriver =
            i18nBook.remoteControl.downloadedSuccessInstalledPrinter.t;
      }
    } else if (e.setPrinterEnum == DevicePrinterEnum.InstallPrinterDrive) {
      if (e.remoteDeviceState == RemoteDeviceStateEnum.Success) {
        List<DevicePrinterParameterDTO> devicePrinterList = [];
        if (e.deviceCode.isNotNullOrEmpty) {
          devicePrinterList = await controller
              .getDevicePrintersForUploadAsync(e.deviceCode ?? '');
        }
        _getPrinterSetting(devicePrinterList.first);
        installPrinter = 2;
      } else if (e.remoteDeviceState == RemoteDeviceStateEnum.Fail) {
        PromptBox.toast(i18nBook.remoteControl.pushFailed.t);
        Future.delayed(Duration(milliseconds: 500), () {
          installPrinter = 0;
          setState(() {});
        });
      }
    } else if (e.setPrinterEnum == DevicePrinterEnum.PrintTestPage) {
      if (e.remoteDeviceState == RemoteDeviceStateEnum.Success) {
        testPrinter = i18nBook.remoteControl.testSuccess.t;
      } else if (e.remoteDeviceState == RemoteDeviceStateEnum.Fail) {
        PromptBox.toast(i18nBook.remoteControl.testFailed.translate(['']));
      }
    }
    setState(() {});
  }

  /// 安装打印机
  Future<void> _onInstallPrinterDrive(DevicePrinterDTO devicePrinter) async {
    var devicePrinterPatchCode = devicePrinter.code ?? '';
    if (!isRemoteMaintenance) {
      var printerDrive = PrinterDrive(
        id: devicePrinter.code ?? '',
        name: currentPrinter?.name ?? '',
        supportedPrinterModels: devicePrinter.printerModels,
        ipAddress: ipAddress,
        fileToken: devicePrinter.fileUploadInfoList?.first.fileUrl,
        size: devicePrinter.fileSize,
        createTime: devicePrinter.createTime ?? DateTime.now(),
      );
      setState(() {
        _installing = true;
      });
      remoteMaintenanceManager.installPrinterDriver(printerDrive);
      router.back();
      return;
    }
    _controller.setDevicePrinterAsync(
      deviceCode: widget.deviceCode,
      setPrinterEnum: DevicePrinterEnum.InstallPrinterDrive,
      parameters: [
        DevicePrinterParameter(
          setPrinterEnum: DevicePrinterParameterEnum.PrinterName,
          parameterValue: currentPrinter?.name,
        ),
        DevicePrinterParameter(
          setPrinterEnum: DevicePrinterParameterEnum.PrinterModel,
          parameterValue: currentPrinter?.brand,
        ),
        DevicePrinterParameter(
          setPrinterEnum: DevicePrinterParameterEnum.DevicePrinterPatchCode,
          parameterValue: devicePrinterPatchCode,
        ),
        DevicePrinterParameter(
          setPrinterEnum: DevicePrinterParameterEnum.IPAddress,
          parameterValue: ipAddress,
        ),
        DevicePrinterParameter(
          setPrinterEnum: DevicePrinterParameterEnum.Port,
          parameterValue: portNumber,
        ),
      ],
    );
    installPrinter = 1;
    router.back();
  }

  /// 上一步
  void _onPreviousStep() {
    // 第四步需要判断是否是直接需要编辑打印机
    if (step == 4 &&
        currentPrinterName != i18nBook.remoteControl.addPrinter.t) {
      if (installPrinter == 2) {
        step -= 3;
      } else {
        currentPrinter = null;
        currentPrinterName = i18nBook.remoteControl.addPrinter.t;
        step--;
      }
    }
    _initIpAndProt();

    /// 搜索ip的时候返回上一页 取消搜索
    ///  第五步需要清空一下选中的打印机
    if (step == 3) {
      _cancelSearch();
    } else {
      step--;
    }
    setState(() {});
  }

  /// 下一步
  void _onNextStep() {
    /// 如果是第一步需要判断是添加打印机还是设置打印机
    if (step == 0 &&
        currentPrinterName != i18nBook.remoteControl.addPrinter.t) {
      step += 4;
      installPrinter = 2;
      setState(() {});
      return;
    }

    /// 如果是第二步，搜索可用打印机搜索的是本地 所以跳到搜索页面
    if (step == 1) {
      /// 搜索打印机 重置搜索打印机的状态
      currentPrinter = null;
      searchPrinterProgress = null;
      getSearchPrintersList = [];
      searchPrint = i18nBook.remoteControl.searchPrinter.t;
      if (isNormalSearchType) {
        _setDevicePrinterAsync(
          deviceCode: widget.deviceCode,
          isNormalSearchType: isNormalSearchType,
        );
        step += 2;
        setState(() {});
      } else {
        //如果是Ip搜索，则跳转到Ip配置页面
        step += 1;
        setState(() {});
      }
    }

    /// 第三步，使用TCP/IP地址或者主机名添加打印机 校验ip地址是否正确
    if (step == 2) {
      setState(() {});
      print('开始校验了');
      if (_isInitIp) {
        _isInitIp = false;
        setState(() {});
        return;
      }

      /// 校验不通过
      if (!_isValidIP(ipAddress)) {
        isErrorIp = true;
        setState(() {});
        return;
      }

      _setDevicePrinterAsync(
        deviceCode: widget.deviceCode,
        isNormalSearchType: isNormalSearchType,
        isIpSearch: true,
      );
    }

    /// 第四步，判断是否有没有搜索到打印机
    if (step == 3) {
      if (searchPrinterProgress == null) {
        return;
      }
      if (currentPrinter.isNull) {
        PromptBox.toast(i18nBook.remoteControl.pleaseSelectPrinter.t);
        return;
      }
    }

    isErrorIp = false;
    step++;
    setState(() {});
  }

  /// 保存打印机
  void _onSave() {
    _controller.setDevicePrinterAsync(
      deviceCode: widget.deviceCode,
      setPrinterEnum: DevicePrinterEnum.UpdatePrinterConfiguration,
      parameters: [
        DevicePrinterParameter(
          setPrinterEnum: DevicePrinterParameterEnum.PageSize,
          parameterValue: pageSize,
        ),
        DevicePrinterParameter(
          setPrinterEnum: DevicePrinterParameterEnum.PageOrientation,
          parameterValue: pageOrientation,
        ),
        DevicePrinterParameter(
          setPrinterEnum: DevicePrinterParameterEnum.PrinterName,
          parameterValue: currentPrinter?.name,
        ),
      ],
    );
    PromptBox.toast(i18nBook.user.saveSuccess.t);
    router.back();
  }

  /// 取消或搜索打印机
  void _onSearchOrCancelSearchPrinter() {
    if (searchPrinterProgress == 100) {
      searchPrinterProgress = null;
      searchPrint = i18nBook.remoteControl.searchPrinter.t;
    } else {
      searchPrinterProgress = 100;
      searchPrint = i18nBook.remoteControl.cancelSearch.t;
    }
    _setDevicePrinterAsync(
      deviceCode: widget.deviceCode,
      isNormalSearchType: isNormalSearchType,
      isCancel: searchPrinterProgress == 100,
    );
    setState(() {});
  }

  void _onTestPrinter() {
    List<DevicePrinterParameter> parameterLists = [
      DevicePrinterParameter(
        setPrinterEnum: DevicePrinterParameterEnum.PrinterName,
        parameterValue: currentPrinter?.name,
      ),
    ];
    testPrinter = i18nBook.remoteControl.testingPrinter.t;
    _controller.setDevicePrinterAsync(
      deviceCode: widget.deviceCode,
      setPrinterEnum: DevicePrinterEnum.PrintTestPage,
      parameters: parameterLists,
    );
  }

  /// 开启打印机
  void _openPrinter() {
    router.dialog(
      () => FObx(
        () => ManagementDialog(
          dialogName: i18nBook.remoteControl.printerDriverManagement.t,
          tableColumn: PrintMachineTableColumn.printMachineList,
          tableLoading: controller.state.tableLoading,
          tableData: controller.state.printDriverTableDatas,
          onRefresh: (keyWord) {
            controller.findPrintDriverDatas(
              keyWord: currentPrinter?.brand ?? '',
            );
          },
          isSearch: false,
          onMakeSure: (value) {
            _onInstallPrinterDrive(value);
          },
          onSearch: (keyWord) {
            controller.findPrintDriverDatas(
              keyWord: keyWord,
            );
          },
        ),
      ),
      dismissible: false,
    );
  }

  /// 手机端使用云驱动
  void _openMobilePrinter() {
    controller.findPrintDriverDatas(
      keyWord: currentPrinter?.brand ?? '',
    );
    router.dialog(
      () => UsingCloudDriven(
        deviceCode: widget.deviceCode ?? '',
        currentPrinter: currentPrinter,
        ipAddress: ipAddress,
        portNumber: portNumber,
        successCallback: () {
          installPrinter = 1;
          controller.state.deviceSelectPrinterCode = '';
        },
      ),
      dismissible: false,
    );
  }

  // 根据ip搜索或取消搜索打印机
  void _setDevicePrinterAsync({
    String? deviceCode,
    bool? isCancel = false,
    bool isIpSearch = false,
    required bool isNormalSearchType,
  }) async {
    List<DevicePrinterParameter> parameterLists = [
      DevicePrinterParameter(
        setPrinterEnum: DevicePrinterParameterEnum.IPAddress,
        parameterValue: ipAddress,
      ),
      DevicePrinterParameter(
        setPrinterEnum: DevicePrinterParameterEnum.Port,
        parameterValue: portNumber,
      ),
      DevicePrinterParameter(
        setPrinterEnum: DevicePrinterParameterEnum.IsNormalSearchType,
        parameterValue: isNormalSearchType.toString(),
      ),
    ];

    await _controller.setDevicePrinterAsync(
      deviceCode: deviceCode ?? '',
      setPrinterEnum: isCancel!
          ? DevicePrinterEnum.CancelSearchPrinter
          : DevicePrinterEnum.SearchPrinter,
      parameters: parameterLists,
      isIpSearch: isIpSearch,
    );
  }

  void _onInstallPrinterDriverChange(
      Object sender, InstallPrinterDriverState e) {
    if (e == InstallPrinterDriverState.Installed) {
      setState(() {
        _installing = false;
        step = 5;
      });
    } else if (e == InstallPrinterDriverState.InstallationFailed) {
      setState(() {
        _installing = false;
        _isInstallFail = true;
      });
    }
  }
}
