// import { Message } from 'element-ui';
// import projectConfig from '@/core/config';
import { getToken } from '@/utils';
class GetStreaming {
  constructor (url, param, onmessage = () => {}, success = () => {}) {
    // eslint-disable-next-line no-unused-vars
    this.tokrn = getToken()
    this.param = param
    this.url = url
    this.es = null;
    this.onmessage = onmessage
    this.success = success
  }
  // 初始化weosocket
  initeventSource () {
    fetch(this.url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(this.param)
    })
      .then(response => {
        if (response.ok) {
          const reader = response.body.getReader();
          return this.readStream(reader);
        } else {
          throw new Error(`Unexpected status code: ${response.status}`);
        }
      })
      .catch(error => {
        console.error(`Error: ${error.message}`);
      });
  }

  readStream (reader) {
    return reader.read().then(({ done, value }) => {
      if (done) {
        console.log('Stream ended');
        this.success()
        return;
      }
      const chunk = new TextDecoder().decode(value);
      this.onmessage(chunk)
      // Continue reading the next chunk
      return this.readStream(reader);
    });
  }
}

export { GetStreaming }

// import { fetchEventSource } from '@microsoft/fetch-event-source';
// submit () {
//       fetchEventSource('/2api/chat/chat', {
//         method: 'POST',
//         signal: new AbortController().signal,
//         headers: {
//           'Content-Type': 'application/json'
//         },
//         body: JSON.stringify(this.param),
//         async onopen (response) {
//           console.log('连接了:', response);
//         },
//         onmessage (msg) {
//           console.log('消息:', msg);
//         },
//         onclose () {
//           console.log('关闭');
//         },
//         onerror (err) {
//           throw new Error(err)
//         }
//       });
//     }
