import 'dart:async';
import 'dart:convert';

import 'package:ef/ef.dart';
import 'package:vbvs_app/controller/user_info_controller.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

class WebsocketProp {
  late WebSocketChannel channel;
  bool isConnecting = false;
  bool isOpen = false;
  bool isClose = false; //是否关闭
  late String url;
  late Map fun;

  WebsocketProp initState(String url_, Map funn) {
    print(url_);
    fun = funn;
    url = url_;
    isConnecting = false;
    _connect();
    return this;
  }

  void _connect() {
    isOpen = false;
    channel = IOWebSocketChannel.connect(
        "$url?token=${Get.find<UserInfoController>().model.token}");
    channel.stream.listen((message) {
      // print('Received message: $message');
      // Handle incoming messages here
      heartCheck();
      if (isOpen == false) {
        fun['open']?.call();
        print('Received message: $message');
        isOpen = true;
        isConnecting = false;
        // Get.find<BedController>().websocketSend(1);
        return;
      }
      if (message == "ht") {
        print('Received message: $message');
        return;
      }
      fun["message"]?.call(message);
    }, onError: (error) {
      // Handle connection error and initiate reconnection
      print('Error: $error');
      isOpen = false;
      _reconnect();
    }, onDone: () {
      // Handle connection closed
      print('Connection closed');
      isOpen = false;
      _reconnect();
    });
  }

  Timer? timeoutObj;
  Timer? serverTimeoutObj;
  int timeout = 10;

  void heartCheck() {
    timeoutObj?.cancel();
    serverTimeoutObj?.cancel();
    timeoutObj = Timer(Duration(seconds: timeout), () {
      sendMessage("ht");
      serverTimeoutObj = Timer(Duration(seconds: timeout), () {
        dispose();
      });
    });
  }

  void _reconnect() {
    if (isClose) {
      return;
    }
    if (!isConnecting) {
      isConnecting = true;
      _connect();
      Timer(const Duration(seconds: 5), () {
        isConnecting = false;
        if (isOpen == false) {
          _reconnect();
        }
      });
    }
  }

  void sendMessage(data) {
    if (isOpen == false) {
      // showToast("websocket 已断开");
      return;
    }
    if (data is String) {
      channel.sink.add(data);
    } else {
      String s = jsonEncode(data);
      // print("发送 $s");
      channel.sink.add(s);
    }
  }

  sendWebSocketMessageCodeN(code, data) {
    sendMessage({"code": code, "data": data});
  }

  void dispose() {
    isClose = true;
    channel.sink.close();
  }
}
