import { getToken } from '@/utils/auth';
import { ElNotification } from 'element-plus';
import { useNoticeStore } from '@/store/modules/notice';
import { toRefs } from 'vue';

// 初始化
export const initSSE = (url: any) => {
  const noticeStore = useNoticeStore();
  const { isNotice, notices } = toRefs(noticeStore.state);
  if (import.meta.env.VITE_APP_SSE === 'false') {
    return;
  }

  url = url + '?Authorization=Bearer ' + getToken() + '&clientid=' + import.meta.env.VITE_APP_CLIENT_ID;
  const { data, error } = useEventSource(url, [], {
    autoReconnect: {
      retries: 5,
      delay: 5000,
      onFailed() {
        console.log('Failed to connect after 5 retries');
      }
    }
  });

  watch(error, () => {
    console.log('SSE connection error:', error.value);
    error.value = null;
  });

  watch(data, () => {
    if (!data.value) return;

    // 打印接收到的 SSE 消息
    console.log('=== SSE 接收到消息 ===');
    console.log('消息内容:', data.value);
    console.log('消息类型:', typeof data.value);
    console.log('接收时间:', new Date().toLocaleString());
    console.log('=====================');

    useNoticeStore().addNotice({
      message: data.value,
      read: false,
      time: new Date().toLocaleString()
    });
    const displayMessage = data.value.split('|')[0].trim();
    // ElNotification({
    //   title: '消息',
    //   message: displayMessage,
    //   type: 'success',
    //   duration: 3000
    // });
    noticeStore.state.isNotice = true;
    data.value = null;
  });
};
