feat: 优化景区素材

This commit is contained in:
2025-10-25 18:04:01 +08:00
parent 839f682ca8
commit 10a8e2a1ea
12 changed files with 515 additions and 552 deletions
@@ -1,24 +1,18 @@
import React, { useEffect, useRef, useState } from 'react';
import type { ActionType } from '@ant-design/pro-components';
import React, { useEffect, useRef, useState } from 'react';
import { ActionBar, GlassCard, SearchBarPlus } from '@/components/ui';
import {
ModalForm,
PageContainer,
ProForm,
ProFormSelect,
ProFormText,
ProTable,
} from '@ant-design/pro-components';
import { Button, Image, Popconfirm, Space, Tag, Upload, message, Form } from 'antd';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { PageContainer, ProFormSelect } from '@ant-design/pro-components';
import { Button, Image, Popconfirm, Space, Tag, message, Pagination } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { ordersApi } from '@/services/orders';
import TourismFileForm, { TourismFileItem } from './components/TourismFileForm';
// 资源类型枚举(用于卡片展示的颜色)
const TYPE_OPTIONS = [
{ label: '视频', value: 5, color: '#f5222d' },
{ label: '首页 Banner', value: 6, color: '#2f54eb' },
{ label: '展示封面', value: 4, color: '#52c41a' },
{ label: '入口引导', value: 3, color: '#722ed1' },
{ label: '服务小结展示', value: 2, color: '#13c2c2' },
{ label: '展示图片', value: 4, color: '#52c41a' },
{ label: '景区详情', value: 3, color: '#722ed1' },
{ label: '景区小图展示', value: 2, color: '#13c2c2' },
{ label: '活动', value: 1, color: '#1890ff' },
] as const;
@@ -28,218 +22,197 @@ const STATUS_OPTIONS = [
] as const;
const TourismFilePage: React.FC = () => {
const actionRef = useRef<ActionType>();
const [query, setQuery] = useState<Record<string, any>>({});
const [tourismOptions, setTourismOptions] = useState<Array<{ label: string; value: number }>>([]);
const [createOpen, setCreateOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
const [current, setCurrent] = useState<any>();
const [uploadPreviewUrl, setUploadPreviewUrl] = useState<string | undefined>();
const [uploadPath, setUploadPath] = useState<string | undefined>();
const [editUploadPreviewUrl, setEditUploadPreviewUrl] = useState<string | undefined>();
const [editUploadPath, setEditUploadPath] = useState<string | undefined>();
// 分组数据(按项目分组)与分页
const [groups, setGroups] = useState<Array<{ tourismId: number; tourismName?: string; files: any[] }>>([]);
const [loading, setLoading] = useState(false);
const fetchingRef = useRef(false);
const [pagination, setPagination] = useState<{ current: number; pageSize: number; total: number }>({ current: 1, pageSize: 10, total: 0 });
// 加载可选项目列表(用于筛选与表单下拉)
useEffect(() => {
(async () => {
try {
const res = await ordersApi.tourism({ page: 1, limit: 1000 });
const list: Array<{ id: number; tourismName: string }> = (res as any).data || res?.data || [];
setTourismOptions(list.map((it) => ({ label: (it as any).tourismName, value: (it as any).id })));
} catch (e) {
// 忽略错误以不影响页面
}
const res = await ordersApi.tourism({ page: 1, limit: 1000, tenantId: query?.tenantId, includeChildren: query?.includeChildren });
const list: Array<{ id: number; tourismName: string }> = (res as any)?.data || [];
setTourismOptions(list.map((it: any) => ({ label: it.tourismName, value: it.id })));
} catch {}
})();
}, []);
// 租户切换时刷新
}, [query?.tenantId, query?.includeChildren]);
const columns: any[] = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
{
title: '旅游项目',
dataIndex: 'tourismId',
render: (_: any, record: any) => tourismOptions.find((o) => o.value === record.tourismId)?.label || record.tourismName || '-',
},
{
title: '图片/预览',
dataIndex: 'imageUrl',
search: false,
width: 140,
render: (_: any, record: any) =>
record.type === 5 ? (
<video src={record.imageUrl} controls style={{ width: 120, height: 80, objectFit: 'cover' }} />
) : (
<Image src={record.imageUrl} width={120} height={80} style={{ objectFit: 'cover' }} />
),
},
{ title: '页面链接', dataIndex: 'linkUrl', ellipsis: true, copyable: true },
{ title: '描述', dataIndex: 'description', ellipsis: true },
{
title: '状态',
dataIndex: 'status',
width: 90,
render: (v: number) => <Tag color={v === 0 ? 'green' : 'default'}>{v === 0 ? '启用' : '禁用'}</Tag>,
},
{
title: '类型',
dataIndex: 'type',
width: 120,
render: (v: number) => {
const t = TYPE_OPTIONS.find((i) => i.value === Number(v));
return t ? <Tag color={t.color}>{t.label}</Tag> : '-';
},
},
{ title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', width: 180 },
{
title: '操作',
key: 'action',
width: 160,
render: (_: any, record: any) => (
<Space>
<a
onClick={() => {
setCurrent(record);
setEditOpen(true);
setEditUploadPreviewUrl(undefined);
setEditUploadPath(undefined);
}}
>
编辑
</a>
<Popconfirm
title={`确认删除资源[${record.id}]?`}
onConfirm={async () => {
const hide = message.loading('正在删除...');
try {
await ordersApi.deleteTourismFile(record.id);
message.success('删除成功');
actionRef.current?.reload();
} catch (e) {
message.error('删除失败');
} finally {
hide();
}
}}
>
<a style={{ color: '#1677ff' }}>删除</a>
</Popconfirm>
</Space>
),
},
];
const doUpload = async (file: File) => {
const formData = new FormData();
formData.append('file', file);
const resp = await fetch('/api-file/files-anon', { method: 'POST', body: formData });
const data = await resp.json();
if (!data || (!data.url && !data.path)) throw new Error('上传失败');
return data as { url: string; path: string };
// 加载查询结果(含分页)
const loadGroups = async (extra?: Record<string, any>) => {
const params = { ...(query || {}), ...(extra || {}), current: pagination.current, pageSize: pagination.pageSize };
if (fetchingRef.current) return; // 防抖去重
fetchingRef.current = true;
setLoading(true);
try {
const res = await ordersApi.tourismFilesGroupedByTenant(params as any);
setGroups(Array.isArray((res as any)?.data) ? (res as any).data : []);
setPagination((p) => ({ ...p, total: Number((res as any)?.total || 0) }));
} catch (e) {
setGroups([]);
setPagination((p) => ({ ...p, total: 0 }));
} finally {
fetchingRef.current = false;
setLoading(false);
}
};
// 首次与查询/分页变化时刷新
useEffect(() => {
loadGroups();
}, [query, pagination.current, pagination.pageSize]);
return (
<PageContainer header={{ title: '旅游资源管理' }}>
<SearchBarPlus defaultCollapsed split span={8} onTenantChanged={() => actionRef.current?.reload()} onFinish={async (values) => setQuery(values)}>
<ProFormText name="description" label="资源描述" placeholder="请输入关键字" />
<ProFormSelect name="tourismId" label="项目" placeholder="请选择" options={tourismOptions} showSearch />
<ProFormSelect name="type" label="资源类型" placeholder="请选择" options={TYPE_OPTIONS as any} />
<PageContainer header={{ title: '景区素材管理' }}>
<SearchBarPlus
defaultCollapsed
split
span={8 as any}
hideReset
onFinish={async (values) => {
// 查询提交后重置到第1页
setPagination((p) => ({ ...p, current: 1 }));
setQuery(values);
}}
>
<ProFormSelect name="status" label="状态" placeholder="请选择" options={STATUS_OPTIONS as any} />
</SearchBarPlus>
<ActionBar left={<Button size="middle" type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>新增</Button>} />
<GlassCard>
<ProTable<any>
rowKey="id"
headerTitle="资源列表"
actionRef={actionRef}
request={(p) => ordersApi.tourismFile({ ...p, ...query })}
columns={columns}
search={false}
pagination={{ showSizeChanger: true, showQuickJumper: true, defaultPageSize: 10 }}
/>
{loading ? (
<div style={{ padding: 24 }}>加载中...</div>
) : (
<div>
{groups && groups.length ? (
groups.map((g) => (
<div key={g.tourismId} style={{ marginBottom: 24 }}>
<h3 style={{ marginBottom: 12 }}>{g.tourismName || `项目#${g.tourismId}`}</h3>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, minmax(320px, 1fr))', gap: 16 }}>
{(g.files || []).map((record: any) => (
<div key={record.id} style={{ border: '1px solid #f0f0f0', borderRadius: 8, padding: 12 }}>
<div style={{ marginBottom: 8 }}>
{Number(record.type) === 5 ? (
<video src={record.imageUrl} controls style={{ width: '100%', height: 180, objectFit: 'cover', borderRadius: 4 }} />
) : (
<Image src={record.imageUrl} width={'100%'} height={180} style={{ objectFit: 'cover', borderRadius: 4 }} />
)}
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
<Tag color={Number(record.status) === 0 ? 'green' : 'default'}>{Number(record.status) === 0 ? '启用' : '禁用'}</Tag>
<Tag color={(TYPE_OPTIONS.find((i) => i.value === Number(record.type)) || ({} as any)).color || 'default'}>
{(TYPE_OPTIONS.find((i) => i.value === Number(record.type)) || ({} as any)).label || '未知类型'}
</Tag>
</div>
<div style={{ fontSize: 12, color: '#666', marginBottom: 8 }}>{record.description || '-'}</div>
{record.linkUrl ? (
<div style={{ fontSize: 12, color: '#999' }}>
链接:
<a href={record.linkUrl} target="_blank" rel="noreferrer">
{record.linkUrl}
</a>
</div>
) : null}
<div style={{ marginTop: 8 }}>
<Space>
<a
style={{ color: '#1677ff' }}
onClick={() => {
setCurrent(record);
setEditOpen(true);
}}
>
编辑
</a>
<Popconfirm
title={`确认删除资源[${record.id}]?`}
onConfirm={async () => {
const hide = message.loading('正在删除...');
try {
await ordersApi.deleteTourismFile(record.id);
message.success('删除成功');
loadGroups();
} catch (e) {
message.error('删除失败');
} finally {
hide();
}
}}
>
<a style={{ color: '#ff4d4f' }}>删除</a>
</Popconfirm>
</Space>
</div>
</div>
))}
</div>
</div>
))
) : (
<div style={{ padding: 24, color: '#999' }}>暂无数据</div>
)}
</div>
)}
{/* 分页 */}
<div style={{ marginTop: 16, textAlign: 'right' }}>
<span style={{ marginRight: 12, color: '#999' }}>共 {pagination.total} 条</span>
<Pagination
current={pagination.current}
pageSize={pagination.pageSize}
total={pagination.total}
showSizeChanger
showQuickJumper
onChange={(cur, size) => {
setPagination({ current: cur, pageSize: (size as number) || pagination.pageSize, total: pagination.total });
}}
/>
</div>
</GlassCard>
{/* 新建 */}
<ModalForm
<TourismFileForm
title="新增资源"
open={createOpen}
onOpenChange={(v: boolean) => {
if (!v) {
setUploadPreviewUrl(undefined);
setUploadPath(undefined);
}
setCreateOpen(v);
}}
onFinish={async (values) => {
if (!uploadPath) {
message.warning('请先上传资源');
return false;
}
tourismOptions={tourismOptions}
onOpenChange={setCreateOpen}
onFinish={async (values: TourismFileItem) => {
const hide = message.loading('保存中...');
try {
await ordersApi.saveOrUpdateTourismFile({ ...values, imageUrl: uploadPath, status: values.status ?? 0 });
await ordersApi.saveOrUpdateTourismFile({ ...values, status: values.status ?? 0 });
message.success('新增成功');
actionRef.current?.reload();
loadGroups();
return true;
} catch (e) {
message.error('保存失败');
message.error('新增失败');
return false;
} finally {
hide();
}
}}
>
<ProForm.Group>
<ProFormSelect rules={[{ required: true, message: '请选择项目' }]} width="md" name="tourismId" label="项目" options={tourismOptions} showSearch />
<ProFormSelect rules={[{ required: true, message: '请选择资源类型' }]} width="md" name="type" label="资源类型" options={TYPE_OPTIONS as any} />
<ProFormSelect width="md" name="status" label="状态" options={STATUS_OPTIONS as any} initialValue={0} />
<ProFormText width="md" name="linkUrl" label="页面链接" placeholder="可为空" />
<ProFormText rules={[{ required: true, message: '请输入资源描述' }]} width="md" name="description" label="资源描述" placeholder="请输入资源描述" />
</ProForm.Group>
<Upload
maxCount={1}
showUploadList={false}
customRequest={async ({ file, onSuccess, onError }) => {
try {
if (file instanceof File) {
const r = await doUpload(file as File);
setUploadPreviewUrl(r.url);
setUploadPath(r.path);
onSuccess?.('ok');
}
} catch (err) {
onError?.(err as any);
}
}}
accept="image/*,video/*"
>
<Button icon={<UploadOutlined />}>上传图片/视频</Button>
</Upload>
{uploadPreviewUrl && (
<div style={{ marginTop: 12 }}>
{(ProForm as any) && <Image src={uploadPreviewUrl} width={200} />}
</div>
)}
</ModalForm>
/>
{/* 编辑 */}
<ModalForm
<TourismFileForm
title="编辑资源"
open={editOpen}
initialValues={current}
onOpenChange={(v: boolean) => {
if (!v) {
setEditUploadPreviewUrl(undefined);
setEditUploadPath(undefined);
}
setEditOpen(v);
}}
onFinish={async (values) => {
const payload = { ...(current || {}), ...values } as any;
if (editUploadPath) payload.imageUrl = editUploadPath;
tourismOptions={tourismOptions}
onOpenChange={setEditOpen}
onFinish={async (values: TourismFileItem) => {
const hide = message.loading('保存中...');
try {
await ordersApi.saveOrUpdateTourismFile(payload);
await ordersApi.saveOrUpdateTourismFile({ ...(current || {}), ...values });
message.success('修改成功');
actionRef.current?.reload();
loadGroups();
return true;
} catch (e) {
message.error('修改失败');
@@ -248,42 +221,9 @@ const TourismFilePage: React.FC = () => {
hide();
}
}}
>
<ProForm.Group>
<ProFormSelect rules={[{ required: true, message: '请选择项目' }]} width="md" name="tourismId" label="项目" options={tourismOptions} showSearch />
<ProFormSelect rules={[{ required: true, message: '请选择资源类型' }]} width="md" name="type" label="资源类型" options={TYPE_OPTIONS as any} />
<ProFormSelect width="md" name="status" label="状态" options={STATUS_OPTIONS as any} />
<ProFormText width="md" name="linkUrl" label="页面链接" placeholder="可为空" />
<ProFormText rules={[{ required: true, message: '请输入资源描述' }]} width="md" name="description" label="资源描述" placeholder="请输入资源描述" />
</ProForm.Group>
<Upload
maxCount={1}
showUploadList={false}
customRequest={async ({ file, onSuccess, onError }) => {
try {
if (file instanceof File) {
const r = await doUpload(file as File);
setEditUploadPreviewUrl(r.url);
setEditUploadPath(r.path);
onSuccess?.('ok');
}
} catch (err) {
onError?.(err as any);
}
}}
accept="image/*,video/*"
>
<Button icon={<UploadOutlined />}>上传图片/视频</Button>
</Upload>
{(editUploadPreviewUrl || current?.imageUrl) && (
<div style={{ marginTop: 12 }}>
<Image src={editUploadPreviewUrl || current?.imageUrl} width={200} />
</div>
)}
</ModalForm>
/>
</PageContainer>
);
};
export default TourismFilePage;