vue-vben-admin/packages/effects/common-ui/src/ui/spider/spider-work-view.vue

417 lines
11 KiB
Vue
Raw Normal View History

<script setup lang="ts">
import type { BubbleListProps } from 'ant-design-x-vue';
import type { DrawerPlacement } from '@vben-core/popup-ui';
import type { SpiderItem } from './typing';
import { h, ref, watch } from 'vue';
import { useVbenDrawer } from '@vben-core/popup-ui';
import {
Button,
Card,
CardContent,
CardFooter,
CardHeader,
CardTitle,
} from '@vben-core/shadcn-ui';
import { UserOutlined } from '@ant-design/icons-vue';
import { Flex, message, RangePicker } from 'ant-design-vue';
import { Attachments, Bubble } from 'ant-design-x-vue';
import dayjs, { Dayjs } from 'dayjs';
import SpiderPreview from './spider-preview.vue';
interface SpiderParams {
appid: string;
}
interface SpiderContext {
userId: string;
conversationId: string;
files: unknown[];
inputs: Record<string, unknown>;
}
interface SpiderResult {
data: {
outputs: {
result: string;
};
};
}
interface ResultItem {
key: number;
role: 'ai' | 'user';
content: string;
footer?: any;
}
interface Props {
itemMessage?: ResultItem;
item?: SpiderItem;
title: string;
runSpider?: (
params: SpiderParams,
context: SpiderContext,
) => Promise<SpiderResult>;
}
defineOptions({
name: 'SpiderWorkView',
});
const props = withDefaults(defineProps<Props>(), {
itemMessage: () => null,
item: () => {
return null;
},
runSpider: () => async () => ({
data: {
outputs: {
result: '',
},
},
}),
});
// const styles = computed(() => {
// return {
// 'placeholder': {
// 'padding-top': '32px',
// 'text-align': 'left',
// 'flex': 1,
// },
// } as const
// })
// const placeholderNode = computed(() => h(
// Space,
// { direction: "vertical", size: 16, style: styles.value.placeholder },
// [
// h(
// Welcome,
// {
// variant: "borderless",
// icon: "https://mdn.alipayobjects.com/huamei_iwk9zp/afts/img/A*s5sNRo5LjfQAAAAAAAAAAAAADgCCAQ/fmt.webp",
// title: "Hello, I'm Ant Design X",
// description: "Base on Ant Design, AGI product interface solution, create a better intelligent vision~",
// extra: h(Space, {}, [h(Button, { icon: h(ShareAltOutlined) }), h(Button, { icon: h(EllipsisOutlined) })]),
// }
// ),
// ]
// ))
const resultItems = ref<ResultItem[]>([]);
// const items = computed<BubbleListProps['items']>(() => {
// if (resultItems.value.length === 0) {
// return [{ content: placeholderNode, variant: 'borderless' }]
// }
// return resultItems
// })
const [PreviewDrawer, previewDrawerApi] = useVbenDrawer({
// 连接抽离的组件
connectedComponent: SpiderPreview,
// placement: 'left',
});
function openPreviewDrawer(
placement: DrawerPlacement = 'right',
filename?: string,
) {
const fileData = filename.value;
previewDrawerApi.setState({ placement }).setData(fileData).open();
}
const selectedDateRange = ref<[Dayjs, Dayjs]>([
dayjs('2025-05-05'),
dayjs('2025-05-07'),
]);
// 判断是否是以 .docx 结尾的 URL
function isDocxURL(str: string): boolean {
return str.endsWith('.docx');
}
// 使用正则提取 /static/ 后面的文件名部分
function extractDocxFilename(url: string): null | string {
const match = url.match(/\/static\/([a-f0-9-]+\.docx)$/i);
if (match) {
return match[1]; // 返回类似9e1c421e-991c-411f-8176-6350a97e70f3.docx
}
return null;
}
const startFetching = async () => {
// 更新状态为“抓取中”
isFetching.value = true;
fetchStatus.value = 'fetching';
let publish_start_time = ''; // 默认值
let publish_end_time = ''; // 默认值
if (selectedDateRange.value && selectedDateRange.value.length === 2) {
publish_start_time =
dayjs(selectedDateRange.value[0]).format('YYYYMMDDhhmmss') || '';
publish_end_time =
dayjs(selectedDateRange.value[1]).format('YYYYMMDDhhmmss') || '';
}
try {
const res = await props.runSpider(
{
appid: props.item.id,
},
{
userId: '1562',
conversationId: '',
files: [],
inputs: {
publish_start_time,
publish_end_time,
},
},
);
if (res.data.outputs.result) {
// 保存抓取结果
fetchResult.value = res.data.outputs.result;
message.success('抓取成功');
const { result } = res.data.outputs;
const filename = ref('');
if (result && isDocxURL(result)) {
filename.value = extractDocxFilename(result);
}
// 保存抓取结果 url http://47.112.173.8:6802/static/66f3cfd95e364a239d8036390db658ae.docx
fetchResult.value = `/static/${filename.value}`;
resultItems.value.push({
key: resultItems.value.length + 1,
role: 'ai',
content: '文档已生成',
footer: h(Flex, null, [
h(
Button,
{
size: 'nomarl',
type: 'primary',
onClick: () => {
openPreviewDrawer('right', filename);
},
},
'文档预览',
),
h(
Button,
{
size: 'nomarl',
type: 'primary',
style: {
marginLeft: '10px',
},
onClick: () => {
// 创建隐藏的 <a> 标签用于触发下载
const link = document.createElement('a');
link.href = result; // 设置下载链接
link.download = filename; // 设置下载文件名
document.body.append(link); // 将 <a> 标签添加到页面中
link.click(); // 触发点击事件开始下载
link.remove(); // 下载完成后移除 <a> 标签
},
},
'文档下载',
),
]),
});
fetchStatus.value = 'completed';
} else {
fetchResult.value = '';
message.error('抓取无结果');
}
} catch (error) {
console.error(error);
}
// 模拟抓取完成
isFetching.value = false;
};
// 下载文件逻辑
const downloadFile = () => {
if (!fetchResult.value || !fetchResult.value.startsWith('http')) {
message.error('无效的文件链接');
return;
}
const fileUrl = fetchResult.value;
const fileName = decodeURIComponent(
fileUrl.slice(Math.max(0, fileUrl.lastIndexOf('/') + 1)),
);
const link = document.createElement('a');
link.href = fileUrl;
link.download = fileName;
link.click();
};
// 列表角色
const roles: BubbleListProps['roles'] = {
user: {
placement: 'end',
typing: false,
avatar: { icon: h(UserOutlined), style: { background: '#87d068' } },
},
ai: {
placement: 'start',
typing: false,
style: {
maxWidth: 600,
marginInlineEnd: 44,
},
styles: {
footer: {
width: '100%',
},
},
avatar: { icon: h(UserOutlined), style: { background: '#fde3cf' } },
},
file: {
placement: 'start',
avatar: { icon: h(UserOutlined), style: { visibility: 'hidden' } },
variant: 'borderless',
messageRender: (items: any) =>
h(
Flex,
{ vertical: true, gap: 'middle' },
items.map((item: any) =>
h(Attachments.FileCard, { key: item.uid, item }),
),
),
},
};
const isFetching = ref(false);
const fetchResult = ref('');
const fetchStatus = ref('');
// 监听 itemMessage 变化并更新 resultItems
watch(
() => props.itemMessage,
(newVal) => {
resultItems.value = [];
if (newVal && newVal.length > 0) {
newVal.forEach((msg) => {
// resultItems.value.push({
// key: resultItems.value.length + 1,
// role: msg.role, // 'user' or 'ai'
// content: msg.content,
// footer: msg.footer,
// });
if (msg.role === 'user') {
resultItems.value.push({
key: resultItems.value.length + 1,
role: msg.role, // 'user' or 'ai'
content: msg.content,
footer: msg.footer,
});
} else {
const filename = ref('');
if (msg.content && isDocxURL(msg.content)) {
filename.value = extractDocxFilename(msg.content);
}
resultItems.value.push({
key: resultItems.value.length + 1,
role: msg.role, // 'user' or 'ai'
content: '文档已生成',
footer: h(Flex, null, [
h(
Button,
{
size: 'nomarl',
type: 'primary',
onClick: () => {
openPreviewDrawer('right', filename);
},
},
'文档预览',
),
h(
Button,
{
size: 'nomarl',
type: 'primary',
style: {
marginLeft: '10px',
},
onClick: () => {
// 创建隐藏的 <a> 标签用于触发下载
const link = document.createElement('a');
link.href = msg.content; // 设置下载链接
link.download = filename; // 设置下载文件名
document.body.append(link); // 将 <a> 标签添加到页面中
link.click(); // 触发点击事件开始下载
link.remove(); // 下载完成后移除 <a> 标签
},
},
'文档下载',
),
]),
});
}
});
}
},
{ deep: true },
);
</script>
<template>
<!-- style="flex-direction: column"-->
<div class="flex h-full" style="width: 70%">
<PreviewDrawer />
<!-- <PreviewDrawer />-->
<Bubble.List
variant="shadow"
:typing="true"
:items="resultItems"
:roles="roles"
style="flex: 1"
/>
<Card class="w-full self-end" v-loading="isFetching">
<CardHeader class="py-4">
<CardTitle class="text-lg">{{ title }}</CardTitle>
</CardHeader>
<CardContent class="flex flex-wrap pt-0">
{{ item ? item.name : '请选择右侧爬虫' }}
</CardContent>
<CardFooter class="flex justify-end">
<RangePicker
class="mx-2"
v-model:value="selectedDateRange"
format="YYYY/MM/DD"
/>
<Button
:disabled="!item || selectedDateRange.length < 2"
@click="startFetching"
>
{{ isFetching ? '抓取中...' : '开始抓取' }}
</Button>
<Button
class="mx-2"
:disabled="fetchStatus !== 'completed'"
@click="downloadFile"
>
下载文件
</Button>
</CardFooter>
</Card>
</div>
</template>