import 'dart:async';

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: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/utils/prompt_box.dart';
import 'package:flyinsono/managers/interfaces/network_error_handler.dart';
import 'package:flyinsono/managers/interfaces/remote_controller.dart';
import 'package:flyinsono/views/common/device_live/device_live_list/controller.dart';
import 'package:flyinsono/views/common/device_live/device_live_list/widgets/printer_settings_dialog.dart';
import 'package:flyinsono/views/common/device_live/device_live_list/widgets/push_update_package.dart';
import 'package:flyinsono/views/common/device_live/device_live_list/widgets/remote_main_tenance.dart';
import 'package:get/get.dart';

/// 手机端的远程控制UI
class RemoteMainTenanceMobile extends FStatefulWidget implements FPage {
  /// 索引
  final int index;

  final double width;
  final double height;
  const RemoteMainTenanceMobile({
    super.key,
    required this.index,
    required this.width,
    required this.height,
  });
  @override
  String get pageName => 'RemoteMainTenanceMobile';

  @override
  FState<RemoteMainTenanceMobile> createState() => _RemoteMainTenanceState();
}

class _RemoteMainTenanceState extends FState<RemoteMainTenanceMobile>
    with TickerProviderStateMixin {
  static TextStyle _textStyle = TextStyle(
    color: Colors.white,
    fontSize: FFontSizes.BODY,
  );

  final _controller = Get.find<DeviceLiveListController>();
  final remoteControllerManager = Get.find<IRemoteControllerManager>();
  final networkErrorHandlerManager = Get.find<INetworkErrorHandlerManager>();

  String get deviceCode =>
      _controller.state.deviceList[widget.index].deviceCode!;
  DeviceExtendInfoDTO get _dto => _controller.state.deviceList[widget.index];
  late AnimationController _animationController;
  late Animation<double> _pageFlipAnimation;

  Timer? _heartbeatTimer;
  ConnectIconStatus connectPromp = ConnectIconStatus.None;

  late bool isHover = _controller.state.isShowDeviceDetailIndex == widget.index;
  bool get isCompleteConnect =>
      _controller.state.connectStatus[deviceCode] ==
      ConnectStatusEnum.CompleteConnect;
  bool get isOnline => _dto.isOnline == true;
  bool get isWaitConnect =>
      _controller.state.connectStatus[deviceCode] ==
      ConnectStatusEnum.WaitConnect;
  @override
  FWidget build(BuildContext context) {
    return _buildRemoteMaintenanceModule(widget.width, widget.height);
  }

  @override
  void dispose() {
    super.dispose();
    remoteControllerManager.onConnectStatusToClient
        .removeListener(_onConnectStatusToClient);
    remoteControllerManager.onDeviceDisconnectRemote
        .removeListener(_onDeviceDisconnectRemote);
    remoteControllerManager.onDeviceRejectRemoteControl
        .removeListener(_onDeviceRejectRemoteControl);

    /// 网络断开
    networkErrorHandlerManager.onNetworkInterruption
        .removeListener(_onNetworkInterruption);
    // _controller.getDeviceStateListByTokenAsync();
    // _controller.colseDevice();
    _animationController.dispose();
  }

  @override
  void initState() {
    super.initState();
    remoteControllerManager.onConnectStatusToClient
        .addListener(_onConnectStatusToClient);
    remoteControllerManager.onDeviceDisconnectRemote
        .addListener(_onDeviceDisconnectRemote);
    remoteControllerManager.onDeviceRejectRemoteControl
        .addListener(_onDeviceRejectRemoteControl);

    /// 网络断开
    networkErrorHandlerManager.onNetworkInterruption
        .addListener(_onNetworkInterruption);
    _animationController = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 500),
    );

    _pageFlipAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));
  }

  void _onNetworkInterruption(sender, e) {
    setState(() {});

    // _controller.closeHeartbeat();
    _controller.state.connectStatus[deviceCode] =
        ConnectStatusEnum.CompleteDisconnect;
    _animationController.reverse();
  }

  /// 按钮组
  FWidget _buildButtonGroup() {
    List<FWidget> _buttons = <FWidget>[
      _buildTextOutlinedButton(
        i18nBook.remoteControl.updatePush.t,
        () async {
          var deviceCode = _dto.deviceCode ?? '';
          var deviceType = _dto.deviceType ?? '';
          _controller.findPushDevicePatchPagesAsync(deviceCode, deviceType,
              _dto.deviceType == 'US' ? ["US", "FISSDK"] : ["sonopost"]);
          var connectResult = await _controller.applyRemoteConnectionAsync(
              deviceCode: deviceCode);
          if (connectResult || kDebugMode) {
            await Get.to(() => FPushUpdatePackage(deviceCode));
          }
        },
        Icons.move_up_rounded,
      ),
    ];
    if (_dto.deviceType == 'US') {
      _buttons.add(
        _buildTextOutlinedButton(
          i18nBook.remoteControl.remoteParameterAdjustment.t,
          () {
            _controller.startRemoteController(_dto);
          },
          Icons.control_camera_rounded,
        ),
      );
      _buttons.add(
        _buildTextOutlinedButton(i18nBook.remoteControl.printerSettings.t, () {
          _controller.setDevicePrinterAsync(
            deviceCode: _dto.deviceCode,
          );
          router.dialog(
            () => PrinterSettingsDialog(
              deviceCode: _dto.deviceCode ?? '',
            ),
            dismissible: false,
          );
        }, Icons.local_printshop_outlined),
      );
    } else if (_dto.deviceType != 'US' && _dto.isCanRestart) {
      _buttons.add(
        _buildTextOutlinedButton(i18nBook.remoteControl.reboot.t, () {
          _controller.restartDeviceAsync(deviceCode: _dto.deviceCode);
          setState(() {});
        }, Icons.refresh_rounded),
      );
    }

    return FContainer(
      height: widget.height - 75,
      padding: EdgeInsets.symmetric(horizontal: 6),
      child: FColumn(
        children: _buttons,
      ),
    );
  }

  /// 远程维护模块
  FWidget _buildRemoteMaintenanceModule(double width, double height) {
    return FObx(
      () {
        if (isOnline && !isHover) {
          return FContainer(
            decoration: BoxDecoration(
              border: Border(
                top: BorderSide(
                  color: Color.fromRGBO(245, 245, 245, 1),
                  width: 0.5,
                ),
              ),
              color: Colors.grey,
            ),
            width: width,
            child: FColumn(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                QuickFWidget(
                  AnimatedBuilder(
                    animation: _pageFlipAnimation,
                    builder: (context, child) {
                      var transform = Matrix4.identity();
                      return isCompleteConnect
                          ? Transform(
                              alignment: Alignment.center,
                              transform: transform,
                              child: isCompleteConnect
                                  ? _buildButtonGroup()
                                  : FSizedBox(),
                            )
                          : FSizedBox();
                    },
                  ),
                ),
                FContainer(
                  padding: EdgeInsets.symmetric(horizontal: 15),
                  height: 40,
                  child: FRow(
                    children: [
                      FText(
                        i18nBook.remoteControl.remoteControl.t,
                        style: _textStyle.copyWith(
                          /// TODO:[Gavin] 多语言-UI-整合
                          fontSize: i18nBook.isCurrentChinese ? 14 : 12,
                        ),
                      ),
                      QuickFWidget(
                        Transform.scale(
                          scale: 1.2,
                          child: FSwitch(
                            value: isCompleteConnect,
                            onChanged: (value) => _changeDeviceState(value),
                          ),
                        ),
                      ),
                      _buildConnectStatusIcon(connectPromp),
                    ],
                  ),
                ),
              ],
            ),
          );
        }
        return FSizedBox();
      },
    );
  }

  /// 边框按钮
  FWidget _buildTextOutlinedButton(
    String textString,
    Function onPressed,
    IconData iconData,
  ) {
    return FRow(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        FExpanded(
          child: FInkWell(
            onTap: () {
              onPressed.call();
            },
            child: FContainer(
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(vertical: 3),
              width: 150,
              margin: EdgeInsets.only(
                top: 3,
              ),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(
                  Radius.circular(
                    4,
                  ),
                ),
                color: FTheme.ins.colorScheme.primary,
              ),
              child: FText(
                textString,
                textAlign: TextAlign.center,
                style: _textStyle,
              ),
            ),
          ),
        ),
      ],
    );
  }

  FWidget _buildConnectStatusIcon(ConnectIconStatus connectPromp) {
    switch (connectPromp) {
      case ConnectIconStatus.Connecting:
      case ConnectIconStatus.Disconnecting:
        return FCenter(
          child: FSizedBox(
            width: 16,
            height: 16,
            child: FCircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation(Colors.white),
              strokeWidth: 3,
            ),
          ),
        );
      case ConnectIconStatus.ConnectFail:
        return FSizedBox(
          child: FCenter(
            child: FSizedBox(
              width: 20,
              height: 20,
              child: FIcon(
                Icons.highlight_off,
                color: Colors.white,
              ),
            ),
          ),
        );
      default:
        return FSizedBox();
    }
  }

  void _changeDeviceState(bool value) async {
    if (value) {
      _controller.state.connectStatus[deviceCode] =
          ConnectStatusEnum.WaitConnect;
      connectPromp = ConnectIconStatus.Connecting;
      final result = await _controller.applyRemoteConnectionAsync(
        deviceCode: _dto.deviceCode ?? '',
      );
      if (!result) {
        _controller.state.connectStatus[deviceCode] =
            ConnectStatusEnum.UnConnect;
        connectPromp = ConnectIconStatus.None;
      }
      _animationController.forward();
    } else {
      connectPromp = ConnectIconStatus.Disconnecting;
      _controller.applyRemoteConnectionAsync(
        deviceCode: _dto.deviceCode ?? '',
        controlType: ControlDeviceParameterEnum.End,
      );
      _animationController.reverse();
    }
    setState(() {});
  }

  _onConnectStatusToClient(Object a, ConnectStatusToClientNotification e) {
    setState(() {
      if (e.deviceCode == _dto.deviceCode) {
        if (e.remoteDeviceState == RemoteDeviceStateEnum.Success) {
          _controller.state.connectStatus[deviceCode] =
              ConnectStatusEnum.CompleteConnect;
          connectPromp = ConnectIconStatus.None;
        }
        if (e.remoteDeviceState == RemoteDeviceStateEnum.Fail) {
          connectPromp = ConnectIconStatus.ConnectFail;
        }
      }
      _heartbeatTimer?.cancel();
      _heartbeatTimer = null;
      _startHeartbeat();
    });
  }

  /// 设备端断开连接的通知
  _onDeviceDisconnectRemote(
      Object a, DeviceDisconnectRemoteControlNotification e) {
    if (e.deviceCode == _dto.deviceCode) {
      if (e.remoteDeviceState ==
          RemoteDeviceStateEnum.DeviceTimeOutDisconnect) {
        PromptBox.toast(i18nBook.remoteControl.deviceTimeoutDisconnection.t);
      } else if (e.remoteDeviceState ==
          RemoteDeviceStateEnum.UserTimeOutDisconnect) {
        PromptBox.toast(i18nBook.remoteControl.clientTimeout.t);
      } else if (e.remoteDeviceState ==
          RemoteDeviceStateEnum.DeviceDisconnect) {
        PromptBox.toast(i18nBook.remoteControl.deviceDisconnected.t);
        Future.delayed(Duration(milliseconds: 1000), () {
          _controller.reloadList();
        });
      }
      connectPromp = ConnectIconStatus.None;
      _controller.state.connectStatus[deviceCode] =
          ConnectStatusEnum.CompleteDisconnect;
    }
    setState(() {});
  }

  _onDeviceRejectRemoteControl(
      Object a, DeviceRejectRemoteControlNotification e) {
    setState(() {
      if (e.deviceCode == _dto.deviceCode) {
        connectPromp = ConnectIconStatus.None;
        PromptBox.toast(i18nBook.remoteControl.probeControlOff.t);
      }
    });
  }

  /// 开启远程连接心跳
  Future<void> _startHeartbeat() async {
    _heartbeatTimer = Timer.periodic(
      Duration(seconds: 5),
      (timer) {
        _controller.remoteConnectHeartRateSendOnce();
      },
    );
  }
}
