import { defineStore, storeToRefs } from 'pinia';
import { ref } from 'vue';

import { global } from './global';
import { getCache, setCache } from '@/utils';
export const socket = defineStore('socket', () => {
  const socket = ref();
  const status = ref(true); // true在线 false离线
  let hbTimer: any;
  const hbDelay = 25000;
  let rcTimer: any;
  let count = 0;
  let socketStatus = 0;
  const channelId = '';
  const rcDelay = 10000;

  const callBackList = ref<((...args: []) => void)[]>([]);

  function beforeInit() {
    if (socketStatus > 0) return false;
    socket.value?.close(); // 关闭之前的socket
    return true;
  }
  async function initSocket(simSerialNumber: string) {
    const token = getCache('token');
    init();
    function init() {
      if (!beforeInit()) return;
      socket.value = uni.connectSocket({
        url: `${process.env.VITE_WS_URL}?accessToken=${token}`,
        complete: () => {},
      });

      socket.value.onOpen(() => {
        console.log('Socket已打开！', simSerialNumber);
        count = 0;
        socketStatus = 10;
        clearInterval(hbTimer);
        clearInterval(rcTimer);
        heartBeat(); // 心跳
        socketSend({ type: 'desktopPreview', simSerialNumber: simSerialNumber });
        // status.value = SOCKET_STATUS.CONNECTED;
      });
      socket.value.onError((err: any) => {
        // console.log('Socket打开失败！');
        console.error(err);
        socketStatus = 0;
        // status.value = SOCKET_STATUS.OFFLINE;
        reconnect();
      });
      socket.value.onClose((err: any) => {
        // console.log('Socket已断开！');
        console.error(err);
        socketStatus = 0;
        // status.value = SOCKET_STATUS.OFFLINE;
        reconnect();
      });
      socket.value.onMessage((res: anyObj) => {
        // 接收服务器返回信息
        const info = JSON.parse(res.data);
        console.log('socketMsg', info);
        uni.$emit('socketMsg', info);
      });
    }

    // 心跳
    function _heartBeat() {
      // console.log('心跳')
      if (!getCache('token')) {
        socket.value?.close();
        clearInterval(hbTimer);
        return;
      }
      socketSend({
        message: 'ping',
      });
    }
    function heartBeat() {
      _heartBeat(); // 首次连上必须ping才建立通道
      hbTimer = setInterval(() => _heartBeat(), hbDelay);
    }

    // 重连
    function reconnect(leading = false) {
      clearInterval(hbTimer);
      if (leading) {
        init();
        return;
      }
      rcTimer = setTimeout(() => {
        count++;
        console.error(`Socket尝试重连（第${count}次）`);
        init();
      }, 10000);
    }
  }

  // 消息回调
  function callback(res: anyObj) {
    // console.log('接收消息',res)
  }

  // 发送消息
  function socketSend(value: any) {
    console.log('send', value);
    socket.value.send({
      data: JSON.stringify(value),
      success: () => {
        console.log('发送成功');
      },
    });
  }

  // 增加回调
  function addCallBack(cb: any) {
    if (callBackList.value.some(i => i === cb)) return;
    callBackList.value.push(cb);
  }

  // 删除回调
  function removeCallBack(cb: any) {
    const idx = callBackList.value.findIndex(i => i === cb);
    if (idx === -1) return;
    callBackList.value.splice(idx, 1);
  }

  // 关闭socket
  function closeSocket() {
    socket.value?.close();
  }

  return {
    socket,
    status,
    callBackList,
    initSocket,
    socketSend,
    addCallBack,
    removeCallBack,
    closeSocket,
    callback,
  };
});
