Files
gofly-platform-services/zlt-web/react-web-next/src/pages/orders/TourismFile/index.tsx
T

290 lines
11 KiB
TypeScript
Raw Normal View History

import React, { useEffect, useRef, useState } from 'react';
import type { ActionType } from '@ant-design/pro-components';
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 { ordersApi } from '@/services/orders';
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: 1, color: '#1890ff' },
] as const;
const STATUS_OPTIONS = [
{ label: '启用', value: 0 },
{ label: '禁用', value: 1 },
] 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>();
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 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 };
};
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} />
</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 }}
/>
</GlassCard>
{/* 新建 */}
<ModalForm
title="新增资源"
open={createOpen}
onOpenChange={(v: boolean) => {
if (!v) {
setUploadPreviewUrl(undefined);
setUploadPath(undefined);
}
setCreateOpen(v);
}}
onFinish={async (values) => {
if (!uploadPath) {
message.warning('请先上传资源');
return false;
}
const hide = message.loading('保存中...');
try {
await ordersApi.saveOrUpdateTourismFile({ ...values, imageUrl: uploadPath, status: values.status ?? 0 });
message.success('新增成功');
actionRef.current?.reload();
return true;
} catch (e) {
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
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;
const hide = message.loading('保存中...');
try {
await ordersApi.saveOrUpdateTourismFile(payload);
message.success('修改成功');
actionRef.current?.reload();
return true;
} catch (e) {
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} />
<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;