wujingjing
2025-01-16 8628af0dc8ce68662b339559935519a7f4a2d025
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
import { reject } from 'lodash-es';
import { computed, ref } from 'vue';
import { CreateHistoryGroup, GetHistoryGroups, getSectionList, getSelectSample, getUserTemplateList } from '../api/ai/chat';
import type { ChatRoomItem } from '../layout/component/sidebar/components/types';
import { router } from '../router';
import emitter from '../utils/mitt';
import { gotoRoute } from '../utils/route';
import { Local } from '../utils/storage';
import { PingLogin } from '../api/system';
import { SSEClient } from '../utils/sse/SSEClient';
import { accessSessionKey } from '../utils/request';
import { MAIN_URL } from '../constants';
 
/**
 * Room 关联的一些配置
 */
export type RoomConfig = {
    /** 是否直接调用大模型(通义千问)回答 */
    isAnswerByLLM: boolean;
    /** @description 从首页进去获取的第一个回复,回调函数 */
    firstResCb: any;
    /** @description 当前聊天室的 group_type */
    activeGroupType: string;
};
 
export type RoomConfigKey = keyof RoomConfig;
export const roomConfig = ref<Record<string, RoomConfig>>(null);
 
export const setRoomConfig = <T extends RoomConfigKey>(roomId: string, key: T, value: RoomConfig[T]) => {
    if (!roomId) return;
    if (!roomConfig.value) {
        roomConfig.value = {};
    }
    if (!roomConfig.value[roomId]) {
        roomConfig.value[roomId] = {
            [key]: value,
        } as any;
    } else {
        roomConfig.value[roomId][key] = value;
    }
};
 
export const getRoomConfig = <T extends RoomConfigKey>(roomId: string, key: T) => {
    if (!roomId) return;
    if (!roomConfig.value) {
        return null;
    }
    if (!roomConfig.value[roomId]) {
        return null;
    } else {
        return roomConfig.value[roomId][key];
    }
};
 
export const chatRoomList = ref<ChatRoomItem[]>([]);
 
export const activeRoomId = ref(null);
export const activeChatRoom = computed(() => chatRoomList.value?.find((item) => item.id === activeRoomId.value));
export const activeSampleId = ref(null);
export const activeSectionAId = ref(null);
export const topGroupId = ref(null);
 
export const activeLLMId = ref(null);
 
/** @description 当前聊天室 groupType */
export const activeGroupType = computed({
    get: () => {
        const result = getRoomConfig(activeRoomId.value, 'activeGroupType') ?? '业务场景';
        return result;
    },
    set: (value) => {
        setRoomConfig(activeRoomId.value, 'activeGroupType', value);
    },
});
 
/**
 * 全局使用的 ref
 */
export const sectionAList = ref([]);
export const isShowLogin = ref(false);
export const isLoginStatus = ref(false);
 
//#region ====================== 全局使用数据 ======================
// 主场景 列表
export const sceneGroupList = ref([]);
// groupType 列表
export const groupTypeList = computed(() => Array.from(new Set(sceneGroupList.value.map((item) => item.group_type))));
// 办公/模板 列表
export const exampleSceneList = ref([]);
export const officeList = ref([]);
export const groupTypeMapIcon = {
    办公助手: 'ywicon-bangong',
    知识库: 'ywicon-changyonggongjuzhishisuoyin',
    业务场景: 'ywicon-yewu',
};
const getSelectListSample = async (res1, res2) => {
    try {
        const samples = res1?.value?.samples ?? [];
        const templateSamples = (res2?.value?.templates ?? []).map((item) => ({
            group_id: item.template_group,
            sample_id: item.template_id,
            sample_title: item.template_title,
            sample_question: item.template_value,
            template_create_time: item.create_time,
            template_type: item.template_type,
            isTemplate: true,
        }));
        exampleSceneList.value = samples
            .concat(templateSamples)
            .map((item) => ({ ...item, Icon: '/static/images/wave/ChatImg.png', BgColor: randomHexColor() }));
    } catch (error) {
        console.error('获取选择列表样本时出错:', error);
    }
};
//随机生成颜色
const randomHexColor = () => {
    return `#${Math.floor(Math.random() * 16777215)
        .toString(16)
        .padEnd(6, '0')}`;
};
/**
 * 获取全局所有数据
 */
export const getAllData = async () => {
    Promise.allSettled([getSectionList(), getSelectSample({}), getUserTemplateList()])
        .then((res) => {
            let [sectionList, selectSample, userTemplateList] = res;
            sceneGroupList.value = sectionList?.value?.groups ?? [];
            getSelectListSample(selectSample, userTemplateList);
        })
        .catch((err) => {});
    getHistoryChatRooms();
};
 
//#endregion
/** @description 聊天室展示模式 */
export type ChatMode = 'share' | 'default';
 
/** @description 聊天室展示模式 */
// export const chatDisplayMode = ref<ChatMode>('default');
 
export const SHARE_PAGE_NAME = 'ShareAnswer';
export const isSharePage = computed(() => {
    const isShare = router.currentRoute.value.name === SHARE_PAGE_NAME;
    return isShare;
});
 
export const newChatRoomClick = async () => {
    const res = await CreateHistoryGroup({
        group_title: '新建对话开始',
    });
 
    const newRoom = {
        id: res.history_group_id,
        isInitial: true,
        title: '新建对话开始',
    };
    if (!chatRoomList.value) {
        chatRoomList.value = [newRoom];
    } else {
        chatRoomList.value.unshift(newRoom);
    }
    activeRoomId.value = newRoom.id;
 
    gotoAnswerPage(newRoom);
};
export const gotoAnswerPage = (room: ChatRoomItem) => {
    if (room.isInitial) {
        gotoRoute({
            name: 'Home',
            query: {
                id: room.id,
            },
        });
    } else {
        gotoRoute({
            name: 'AskAnswer',
            query: {
                id: room.id,
            },
        });
    }
    setTimeout(() => {
        emitter.emit('isShowHomePage', room.isInitial);
    }, 300);
};
 
// 用户信息
export const userInfo = {
    get: () => {
        return Local.get('userInfo');
    },
    set: (val) => {
        return Local.set('userInfo', val);
    },
    clear: () => {
        Local.remove('userInfo');
    },
    get isNew() {
        return !this.get()?.web_login;
    },
};
 
let getHistoryChatRoomsPromise: Promise<any>;
//历史对话
const getHistoryChatRooms = async () => {
    getHistoryChatRoomsPromise = new Promise(async (resolve, reject) => {
        if (isSharePage.value) return resolve(null);
        const res = await GetHistoryGroups();
        const resData = (res?.groups || []) as any[];
        // 按最晚时间到最早时间
        chatRoomList.value = resData
            ?.toSorted((a, b) => {
                return b.create_time.localeCompare(a.create_time);
            })
            .map((item) => {
                return {
                    id: item.group_id,
                    title: item.group_title,
                    createTime: item.create_time,
                    isInitial: Number(item.chat_count) === 0,
                };
            });
 
        resolve(chatRoomList.value);
    });
};
 
const roomClick = (room: ChatRoomItem) => {
    activeRoomId.value = room.id;
 
    gotoAnswerPage(room);
};
 
export const selectFirstRoom = () => {
    getHistoryChatRoomsPromise.then(() => {
        if (!chatRoomList.value || chatRoomList.value.length === 0) {
            newChatRoomClick();
        } else {
            const toClickRoom = activeChatRoom.value ?? chatRoomList.value[0];
            roomClick(toClickRoom);
        }
    });
};
 
export const pingLogin = async () => {
    // 5分钟
    const interval = 1000 * 60 * 5;
    // const interval = 1000 *2;
 
    const timer = setInterval(async () => {
        const res = await PingLogin();
        if (!res?.is_login) {
            clearInterval(timer);
        }
    }, interval);
    return timer;
};