
import 'package:get/get.dart';
import 'package:naiyouwl/app/controller/core.dart';
import 'package:web_socket_channel/io.dart';
import 'dart:convert';
import 'package:naiyouwl/app/bean/connect.dart';

class ConnectController extends GetxController {
  final CoreController coreController = Get.find<CoreController>();
  late IOWebSocketChannel channel;
  var connect = Rx<Connect?>(null);
  
  @override
  void onInit() {
    super.onInit();
    connectWebSocket();
  }

  void connectWebSocket() {
    channel = coreController.fetchConnectionsWs();
    channel.stream.listen((message) {
      try {
        final data = jsonDecode(message);
        if (data != null && data is Map<String, dynamic>) {
          connect.value = Connect.fromJson(data);
        } else {
          connect.value = null;
        }
      } catch (e) {
        print('解析WebSocket消息时出错: $e');
        connect.value = null;
      }
    });
  }

  @override
  void onClose() {
    channel.sink.close();
    super.onClose();
  }
}