import request from '@/utils/request';
import { AxiosPromise } from 'axios';
import { AskVO } from '@/api/ai/skill/aiChat/types';
import EventSourcePolyfill from 'event-source-polyfill';
import { AiChatMessageForm } from '@/api/ai/skill/aiChat/types';


/**
 * 下拉框查询AI模型列表
 * @param query
 * @returns {*}
 */
export function getAiModelJoinList (query) {
  return request({
    url: '/ai/assistant/getAiModelJoinList',
    method: 'get',
    params: query
  });
};


/**
 * 获取AI会话列表
 * @param query
 * @returns {*}
 */
export function getAiChatMessageList (query) {
  return request({
    url: '/ai/assistant/getAiChatMessageList',
    method: 'get',
    params: query
  });
};

/**
 * 根据会话ID获取会话信息列表
 * @param query
 * @returns {*}
 */
export function getAiChatMessages (sessionId: string) {
  return request({
    url: '/ai/assistant/getAiChatMessages/'+sessionId,
    method: 'get',
  });
};


/**
 * 修改AI会话标题
 * @param data
 */
export const updateAiMessageTopic = (data: AiChatMessageForm) => {
  return request({
    url: '/ai/assistant/updateAiChatMessageTopic',
    method: 'post',
    data: data
  });
};

/**
 * 删除AI会话信息
 * @param sessionId
 */
export const delAiMessage = (sessionId: string) => {
  return request({
    url: '/ai/assistant/' + sessionId,
    method: 'delete'
  });
};


export const generateSql = (query?: AskVO): AxiosPromise<AskVO[]> => {
  return request({
    url: '/ai/assistant/generateSql',
    method: 'post',
    params: query,
    timeout: 1000000
  });
};




/**
 * AI问答，完整回复
 * @param query
 * @returns {*}
 */

export const aiAsk = (query?: AskVO): AxiosPromise<AskVO[]> => {
  return request({
    url: '/ai/api/stream/ask',
    method: 'get',
    params: query
  });
};

export const aiStreamAsk = (query?: AskVO): AxiosPromise<AskVO[]> => {
  return request({
    url: '/ai/api/stream/stream',
    method: 'post',
    params: query
  });
};




export const streamDeepSeek = (prompt, handlers) => {
  const url = `/ai/api/stream/stream?prompt=${encodeURIComponent(prompt)}`;

  const eventSource = new EventSourcePolyfill(url, {
    headers: {
      'Content-Type': 'text/event-stream'
    },
    withCredentials: false, // 根据你的CORS配置调整
    heartbeatTimeout: 300000 // 5分钟超时
  });

  eventSource.onmessage = (event) => {
    if (event.data === '[DONE]') {
      handlers.onComplete();
      eventSource.close();
    } else {
      try {
        handlers.onData(event.data);
      } catch (e) {
        console.error('Error processing chunk:', e);
      }
    }
  };

  eventSource.onerror = (error) => {
    handlers.onError(new Error(`EventSource failed: ${error.message || 'Unknown error'}`));
    eventSource.close();
  };

  return () => {
    eventSource.close();
  };
};
