import type { TaskCallback, TaskConfig, TaskDataInfo as TaskMindInfo, TaskInterface, TaskMessageModel, TaskLoadMoreRequestInterface, TaskLoadMoreResponseInterface, TaskUrlConfig } from './interface/task'; import request from './request'; export default class Task implements TaskInterface { _callback: TaskCallback; mindInfo: TaskMindInfo; private taskList: TaskMessageModel[] = []; private _cacheTaskList: TaskMessageModel[] = []; // 等待的时候,将内容添加到 cacheTaskList 中 private _startReceiveMessage = false; private _sessionId: string; private _urlConfig: TaskUrlConfig; set callback(callback: TaskCallback) { // 更新 callback 之后,更新内容 this._callback = callback; this._callback.onTaskListDidUpdate(this.taskList); } get callback(): TaskCallback { return this._callback; } constructor(taskConfig: TaskConfig) { const { callback, mindInfo, sessionId, urlConfig: taskURLConfig } = taskConfig; this._callback = callback; this.mindInfo = mindInfo; this._sessionId = sessionId; this._startReceiveMessage = false; this._urlConfig = taskURLConfig; } waitingForStart(): void { this._startReceiveMessage = false; } startReceiveMsg(): Promise { return this.fetchAllHistoryMsg() .then((res) => { const newTaskList = [...res, ...this._cacheTaskList]; newTaskList.forEach((item) => { this._appendTask(item); }); this._startReceiveMessage = true; this._cacheTaskList = []; return; }) .catch((error) => { this._startReceiveMessage = true; this._cacheTaskList = []; this.callback.onTaskListLoadError(error); return; }); } // 获取所有的 msg fetchAllHistoryMsg(): Promise { const loadMsg: ( msgList?: TaskMessageModel[] ) => Promise = (msgList) => { const currentMsg = msgList ?? []; const seqId = currentMsg.at(0)?.seqId; return this.fetchTaskMsg({ history: true, seqId: seqId }).then((msg) => { const newMsg = [...msg, ...(msgList ?? [])]; // 如果加载新消息的时候,没有新消息,那么就不需要再次加载了。 if (msg.length === 0) { return Promise.resolve(newMsg); } return loadMsg(newMsg); }); }; return loadMsg(); } fetchTaskMsg(data: { history: boolean; seqId?: string | undefined; }): Promise { const { history, seqId } = data; const direction = history ? 'backward' : 'forward'; const params = new URLSearchParams({ sessionId: this._sessionId, direction, refUserId: this._urlConfig.refUserId }); if (seqId) { params.append('seqId', seqId); } return request( { baseUrl: this._urlConfig.baseUrl, url: `/chat/rest/general/task/canvas/page?${params.toString()}`, method: 'GET', header: this._urlConfig.header } ).then((res) => { return res.list; }); } appendTask(taskItem: TaskMessageModel): void { if (!this._startReceiveMessage) { this._cacheTaskList.push(taskItem); return; } this._appendTask(taskItem); } /** * 内部调用,不需要校验当前状态 * @param taskItem 内部需要追加的 taskItem */ private _appendTask(taskItem: TaskMessageModel): void { this.taskList.push(taskItem); this.callback.onTaskListDidUpdate(this.taskList); } }