// utils/socket.js
import { ref, onUnmounted } from 'vue';

export default function useWebSocket() {
	const continturl='http://10.75.15.246:8899/mqttprod/ws';
	console.log("传进来的url----useWebSocket----11111--",continturl)
  // 连接状态
  const isConnected = ref(false);
  // 接收的消息
  const receivedMessages = ref([]);
  // WebSocket实例
  let socket = null;
  console.log("连接WebSocket---22222---",continturl)
  // 连接WebSocket
  const connect = () => {
    // 使用uni-app的WebSocket API
    socket = uni.connectSocket({
      url: continturl,
      success: () => {
        console.log('WebSocket连接成功');
      },
      fail: (err) => {
        console.error('WebSocket连接失败:', err);
      }
    });
    console.log("连接WebSocket---333333---",continturl)
    // 监听连接打开
    socket.onOpen(() => {
      isConnected.value = true;
      console.log('WebSocket已连接');
    });
    
    // 监听消息接收
    socket.onMessage((res) => {
      try {
        // 尝试解析JSON消息
        const message = JSON.parse(res.data);
        receivedMessages.value.push(message);
      } catch (e) {
        // 普通文本消息
        receivedMessages.value.push(res.data);
      }
    });
        
    // 监听错误
    socket.onError((err) => {
      console.error('WebSocket错误:', err);
    });
  };
  // 监听连接关闭
  socket.onClose(() => {
    isConnected.value = false;
    console.log('WebSocket已关闭');
  });
  
  // 发送消息
  const sendMessage = (data) => {
    if (isConnected.value) {
      socket.send({
        data: typeof data === 'string' ? data : JSON.stringify(data),
        success: () => {
          console.log('消息发送成功');
        },
        fail: (err) => {
          console.error('消息发送失败:', err);
        }
      });
    } else {
      console.error('WebSocket未连接，无法发送消息');
    }
  };
  
  // 关闭连接
  const disconnect = () => {
	  console.log("关闭连接------",socket)
    if (socket) {
      socket.close({
        success: () => {
          console.log('WebSocket关闭成功');
        },
        fail: (err) => {
          console.error('WebSocket关闭失败:', err);
        }
      });
      socket = null;
    }
  };
  
  // 组件卸载时关闭连接
  onUnmounted(() => {
    disconnect();
  });
  
  return {
    isConnected,
    receivedMessages,
    connect,
    sendMessage,
    disconnect
  };
}