wujingjing
2024-12-14 1476d27514874e9c95002451a81878bd9bec8382
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
import moment from 'moment';
import { Ref, ShallowRef, computed, nextTick, onBeforeUnmount, ref, unref } from 'vue';
import { LOAD_CHAT_LIMIT } from '../constants';
import { AnswerType, ChatContent, ChatMessage, MultiChatType, RoleEnum, StepEnum, StepItem } from '../model/types';
import { GetHistoryAnswer, QueryHistoryDetail, getShareChatJsonByPost } from '/@/api/ai/chat';
import router from '/@/router';
import { isSharePage } from '/@/stores/chatRoom';
type UseScrollLoadOption = {
    container: ShallowRef<HTMLDivElement>;
    historyGroupId: string | Ref<string>;
    messageList: Ref<ChatMessage[]>;
    parseAnswerContent: (res: any) => ChatContent;
};
 
export const convertProcessItem = (processItem: any) => {
    switch (processItem.mode) {
        case 'begin':
            break;
        case 'end':
            break;
    }
    return {
        status: StepEnum.Success,
        title: processItem.value,
    } as StepItem;
};
export const convertProcessToStep = (process: any[]) => {
    const stepList = (process ?? []).reduce((preVal, curVal) => {
        if (curVal.mode === 'question') {
            const last = preVal.at(-1);
            if (!last.subStep) {
                last.subStep = [];
            }
            const sub = {
                data: curVal.value,
                type: MultiChatType.Select,
            };
            last.subStep.push(sub);
        } else {
            const cur = convertProcessItem(curVal);
            preVal.push(cur);
        }
        return preVal;
    }, []);
    return stepList;
};
 
/**
 * 滚动加载数据
 * @returns
 */
export const useScrollLoad = (option: UseScrollLoadOption) => {
    const { container, historyGroupId, messageList, parseAnswerContent } = option;
    const moreIsLoading = ref(false);
 
    /** @description 下次需要加载的用户结束索引(倒着数) */
    const nextUserMsgEndIndex = ref(0);
 
    // 是否没有更多数据了
    let isNoMore = false;
    const getAnswerById = async (historyId: string) => {
        return await GetHistoryAnswer({
            history_id: historyId,
        });
    };
    const formatShowTimeYear = computed(() => {
        return (str) => {
            return moment(str).format('MM月DD日 HH:mm:ss');
        };
    });
    /**
     * 获取用户回复数据,并插入到对话当中去
     */
    const loadReplyData = async (userMsg: any[]) => {
        const userItemIdMap = new Map();
        // 用户消息
        const tmpMessageList: ChatMessage[] = userMsg.map((item) => {
            return {
                historyId: item.history_id,
                role: RoleEnum.user,
                content: {
                    type: AnswerType.Text,
                    values: item.question,
                },
                isChecked: false,
            } as ChatMessage;
        });
        const resList = await Promise.all(
            (userMsg ?? []).map((item) => {
                userItemIdMap.set(item.history_id, item);
                return getAnswerById(item.history_id);
            })
        );
        let i = 0;
        resList.map((item, index) => {
            const insertIndex = index + 1 + i;
            const currentUserMsg = tmpMessageList[insertIndex - 1];
            currentUserMsg.content.values = item?.answer?.question ?? currentUserMsg.content.values;
 
            const mapUser = userItemIdMap.get(item.answer?.history_id);
 
            const answerTime = formatShowTimeYear.value(mapUser?.create_time);
            tmpMessageList.splice(
                insertIndex,
                0,
                item.answer === null
                    ? null
                    : {
                            historyId: item.answer?.history_id,
                            role: RoleEnum.assistant,
                            content: parseAnswerContent(item.answer),
                            state: item.answer_state,
                            sectionAId: mapUser?.section_a_id,
                            createTime: answerTime,
                            stepList: convertProcessToStep(item?.answer?.exec_process),
                            stepIsShow: false,
                            isStopMsg: false,
 
                            conclusion: item?.answer?.conclusion ?? [],
                            isChecked: false,
                      }
            );
            i++;
        });
 
        messageList.value.unshift(...tmpMessageList);
    };
 
    /**
     * 加载分享数据
     */
    const loadShareData = async () => {
        const res = await getShareChatJsonByPost({
            share_id: router.currentRoute.value.query.id as string,
        });
 
        const msgValue = res?.values;
        if (!msgValue) {
            messageList.value = [];
            return;
        }
        const userMsg: ChatMessage = {
            historyId: msgValue.history_id,
            role: RoleEnum.user,
            content: {
                type: AnswerType.Text,
                values: msgValue.question,
            },
            isChecked: false,
        };
 
        const assistantMsg: ChatMessage = {
            historyId: msgValue.history_id,
            role: RoleEnum.assistant,
            content: parseAnswerContent(msgValue),
            stepList: convertProcessToStep(msgValue.exec_process),
            stepIsShow: false,
            isStopMsg: false,
 
            conclusion: msgValue.conclusion ?? [],
            isChecked: false,
        };
        messageList.value = [userMsg, assistantMsg];
    };
 
    /**
     * 加载滚动范围数据
     */
    const loadRangeData = async (lastEnd = nextUserMsgEndIndex.value) => {
        if (isSharePage.value) {
            await loadShareData();
            return;
        }
        const res = await QueryHistoryDetail({
            history_group_id: unref(historyGroupId),
            last_end: lastEnd,
            last_count: LOAD_CHAT_LIMIT,
        });
        const result: ChatMessage[] = res.details ?? [];
        if (result.length) {
            nextUserMsgEndIndex.value += result.length;
            await loadReplyData(res.details);
        } else {
            isNoMore = true;
        }
 
        return result;
    };
 
    //滚动监听
    async function onChatListScroll() {
        if (container.value.scrollTop == 0) {
            // 更多数据正在加载时
            if (moreIsLoading.value) {
                return;
            }
 
            if (isNoMore) {
                return;
            }
 
            let h1 = container.value.scrollHeight;
            moreIsLoading.value = true;
            await loadRangeData(nextUserMsgEndIndex.value).finally(() => {
                moreIsLoading.value = false;
            });
            //更新后,等待页面渲染完毕再去拿scrollHeight,否则拿到的是之前的
            nextTick(() => {
                nextTick(() => {
                    nextTick(() => {
                        let h2 = container.value.scrollHeight;
                        container.value.scrollTo({
                            //顶部在原先基础上往下滚动50px,露出新加载数据的一点
                            // top: h2 - h1 - 50,
                            top: h2 - h1,
                            behavior: 'instant', //auto-自动滚动 instant-瞬间滚动 smooth-平滑滚动
                        });
                    });
                });
            });
        }
    }
 
    onBeforeUnmount(() => {
        container.value.removeEventListener('scroll', onChatListScroll);
    });
 
    return {
        nextUserMsgEndIndex,
        loadRangeData,
        onChatListScroll,
        moreIsLoading,
    };
};