feat(后台管理):,优化文件上传显示条件筛选等功能

This commit is contained in:
2025-03-30 15:49:18 +08:00
parent 57a8951954
commit f3f6ce9c49
16 changed files with 1237 additions and 613 deletions
@@ -3,114 +3,175 @@ import {
ProForm,
ProFormSelect,
ProFormText,
ProFormTextArea,
} from '@ant-design/pro-components';
import { Button, Upload } from 'antd';
import { Button, message, Upload } from 'antd';
import { Image as AntImage } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import React from 'react';
import { TYPE_OPTIONS } from '../index';
import type { RcFile } from 'antd/lib/upload';
import styles from '../index.less';
import React, { useState } from 'react';
import type { RcFile } from 'antd/es/upload';
import { importImage } from '@/services/system/api';
export type UpdateFormProps = {
onSubmit: (values: Partial<ORDERS.HomeCarousel>) => Promise<void>;
interface UpdateFormProps {
onSubmit: (values: any) => Promise<void>;
onVisibleChange: (visible: boolean) => void;
updateModalVisible: boolean;
values?: ORDERS.HomeCarousel;
onUpload: (fileUrl: string) => void;
};
onUpload: (url: string, path: string) => void;
imageUrl?: string;
}
const UpdateForm: React.FC<UpdateFormProps> = (props) => {
const { onSubmit, onVisibleChange, updateModalVisible, values, onUpload } = props;
interface UploadResponse {
id: string;
name: string;
url: string; // 添加 url 字段
isImg: boolean;
contentType: string;
size: number;
path: string;
source: string;
createTime: string;
updateTime: string;
}
// 导入处理函数
const handleImport = async (file: RcFile) => {
const hide = message.loading('正在上传');
const UpdateForm: React.FC<UpdateFormProps> = ({
onSubmit,
onVisibleChange,
updateModalVisible,
values,
onUpload,
imageUrl,
}) => {
const [uploading, setUploading] = useState(false);
// 修改文件上传处理逻辑
const handleUpload = async (file: RcFile) => {
setUploading(true);
const hide = message.loading('正在上传...');
try {
const formData = new FormData();
formData.append('file', file);
const result = await importImage(formData);
hide();
if (result && result.name) {
message.success('上传素材成功');
onUpload(result.name);
if (result.url && result.path) {
message.success('上传成功');
onUpload(result.url, result.path); // 传递两个值
return true;
}
message.error('上传失败:未获取到文件信息');
return false;
} catch (error) {
console.error('Upload error:', error);
hide();
message.error('上传素材失败');
message.error('上传失败:' + (error.message || '未知错误'));
return false;
} finally {
setUploading(false);
}
};
return (
<ModalForm
title="修改素材"
title="修改轮播图"
visible={updateModalVisible}
onVisibleChange={onVisibleChange}
modalProps={{ destroyOnClose: true }}
onFinish={async (formValues) => {
// 只提交已修改的字段
const changedValues: Partial<ORDERS.HomeCarousel> = {};
Object.keys(formValues).forEach(key => {
if (formValues[key] !== values?.[key]) {
changedValues[key] = formValues[key];
}
});
if (Object.keys(changedValues).length === 0) {
return true;
}
await onSubmit(changedValues);
modalProps={{
destroyOnClose: true,
confirmLoading: uploading,
}}
initialValues={values}
onFinish={async (formValues) => {
if (uploading) {
message.warning('请等待图片上传完成');
return false;
}
return onSubmit(formValues);
}}
>
<ProForm.Group>
<ProFormText
rules={[{ required: true, message: '标题不能为空' }]}
width="md"
name="title"
label="标题"
placeholder="请输入标题"
/>
<ProFormText
width="md"
name="redirectUrl"
label="链接url"
placeholder="输入url"
label="跳转链接"
rules={[{ type: 'url', message: '请输入正确的URL格式' }]}
/>
<ProFormSelect
width="md"
name="type"
label="类型"
placeholder="请选择类型"
options={TYPE_OPTIONS}
options={[
{ label: '首页轮播', value: 0 },
{ label: '活动', value: 1 },
{ label: '其他', value: 2 },
]}
rules={[{ required: true, message: '请选择类型' }]}
/>
<ProFormText
<ProFormSelect
width="md"
name="status"
label="状态"
options={[
{ label: '启用', value: '1' },
{ label: '禁用', value: '0' },
]}
rules={[{ required: true, message: '请选择状态' }]}
/>
<ProFormTextArea
width="md"
name="description"
label="素材描述"
placeholder="输入描述"
label="描述"
/>
{/* 添加图片上传组件 */}
<div style={{ marginBottom: 24 }}>
<div style={{ marginBottom: 8 }}>当前图片:</div>
<Image src={values?.imageUrl} width={100} style={{ marginBottom: 16 }} />
<Upload
maxCount={1}
action="/api-file/files-anon"
showUploadList={false}
beforeUpload={handleImport}
>
<div className={styles.button_view}>
<Button>
<UploadOutlined />
更新素材
</Button>
</div>
</Upload>
</div>
</ProForm.Group>
<div style={{ marginBottom: 16 }}>
<Upload
maxCount={1}
accept="image/*"
showUploadList={false}
disabled={uploading}
customRequest={async ({ file, onSuccess, onError }) => {
try {
const success = await handleUpload(file as RcFile);
if (success) {
onSuccess?.('ok');
} else {
onError?.(new Error('上传失败'));
}
} catch (error) {
onError?.(error);
}
}}
>
<Button
icon={<UploadOutlined />}
loading={uploading}
disabled={uploading}
>
{uploading ? '上传中...' : '更新图片'}
</Button>
</Upload>
</div>
{/* 显示图片预览 */}
<div style={{ marginTop: 16 }}>
{(imageUrl || values?.imageUrl) && (
<AntImage
src={imageUrl || values?.imageUrl}
width={200}
style={{ marginTop: 16 }}
/>
)}
</div>
</ModalForm>
);
};
@@ -1,6 +1,6 @@
import { deleteHomeCarousel, saveOrUpdateHomeCarousel, homeCarousel } from '@/services/orders/api';
import { importImage } from '@/services/system/api';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { PlusOutlined, UploadOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
ModalForm,
@@ -8,197 +8,187 @@ import {
ProForm,
ProFormSelect,
ProFormText,
ProFormTextArea,
ProTable,
QueryFilter,
} from '@ant-design/pro-components';
import { Typography, Popconfirm, Space, message, Image, Button, Tag, Upload } from 'antd';
import type { RcFile } from 'antd/lib/upload';
import React, { useRef, useState, useCallback } from 'react';
import { Typography, Popconfirm, Space, message, Button, Tag, Upload } from 'antd';
import { Image as AntImage } from 'antd';
import type { RcFile, UploadProps } from 'antd/es/upload';
import React, { useRef, useState } from 'react';
import UpdateForm from './components/UpdateForm';
import styles from './index.less';
const { Link } = Typography;
// 提取常量
export const TYPE_OPTIONS = [
// 状态常量
const STATUS_OPTIONS = [
{ label: '启用', value: '1' },
{ label: '禁用', value: '0' },
];
// 类型常量
const TYPE_OPTIONS = [
{ label: '首页轮播', value: 0 },
{ label: '活动', value: 1 },
{ label: '其他', value: 2 },
] as const;
];
// 类型颜色映射
const typeColorMap = {
0: { color: 'yellow', text: '首页轮播' },
1: { color: 'orange', text: '活动' },
2: { color: 'red', text: '其他' },
};
// 统一错误处理
const handleApiRequest = async (
apiCall: () => Promise<any>,
loadingMessage: string,
successMessage: string,
) => {
const hide = message.loading(loadingMessage);
try {
const result = await apiCall();
hide();
if (result.resp_code === 0) {
message.success(successMessage);
return true;
}
message.error(result.resp_msg);
return false;
} catch (error) {
hide();
message.error(`${successMessage}失败`);
return false;
}
};
// 处理函数优化
const handleAdd = async (fields: ORDERS.HomeCarousel) => {
return handleApiRequest(
() => saveOrUpdateHomeCarousel({ ...fields }),
'正在添加',
'添加成功'
);
};
const handleEdit = async (original: ORDERS.HomeCarousel, fields: Partial<ORDERS.HomeCarousel>) => {
return handleApiRequest(
() => saveOrUpdateHomeCarousel({
id: original.id,
...fields
}),
'正在更新',
'修改成功'
);
};
const handleDelete = async (carousel: ORDERS.HomeCarousel) => {
return handleApiRequest(
() => deleteHomeCarousel(carousel.id),
'正在删除',
'删除成功'
);
};
const handleImport = async (file: RcFile) => {
return handleApiRequest(
async () => {
const formData = new FormData();
formData.append('file', file);
return await importImage(formData);
},
'正在上传',
'上传素材成功'
);
};
// 渲染函数
const renderType = (type: {} | null | undefined) => {
const typeInfo = typeColorMap[type] || { color: 'gray', text: '未知状态' };
return <Tag color={typeInfo.color}>{typeInfo.text}</Tag>;
};
interface UploadResponse {
id: string;
name: string;
url: string;
path: string;
isImg: boolean;
contentType: string;
size: number;
source: string;
createTime: string;
updateTime: string;
}
const TableList: React.FC = () => {
const actionRef = useRef<ActionType>();
const [params, setParams] = useState<Record<string, string | number>>({});
const [createModalVisible, handleModalVisible] = useState<boolean>(false);
const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
const [searchParams, setSearchParams] = useState<Record<string, any>>({});
const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
const [currentRow, setCurrentRow] = useState<ORDERS.HomeCarousel>();
const [file, setFile] = useState<string>();
const [updateFile, setUpdateFile] = useState<string>();
const [createImageUrl, setCreateImageUrl] = useState<string>();
const [createImagePath, setCreateImagePath] = useState<string>();
const [updateImageUrl, setUpdateImageUrl] = useState<string>();
const [updateImagePath, setUpdateImagePath] = useState<string>();
const handleTableAction = useCallback(async (
action: 'add' | 'edit' | 'delete',
record?: ORDERS.HomeCarousel,
values?: Partial<ORDERS.HomeCarousel>
) => {
let success = false;
switch (action) {
case 'add':
success = await handleAdd({ ...values, imageUrl: file } as ORDERS.HomeCarousel);
success && handleModalVisible(false);
break;
case 'edit':
if (record) {
const updateData = {
...values,
...(updateFile ? { imageUrl: updateFile } : {})
};
success = await handleEdit(record, updateData);
if (success) {
handleUpdateModalVisible(false);
setCurrentRow(undefined);
setUpdateFile(undefined);
}
}
break;
case 'delete':
success = await handleDelete(record!);
break;
// 处理文件上传
const handleUpload = async (file: RcFile) => {
const hide = message.loading('正在上传...');
try {
const formData = new FormData();
formData.append('file', file);
const result = await importImage(formData);
hide();
if (result.url && result.path) {
message.success('上传成功');
return {
url: result.url,
path: result.path
};
}
message.error('上传失败:未获取到文件信息');
return false;
} catch (error) {
hide();
message.error('上传失败:' + (error.message || '未知错误'));
return false;
}
if (success && actionRef.current) {
actionRef.current.reload();
};
// 处理删除操作
const handleDelete = async (record: ORDERS.HomeCarousel) => {
const hide = message.loading('正在删除...');
try {
const result = await deleteHomeCarousel(record.id);
hide();
if (result.resp_code === 0) {
message.success('删除成功');
actionRef.current?.reload();
return true;
}
message.error(result.resp_msg);
return false;
} catch (error) {
hide();
message.error('删除失败');
return false;
}
}, [file, updateFile]);
};
const columns: ProColumns<ORDERS.HomeCarousel>[] = [
{
title: '序号',
dataIndex: 'index',
valueType: 'indexBorder',
width: 48,
},
{
title: '标题',
dataIndex: 'title',
ellipsis: true,
copyable: true,
},
{
title: '素材',
title: '素材预览',
dataIndex: 'imageUrl',
render: (imageUrl) => <Image src={imageUrl} width={100} />
width: 120,
render: (imageUrl) => (
<AntImage
src={imageUrl as string}
width={100}
placeholder={
<div style={{ background: '#f5f5f5', height: 100, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
加载中...
</div>
}
/>
),
},
{
title: '跳转链接',
dataIndex: 'redirectUrl',
ellipsis: true,
render: (url) => (
<Link href={url as string} target="_blank">{url}</Link>
),
},
{
title: '类型',
dataIndex: 'type',
render: renderType,
width: 100,
valueEnum: TYPE_OPTIONS.reduce((acc, curr) => ({
...acc,
[curr.value]: { text: curr.label },
}), {}),
},
{
title: '描述',
dataIndex: 'description',
ellipsis: true,
},
{
title: '状态',
dataIndex: 'status',
width: 80,
valueEnum: {
'1': { text: '启用', status: 'Success' },
'0': { text: '禁用', status: 'Error' },
},
},
{
title: '创建时间',
dataIndex: 'createTime',
valueType: 'dateTime',
width: 180,
},
{
title: '操作',
key: 'action',
render: (_, entity) => (
valueType: 'option',
width: 180,
render: (_, record) => (
<Space>
<Link
onClick={() => {
setCurrentRow(entity);
handleUpdateModalVisible(true);
setCurrentRow(record);
setUpdateModalVisible(true);
}}
>
修改
<EditOutlined /> 编辑
</Link>
<Popconfirm
title={`确认删除素材[${entity.id}]?`}
onConfirm={() => handleTableAction('delete', entity)}
title="确认删除该轮播图?"
description="删除后将无法恢复,请谨慎操作"
onConfirm={() => handleDelete(record)}
>
<Link>删除</Link>
<Link><DeleteOutlined /> 删除</Link>
</Popconfirm>
</Space>
),
@@ -206,50 +196,104 @@ const TableList: React.FC = () => {
];
return (
<PageContainer header={{ subTitle: '管理任务' }}>
<PageContainer>
<QueryFilter
defaultCollapsed
defaultCollapsed={false}
split
span={6}
className="query-filter"
onFinish={async (values) => setParams(values)}
onFinish={setSearchParams}
>
<ProFormText name="name" label="搜索" placeholder="输入关键字" />
<ProFormText
name="title"
label="标题"
placeholder="请输入标题关键字"
/>
<ProFormSelect
name="type"
label="类型"
placeholder="请选择类型"
options={TYPE_OPTIONS}
/>
<ProFormSelect
name="status"
label="状态"
placeholder="请选择状态"
options={STATUS_OPTIONS}
/>
</QueryFilter>
<ProTable<ORDERS.HomeCarousel>
rowKey="id"
headerTitle="素材列表"
request={homeCarousel}
headerTitle="轮播图列表"
actionRef={actionRef}
columns={columns}
request={homeCarousel}
params={searchParams}
search={false}
params={params}
pagination={{
defaultPageSize: 10,
showSizeChanger: true,
showQuickJumper: true,
}}
toolBarRender={() => [
<Button
type="primary"
key="add"
onClick={() => {
handleModalVisible(true);
}}
type="primary"
onClick={() => setCreateModalVisible(true)}
>
<PlusOutlined /> 添加
<PlusOutlined /> 新增轮播图
</Button>,
]}
/>
<ModalForm
title="添加素材"
title="新增轮播图"
visible={createModalVisible}
onVisibleChange={handleModalVisible}
modalProps={{ destroyOnClose: true }}
onFinish={(values) => handleTableAction('add', undefined, values)}
onVisibleChange={(visible) => {
setCreateModalVisible(visible);
if (!visible) {
setCreateImageUrl(undefined);
setCreateImagePath(undefined);
}
}}
modalProps={{
destroyOnClose: true,
maskClosable: false,
}}
onFinish={async (values) => {
if (!createImagePath) {
message.error('请上传轮播图片');
return false;
}
const hide = message.loading('正在添加...');
try {
const result = await saveOrUpdateHomeCarousel({
...values,
imageUrl: createImagePath,
});
hide();
if (result.resp_code === 0) {
message.success('添加成功');
setCreateModalVisible(false);
setCreateImageUrl(undefined);
setCreateImagePath(undefined);
actionRef.current?.reload();
return true;
}
message.error(result.resp_msg || '添加失败');
return false;
} catch (error) {
hide();
message.error('添加失败:' + (error.message || '未知错误'));
return false;
}
}}
>
<ProForm.Group>
<ProFormText
rules={[{ required: true, message: '标题不为空' }]}
rules={[{ required: true, message: '标题不能为空' }]}
width="md"
name="title"
label="标题"
@@ -258,54 +302,126 @@ const TableList: React.FC = () => {
<ProFormText
width="md"
name="redirectUrl"
label="链接url"
placeholder="输入url"
label="跳转链接"
placeholder="请输入跳转链接"
rules={[{ type: 'url', message: '请输入正确的URL格式' }]}
/>
<ProFormSelect
width="md"
name="type"
label="类型"
placeholder="请选择类型"
options={TYPE_OPTIONS}
options={[
{ label: '首页轮播', value: 0 },
{ label: '活动', value: 1 },
{ label: '其他', value: 2 },
]}
rules={[{ required: true, message: '请选择类型' }]}
/>
<ProFormText
<ProFormSelect
width="md"
name="status"
label="状态"
placeholder="请选择状态"
options={[
{ label: '启用', value: '1' },
{ label: '禁用', value: '0' },
]}
initialValue="1"
rules={[{ required: true, message: '请选择状态' }]}
/>
<ProFormTextArea
width="md"
name="description"
label="素材描述"
placeholder="输入描述"
label="描述"
placeholder="请输入描述信息"
/>
</ProForm.Group>
<div style={{ marginBottom: 16 }}>
<Upload
maxCount={1}
action="/api-file/files-anon"
accept="image/*"
showUploadList={false}
beforeUpload={async (file) => {
const result = await handleImport(file);
if (result && result.name) {
setFile(result.name);
customRequest={async ({ file, onSuccess, onError }) => {
try {
if (file instanceof File) {
const result = await handleUpload(file as RcFile);
if (result) {
setCreateImageUrl(result.url);
setCreateImagePath(result.path);
onSuccess?.('ok');
} else {
onError?.(new Error('上传失败'));
}
}
} catch (error) {
onError?.(error);
}
return false;
}}
>
<div className={styles.button_view}>
<Button>
<UploadOutlined />
上传素材
</Button>
</div>
<Button icon={<UploadOutlined />}>上传轮播图</Button>
</Upload>
</ProForm.Group>
</div>
{createImageUrl && (
<div style={{ marginTop: 16 }}>
<AntImage
src={createImageUrl}
width={200}
placeholder={
<div style={{ background: '#f5f5f5', height: 100, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
加载中...
</div>
}
/>
</div>
)}
</ModalForm>
<UpdateForm
onSubmit={(values) => handleTableAction('edit', currentRow, values)}
onSubmit={async (values) => {
const hide = message.loading('正在更新...');
try {
const result = await saveOrUpdateHomeCarousel({
id: currentRow?.id,
...values,
imageUrl: updateImagePath || currentRow?.imageUrl,
});
hide();
if (result.resp_code === 0) {
message.success('更新成功');
setUpdateModalVisible(false);
setCurrentRow(undefined);
setUpdateImageUrl(undefined);
setUpdateImagePath(undefined);
actionRef.current?.reload();
return true;
}
message.error(result.resp_msg || '更新失败');
return false;
} catch (error) {
hide();
message.error('更新失败:' + (error.message || '未知错误'));
return false;
}
}}
onVisibleChange={(visible) => {
handleUpdateModalVisible(visible);
setUpdateModalVisible(visible);
if (!visible) {
setUpdateFile(undefined);
setCurrentRow(undefined);
setUpdateImageUrl(undefined);
setUpdateImagePath(undefined);
}
}}
updateModalVisible={updateModalVisible}
values={currentRow}
onUpload={setUpdateFile}
onUpload={(url, path) => {
setUpdateImageUrl(url);
setUpdateImagePath(path);
}}
imageUrl={updateImageUrl}
/>
</PageContainer>
);
@@ -13,16 +13,51 @@ export const ORDER_STATUS = {
} as const;
export const STATUS_CONFIG = {
[ORDER_STATUS.UNPAID]: { color: 'yellow', text: '待支付' },
[ORDER_STATUS.PAID_QUEUING]: { color: 'orange', text: '已支付排队中' },
[ORDER_STATUS.CANCELLED]: { color: 'gray', text: '已取消' },
[ORDER_STATUS.COMPLETED]: { color: 'red', text: '设备执行完成' },
[ORDER_STATUS.SERVING]: { color: 'lightblue', text: '正在服务中' },
[ORDER_STATUS.UPLOADING]: { color: 'pink', text: '素材上传中' },
[ORDER_STATUS.UPLOAD_COMPLETED]: { color: 'green', text: '素材上传完成' },
[ORDER_STATUS.REFUNDING]: { color: 'darkgray', text: '退款中' },
[ORDER_STATUS.REFUNDED]: { color: 'cyan', text: '已退款' },
[ORDER_STATUS.REFUND_FAILED]: { color: 'purple', text: '退款失败' },
// 正常流程状态
[ORDER_STATUS.UNPAID]: {
color: 'gold', // 使用金色表示待支付,引起注意
text: '待支付'
},
[ORDER_STATUS.PAID_QUEUING]: {
color: '#1890ff', // 使用蓝色表示进行中的状态
text: '已支付排队中'
},
[ORDER_STATUS.SERVING]: {
color: '#13c2c2', // 使用青色表示服务进行中
text: '正在服务中'
},
[ORDER_STATUS.UPLOADING]: {
color: '#722ed1', // 使用紫色表示上传中
text: '素材上传中'
},
[ORDER_STATUS.UPLOAD_COMPLETED]: {
color: '#52c41a', // 使用绿色表示完成状态
text: '素材上传完成'
},
[ORDER_STATUS.COMPLETED]: {
color: '#389e0d', // 使用深绿色表示最终完成
text: '任务完成'
},
// 退款相关状态
[ORDER_STATUS.REFUNDING]: {
color: '#fa8c16', // 使用橙色表示退款处理中
text: '退款中'
},
[ORDER_STATUS.REFUNDED]: {
color: '#d48806', // 使用深橙色表示退款完成
text: '已退款'
},
[ORDER_STATUS.REFUND_FAILED]: {
color: '#f5222d', // 使用红色表示退款失败
text: '退款失败'
},
// 取消状态
[ORDER_STATUS.CANCELLED]: {
color: '#8c8c8c', // 使用灰色表示已取消
text: '已取消'
},
} as const;
export const STATUS_OPTIONS = Object.entries(STATUS_CONFIG).map(([value, config]) => ({
@@ -129,7 +129,18 @@ const TableList: React.FC = () => {
split
span={8}
className="query-filter"
onFinish={async (values) => setParams(values)}
onFinish={async (values) => {
// 处理查询参数
const params = {
orderNo: values.orderNo?.trim(), // 去除空格
orderStatus: values.orderStatus, // 状态
};
// 过滤掉空值
const validParams = Object.fromEntries(
Object.entries(params).filter(([_, value]) => value !== undefined && value !== '')
);
setParams(validParams);
}}
>
<ProFormText
name="orderNo"
@@ -148,7 +159,17 @@ const TableList: React.FC = () => {
<ProTable<ORDERS.Order>
rowKey="id"
headerTitle="订单列表"
request={order}
request={async (params) => {
// 处理表格请求参数
const { current, pageSize, orderNo, orderStatus } = params;
const result = await order({
current,
pageSize,
orderNo,
orderStatus: orderStatus ? Number(orderStatus) : undefined,
});
return result;
}}
actionRef={actionRef}
columns={columns}
search={false}
@@ -1,132 +1,184 @@
import { orderFiles,deleteFile } from '@/services/orders/api';
import { orderFiles, deleteFile } from '@/services/orders/api';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
PageContainer,
ProFormText,
ProFormDateRangePicker,
ProTable,
QueryFilter,
} from '@ant-design/pro-components';
import { Typography, message, Popconfirm, Image } from 'antd';
import { Typography, message, Popconfirm, Image, Space, Tag } from 'antd';
import React, { useRef, useState } from 'react';
const { Link } = Typography;
const handleDelete = async (deletefile: ORDERS.OrderFile) => {
const hide = message.loading('正在删除');
// 文件类型配置
const FILE_CONFIG = {
imageTypes: ['image/jpeg', 'image/png', 'image/gif'],
videoTypes: ['video/mp4', 'video/mpeg'],
documentTypes: ['application/pdf', 'application/msword'],
};
// 文件类型标签颜色映射
const TYPE_COLORS = {
'image/jpeg': 'blue',
'image/png': 'blue',
'image/gif': 'blue',
'video/mp4': 'green',
'video/mpeg': 'green',
'application/pdf': 'orange',
'application/msword': 'orange',
'default': 'default',
};
// 获取文件类型标签颜色
const getTypeColor = (fileType: string) => {
return TYPE_COLORS[fileType] || TYPE_COLORS.default;
};
// 处理文件删除
const handleDelete = async (file: ORDERS.OrderFile) => {
const hide = message.loading('正在删除文件...');
try {
const result = await deleteFile(deletefile.id);
const result = await deleteFile(file.id);
hide();
if (result.resp_code === 0) {
message.success('删除File成功');
message.success('删除文件成功');
return true;
} else {
message.error(result.resp_msg);
return false;
}
message.error(result.resp_msg);
return false;
} catch (error) {
hide();
message.error('删除File失败');
message.error('删除文件失败');
return false;
}
};
const imagePreviewTypes = ['image/jpeg', 'image/png', 'image/gif']; // 可预览的图片类型
const TableList: React.FC = () => {
const actionRef = useRef<ActionType>();
const [params, setParams] = useState<Record<string, string | number>>({ });
const [searchParams, setSearchParams] = useState<Record<string, any>>({});
const columns: ProColumns<ORDERS.OrderFile>[] = [
{
dataIndex: 'index',
valueType: 'indexBorder',
width: 48,
},
{
title: '订单文件ID',
dataIndex: 'id',
title: '订单编号',
dataIndex: 'orderNo',
copyable: true,
ellipsis: true,
},
{
title: '文件ID',
dataIndex: 'fileId',
},
{
title: '文件',
title: '文件预览',
dataIndex: 'viewUrl',
render: (viewUrl, entity) => (
<>
{imagePreviewTypes.includes(entity.fileType) ? (
<Image src={viewUrl} width={100} />
width: 200,
render: (viewUrl, record) => (
<Space direction="vertical">
{FILE_CONFIG.imageTypes.includes(record.fileType) ? (
<Image
src={viewUrl as string}
width={100}
placeholder={<div style={{ background: '#f5f5f5', height: 100 }}>加载中...</div>}
/>
) : (
<Link href={entity.viewUrl} target="_blank" rel="noopener noreferrer">
下载文件
</Link>
<Tag color={getTypeColor(record.fileType)}>
{record.fileType.split('/')[1].toUpperCase()}
</Tag>
)}
<Link
href={entity.viewUrl} // 假设 originalUrl 是原图的 URL
target="_blank"
rel="noopener noreferrer"
style={{ marginLeft: '8px', color: 'blue' }} // 添加样式以区分
>
预览原图
</Link>
</>
<Space>
<Link href={viewUrl as string} target="_blank" rel="noopener noreferrer">
下载
</Link>
<Link href={viewUrl as string} target="_blank" rel="noopener noreferrer">
预览
</Link>
</Space>
</Space>
),
},
{
title: '媒体类型',
title: '文件类型',
dataIndex: 'fileType',
width: 120,
render: (type) => (
<Tag color={getTypeColor(type as string)}>
{(type as string).split('/')[1].toUpperCase()}
</Tag>
),
},
{
title: '任务编号',
dataIndex: 'orderNo',
},
{
title: '创建时间',
dataIndex: 'createTime',
valueType: 'dateTime',
sorter: true,
width: 180,
},
{
title: '操作',
key: 'action',
render: (_, entity) => <Popconfirm
title={`确认删除文件[${entity.id}]?`}
onConfirm={async () => {
const success = await handleDelete(entity);
if (success) {
if (actionRef.current) {
valueType: 'option',
width: 120,
render: (_, record) => (
<Popconfirm
title="确认删除该文件?"
description="删除后将无法恢复,请谨慎操作"
onConfirm={async () => {
const success = await handleDelete(record);
if (success && actionRef.current) {
actionRef.current.reload();
}
}
}}
>
<Link>删除</Link>
</Popconfirm>,
}}
>
<Link>删除</Link>
</Popconfirm>
),
},
];
return (
<PageContainer header={{ subTitle: '管理任务' }}>
<PageContainer>
<QueryFilter
defaultCollapsed
defaultCollapsed={false}
split
span={6}
className="query-filter"
onFinish={async (values) => setParams(values)}
onFinish={setSearchParams}
>
<ProFormText name="name" label="搜索" placeholder="输入关键字" />
<ProFormText
name="orderNo"
label="订单编号"
placeholder="请输入订单编号"
/>
<ProFormDateRangePicker
name="createTime"
label="创建时间"
/>
</QueryFilter>
<ProTable<ORDERS.OrderFile>
rowKey="id"
headerTitle="任务列表"
request={orderFiles}
headerTitle="文件列表"
actionRef={actionRef}
columns={columns}
request={orderFiles}
params={searchParams}
search={false}
params={params}
pagination={{
defaultPageSize: 10,
showSizeChanger: true,
showQuickJumper: true,
}}
dateFormatter="string"
toolbar={{
settings: {
draggable: true,
checkable: true,
checkedReset: true,
extra: '表格列设置',
},
}}
/>
</PageContainer>
);
@@ -1,51 +1,30 @@
import { wayline } from '@/services/device/api';
import {
ModalForm,
ProForm,
ProFormSelect,
ProFormText,
} from '@ant-design/pro-components';
import { message } from 'antd';
import React, { useState, useEffect } from 'react';
import { TOURISM_OPTIONS, DEVICE_OPTIONS, STATUS_OPTIONS } from '../index';
import React from 'react';
import { STATUS_OPTIONS } from '../index';
export type UpdateFormProps = {
onSubmit: (values: Partial<ORDERS.Qrcode>) => Promise<void>;
interface UpdateFormProps {
onSubmit: (values: any) => Promise<void>;
onVisibleChange: (visible: boolean) => void;
updateModalVisible: boolean;
values?: ORDERS.Qrcode;
};
waylineOptions: any[]; // 从父组件接收航线选项
tourismOptions: any[]; // 从父组件接收景区选项
}
const UpdateForm: React.FC<UpdateFormProps> = (props) => {
const { onSubmit, onVisibleChange, updateModalVisible, values } = props;
const [waylineOptions, setWaylineOptions] = useState<any[]>([]);
// 获取航线列表
const fetchWaylineOptions = async () => {
try {
const result = await wayline({
current: 1,
pageSize: 100,
});
if (result?.data) {
const options = result.data.map((item: any) => ({
label: item.name,
value: item.waylineId,
wayline: item,
}));
setWaylineOptions(options);
}
} catch (error) {
message.error('获取航线列表失败');
}
};
// 在弹窗显示时获取航线列表
useEffect(() => {
if (updateModalVisible) {
fetchWaylineOptions();
}
}, [updateModalVisible]);
const {
onSubmit,
onVisibleChange,
updateModalVisible,
values,
waylineOptions,
tourismOptions,
} = props;
return (
<ModalForm
@@ -53,25 +32,8 @@ const UpdateForm: React.FC<UpdateFormProps> = (props) => {
visible={updateModalVisible}
onVisibleChange={onVisibleChange}
modalProps={{ destroyOnClose: true }}
initialValues={{
...values,
waylineId: values?.waylineId,
status: values?.status, // 确保状态值被正确初始化
}}
onFinish={async (formValues) => {
const changedValues: Partial<ORDERS.Qrcode> = {};
Object.keys(formValues).forEach(key => {
if (formValues[key] !== values?.[key]) {
changedValues[key] = formValues[key];
}
});
if (Object.keys(changedValues).length === 0) {
return true;
}
await onSubmit(changedValues);
}}
initialValues={values}
onFinish={onSubmit}
>
<ProForm.Group>
<ProFormSelect
@@ -82,12 +44,10 @@ const UpdateForm: React.FC<UpdateFormProps> = (props) => {
options={waylineOptions}
rules={[{ required: true, message: '请选择航线' }]}
fieldProps={{
loading: waylineOptions.length === 0,
loading: !waylineOptions.length,
showSearch: true,
onChange: (value, option: any) => {
// 可以在这里处理航线选择后的联动逻辑
console.log('选择的航线:', option);
}
filterOption: (input, option) =>
(option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
}}
/>
<ProFormSelect
@@ -95,23 +55,21 @@ const UpdateForm: React.FC<UpdateFormProps> = (props) => {
name="tourismId"
label="景区"
placeholder="请选择景区"
options={TOURISM_OPTIONS}
options={tourismOptions}
rules={[{ required: true, message: '请选择景区' }]}
fieldProps={{
loading: !tourismOptions.length,
showSearch: true,
filterOption: (input, option) =>
(option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
}}
/>
<ProFormText
width="md"
name="price"
label="景点打卡价格"
placeholder="输入价格(单位:分)"
rules={[{ required: true, message: '请输入价格' }]}
/>
<ProFormSelect
width="md"
name="deviceSn"
label="设备编号"
placeholder="请选择设备编号"
options={DEVICE_OPTIONS}
rules={[{ required: true, message: '请选择设备编号' }]}
rules={[{ required: true, message: '价格不为空' }]}
/>
<ProFormSelect
width="md"
@@ -1,4 +1,4 @@
import { deleteQrcode, qrcode, saveOrUpdateQrcode } from '@/services/orders/api';
import { deleteQrcode, qrcode, saveOrUpdateQrcode, tourism } from '@/services/orders/api';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
@@ -105,6 +105,7 @@ const TableList: React.FC = () => {
const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
const [currentRow, setCurrentRow] = useState<ORDERS.Qrcode>();
const [waylineOptions, setWaylineOptions] = useState<any[]>([]);
const [tourismOptions, setTourismOptions] = useState<any[]>([]);
const formRef = useRef();
const handleTableAction = useCallback(async (
@@ -154,16 +155,31 @@ const TableList: React.FC = () => {
}
};
useEffect(() => {
console.log('Modal visible changed:', updateModalVisible);
if (updateModalVisible) {
fetchWaylineOptions();
const fetchTourismList = useCallback(async () => {
try {
const result = await tourism({
limit: 100,
page: 1,
});
if (result.data) {
const options = result.data.map(item => ({
label: item.tourismName,
value: item.id,
}));
setTourismOptions(options);
}
} catch (error) {
message.error('获取景区列表失败');
}
}, [updateModalVisible]);
}, []);
useEffect(() => {
console.log('Current wayline options:', waylineOptions);
}, [waylineOptions]);
if (updateModalVisible || createModalVisible) {
fetchTourismList();
fetchWaylineOptions();
}
}, [updateModalVisible, createModalVisible, fetchTourismList]);
const columns: ProColumns<ORDERS.Qrcode>[] = [
{
@@ -272,7 +288,13 @@ const TableList: React.FC = () => {
<ModalForm
title="添加二维码"
visible={createModalVisible}
onVisibleChange={handleModalVisible}
onVisibleChange={(visible) => {
handleModalVisible(visible);
if (!visible) {
setWaylineOptions([]);
setTourismOptions([]);
}
}}
modalProps={{ destroyOnClose: true }}
onFinish={async (values) => handleTableAction('add', undefined, values)}
>
@@ -284,14 +306,26 @@ const TableList: React.FC = () => {
placeholder="请选择航线"
options={waylineOptions}
rules={[{ required: true, message: '请选择航线' }]}
fieldProps={{
loading: !waylineOptions.length,
showSearch: true,
filterOption: (input, option) =>
(option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
}}
/>
<ProFormSelect
width="md"
name="tourismId"
label="景区"
placeholder="请选择景区"
options={TOURISM_OPTIONS}
rules={[{ required: true, message: '景区不为空' }]}
options={tourismOptions}
rules={[{ required: true, message: '请选择景区' }]}
fieldProps={{
loading: !tourismOptions.length,
showSearch: true,
filterOption: (input, option) =>
(option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
}}
/>
<ProFormText
width="md"
@@ -329,10 +363,14 @@ const TableList: React.FC = () => {
handleUpdateModalVisible(visible);
if (!visible) {
setCurrentRow(undefined);
setWaylineOptions([]);
setTourismOptions([]);
}
}}
updateModalVisible={updateModalVisible}
values={currentRow}
waylineOptions={waylineOptions}
tourismOptions={tourismOptions}
/>
</PageContainer>
);
@@ -2,18 +2,34 @@ import {
ModalForm,
ProForm,
ProFormText,
ProFormSelect,
} from '@ant-design/pro-components';
import React from 'react';
export type UpdateFormProps = {
onSubmit: (values: Partial<ORDERS.Tourism>) => Promise<void>;
// 状态选项
const STATUS_OPTIONS = [
{ label: '启用', value: '1' },
{ label: '未启用', value: '0' },
];
interface UpdateFormProps {
onSubmit: (values: any) => Promise<void>;
onVisibleChange: (visible: boolean) => void;
updateModalVisible: boolean;
values?: ORDERS.Tourism;
};
}
const UpdateForm: React.FC<UpdateFormProps> = (props) => {
const { onSubmit, onVisibleChange, updateModalVisible, values } = props;
const UpdateForm: React.FC<UpdateFormProps> = ({
onSubmit,
onVisibleChange,
updateModalVisible,
values,
}) => {
// 表单字段验证规则
const formRules = {
required: { required: true, message: '此项为必填项' },
phone: { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
};
return (
<ModalForm
@@ -21,41 +37,38 @@ const UpdateForm: React.FC<UpdateFormProps> = (props) => {
visible={updateModalVisible}
onVisibleChange={onVisibleChange}
modalProps={{ destroyOnClose: true }}
onFinish={async (formValues) => {
// 只提交已修改的字段
const changedValues: Partial<ORDERS.Tourism> = {};
Object.keys(formValues).forEach(key => {
if (formValues[key] !== values?.[key]) {
changedValues[key] = formValues[key];
}
});
if (Object.keys(changedValues).length === 0) {
return true; // 如果没有修改任何字段,直接关闭
}
await onSubmit(changedValues);
}}
initialValues={values}
onFinish={onSubmit}
>
<ProForm.Group>
<ProFormText
width="md"
name="tourismName"
label="名称"
placeholder="输入名称"
width="md"
rules={[formRules.required]}
placeholder="请输入景区名称"
/>
<ProFormText
width="md"
name="tourismAddress"
label="地址"
placeholder="输入地址"
width="md"
rules={[formRules.required]}
placeholder="请输入景区地址"
/>
<ProFormText
width="md"
name="tourismPhone"
label="手机号"
placeholder="输入手机号"
label="联系电话"
width="md"
rules={[formRules.required, formRules.phone]}
placeholder="请输入联系电话"
/>
<ProFormSelect
name="status"
label="状态"
width="md"
options={STATUS_OPTIONS}
rules={[formRules.required]}
placeholder="请选择状态"
/>
</ProForm.Group>
</ModalForm>
@@ -8,246 +8,256 @@ import {
ProForm,
ProFormText,
ProTable,
QueryFilter,
ProFormSelect,
} from '@ant-design/pro-components';
import { Typography, message, Popconfirm, Button, Space } from 'antd';
import React, { useRef, useState, useCallback } from 'react';
const { Link } = Typography;
// 状态常量
const STATUS_OPTIONS = [
{ label: '启用', value: '1' },
{ label: '未启用', value: '0' },
];
// 统一的消息处理
const showMessage = {
success: (msg: string) => message.success(msg),
error: (msg: string) => message.error(msg),
loading: (msg: string) => message.loading(msg),
};
// API 请求处理器
const handleApiRequest = async (
apiCall: () => Promise<any>,
loadingMessage: string,
successMessage: string,
) => {
const hide = message.loading(loadingMessage);
): Promise<boolean> => {
const hide = showMessage.loading(loadingMessage);
try {
const result = await apiCall();
hide();
if (result.resp_code === 0) {
message.success(successMessage);
showMessage.success(successMessage);
return true;
}
message.error(result.resp_msg);
showMessage.error(result.resp_msg);
return false;
} catch (error) {
hide();
message.error(`${successMessage}失败`);
showMessage.error(`${successMessage}失败: ${error.message}`);
return false;
}
};
const handleAdd = async (fields: ORDERS.Tourism) => {
return handleApiRequest(
() => saveOrUpdateTourism({ ...fields }),
'正在添加',
'添加景区成功'
);
};
const handleEdit = async (original: ORDERS.Tourism, fields: Partial<ORDERS.Tourism>) => {
return handleApiRequest(
() => saveOrUpdateTourism({
id: original.id, // 保留原始ID
...fields // 只包含修改的字段
}),
'正在更新',
'修改景区成功'
);
};
const handleDelete = async (tourism: ORDERS.Tourism) => {
return handleApiRequest(
() => deleteTourism(tourism.id),
'正在删除',
'删除景区成功'
);
};
const TableList: React.FC = () => {
// 1. 先定义所有的 hooks
const actionRef = useRef<ActionType>();
const [params, setParams] = useState<Record<string, string | number>>({});
const [createModalVisible, handleModalVisible] = useState<boolean>(false);
const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
const [searchParams, setSearchParams] = useState<Record<string, string | number>>({});
const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
const [currentRow, setCurrentRow] = useState<ORDERS.Tourism>();
// 2. 然后定义 handleTableAction
// 表格操作处理
const handleTableAction = useCallback(async (
action: 'add' | 'edit' | 'delete',
record?: ORDERS.Tourism,
values?: Partial<ORDERS.Tourism>
) => {
let success = false;
switch (action) {
case 'add':
success = await handleAdd(values as ORDERS.Tourism);
success && handleModalVisible(false);
break;
case 'edit':
if (record) {
success = await handleEdit(record, values || {});
if (success) {
handleUpdateModalVisible(false);
setCurrentRow(undefined);
}
const actions = {
add: async () => {
const success = await handleApiRequest(
() => saveOrUpdateTourism(values as ORDERS.Tourism),
'正在添加景区...',
'添加景区成功'
);
success && setCreateModalVisible(false);
return success;
},
edit: async () => {
if (!record) return false;
const success = await handleApiRequest(
() => saveOrUpdateTourism({ id: record.id, ...values }),
'正在更新景区...',
'修改景区成功'
);
if (success) {
setUpdateModalVisible(false);
setCurrentRow(undefined);
}
break;
case 'delete':
success = await handleDelete(record!);
break;
}
return success;
},
delete: async () => {
if (!record) return false;
return handleApiRequest(
() => deleteTourism(record.id),
'正在删除景区...',
'删除景区成功'
);
},
};
const success = await actions[action]();
if (success && actionRef.current) {
actionRef.current.reload();
}
}, []); // 添加依赖数组
}, []);
// 表格列定义
const columns: ProColumns<ORDERS.Tourism>[] = [
{
dataIndex: 'index',
valueType: 'indexBorder',
width: 48,
},
{
title: 'ID',
dataIndex: 'id',
hideInSearch: true,
width: 80,
},
{
title: '编号',
dataIndex: 'tourismNo',
copyable: true,
},
{
title: '名称',
dataIndex: 'tourismName',
ellipsis: true,
},
{
title: '地址',
dataIndex: 'tourismAddress',
ellipsis: true,
},
{
title: '联系电话',
dataIndex: 'tourismPhone',
copyable: true,
},
{
title: '状态',
dataIndex: 'status',
valueType: 'select',
valueEnum: {
'1': { text: '启用', status: 'Success' },
'0': { text: '未启用', status: 'Error' },
},
},
{
title: '创建时间',
dataIndex: 'createTime',
valueType: 'dateTime',
hideInSearch: true,
},
{
title: '操作',
key: 'action',
render: (_, entity) =>
<Space>
<Link
onClick={() => {
setCurrentRow(entity);
handleUpdateModalVisible(true);
}}
>
修改
</Link>
<Popconfirm
title={`确认删除景区[${entity.tourismName}]?`}
onConfirm={() => handleTableAction('delete', entity)}
>
<Link>删除</Link>
</Popconfirm>
</Space>
valueType: 'option',
width: 180,
render: (_, record) => (
<Space>
<Link
onClick={() => {
setCurrentRow(record);
setUpdateModalVisible(true);
}}
>
修改
</Link>
<Popconfirm
title={`确认删除景区[${record.tourismName}]?`}
onConfirm={() => handleTableAction('delete', record)}
>
<Link>删除</Link>
</Popconfirm>
</Space>
),
},
];
// 表单字段验证规则
const formRules = {
required: { required: true, message: '此项为必填项' },
phone: { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
};
return (
<PageContainer header={{ subTitle: '管理景区' }}>
<QueryFilter
defaultCollapsed
split
span={6}
className="query-filter"
onFinish={async (values) => setParams(values)}
>
<ProFormText name="name" label="搜索" placeholder="输入关键字" />
</QueryFilter>
<PageContainer>
<ProTable<ORDERS.Tourism>
rowKey="id"
headerTitle="景区列表"
request={tourism}
actionRef={actionRef}
columns={columns}
search={false}
params={params}
request={tourism}
params={searchParams}
search={{
labelWidth: 'auto',
}}
pagination={{
defaultPageSize: 10,
showSizeChanger: true,
showQuickJumper: true,
}}
toolBarRender={() => [
<>
<Button
type="primary"
onClick={() => {
handleModalVisible(true);
}}
>
<PlusOutlined /> 添加
</Button>
</>,
<Button
key="add"
type="primary"
onClick={() => setCreateModalVisible(true)}
>
<PlusOutlined /> 新增景区
</Button>,
]}
/>
{/* 新增表单 */}
<ModalForm
title="添加景区"
title="新增景区"
visible={createModalVisible}
onVisibleChange={handleModalVisible}
onVisibleChange={setCreateModalVisible}
modalProps={{ destroyOnClose: true }}
onFinish={(values) => handleTableAction('add', undefined, values)}
>
<ProForm.Group>
<ProFormText
rules={[
{
required: true,
message: '名称不为空',
},
]}
width="md"
name="tourismName"
label="名称"
placeholder="输入名称"
/>
<ProFormText
rules={[
{
required: true,
message: '地址不为空',
},
]}
width="md"
name="tourismAddress"
label="地址"
placeholder="输入地址"
/>
<ProFormText
rules={[
{
required: true,
message: '手机号不为空',
},
]}
width="md"
name="tourismPhone"
label="手机号"
placeholder="输入手机号"
/>
<ProFormText
name="tourismName"
label="名称"
width="md"
rules={[formRules.required]}
placeholder="请输入景区名称"
/>
<ProFormText
name="tourismAddress"
label="地址"
width="md"
rules={[formRules.required]}
placeholder="请输入景区地址"
/>
<ProFormText
name="tourismPhone"
label="联系电话"
width="md"
rules={[formRules.required, formRules.phone]}
placeholder="请输入联系电话"
/>
<ProFormSelect
name="status"
label="状态"
width="md"
options={STATUS_OPTIONS}
rules={[formRules.required]}
initialValue="1"
/>
</ProForm.Group>
</ModalForm>
{/* 修改表单 */}
<UpdateForm
onSubmit={(values) => handleTableAction('edit', currentRow, values)}
onVisibleChange={handleUpdateModalVisible}
onVisibleChange={setUpdateModalVisible}
updateModalVisible={updateModalVisible}
values={currentRow}
/>
</PageContainer>
);
};
@@ -0,0 +1,159 @@
import { ModalForm, ProForm, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import { Button, Upload, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import React, { useState } from 'react';
import { TYPE_OPTIONS } from '../constants';
import { importImage, saveOrUpdateTourismFile } from '@/services/orders/api';
import type { RcFile } from 'antd/lib/upload';
import styles from '../index.less';
interface CreateFormProps {
visible: boolean;
onVisibleChange: (visible: boolean) => void;
tourismOptions: { label: string; value: number; }[];
onSuccess: () => void;
}
const CreateForm: React.FC<CreateFormProps> = ({
visible,
onVisibleChange,
tourismOptions,
onSuccess,
}) => {
const [imageUrl, setImageUrl] = useState<string>();
const handleUpload = async (file: RcFile) => {
const hide = message.loading('正在上传');
try {
const formData = new FormData();
formData.append('file', file);
const result = await importImage(formData);
hide();
if (result.name) {
setImageUrl(result.name);
message.success('上传成功');
}
} catch (error) {
hide();
message.error('上传失败');
}
return false;
};
const handleSubmit = async (values: Record<string, any>) => {
if (!imageUrl) {
message.error('请上传素材图片');
return false;
}
const hide = message.loading('正在提交');
try {
const result = await saveOrUpdateTourismFile({
...values,
imageUrl,
status: 0, // 默认启用
});
hide();
if (result.resp_code === 0) {
message.success('创建成功');
onSuccess();
return true;
}
message.error(result.resp_msg);
return false;
} catch (error) {
hide();
message.error('创建失败');
return false;
}
};
return (
<ModalForm
title="新增素材"
visible={visible}
onVisibleChange={(visible) => {
if (!visible) {
setImageUrl(undefined);
}
onVisibleChange(visible);
}}
modalProps={{
destroyOnClose: true,
maskClosable: false,
}}
onFinish={handleSubmit}
>
<ProForm.Group>
<ProFormSelect
rules={[{ required: true, message: '请选择景区' }]}
width="md"
name="tourismId"
label="景区"
placeholder="请选择景区"
options={tourismOptions}
showSearch
fieldProps={{
loading: !tourismOptions.length,
filterOption: (input, option) =>
(option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
}}
/>
<ProFormSelect
rules={[{ required: true, message: '请选择素材类型' }]}
width="md"
name="type"
label="素材类型"
placeholder="请选择素材类型"
options={TYPE_OPTIONS}
/>
<ProFormText
width="md"
name="linkUrl"
label="素材链接"
placeholder="请输入素材链接"
/>
<ProFormText
width="md"
name="description"
label="素材描述"
placeholder="请输入素材描述"
rules={[{ required: true, message: '请输入素材描述' }]}
/>
<div style={{ width: '100%', marginBottom: 24 }}>
<div style={{ marginBottom: 8 }}>
<span style={{ color: '#666' }}>素材图片:</span>
<span style={{ color: '#ff4d4f' }}>*</span>
</div>
{imageUrl && (
<div style={{ marginBottom: 8 }}>
<img
src={imageUrl}
alt="preview"
style={{
maxWidth: '200px',
maxHeight: '200px',
objectFit: 'contain'
}}
/>
</div>
)}
<Upload
maxCount={1}
showUploadList={false}
beforeUpload={handleUpload}
accept="image/*"
>
<Button icon={<UploadOutlined />}>
{imageUrl ? '重新上传' : '上传素材'}
</Button>
</Upload>
</div>
</ProForm.Group>
</ModalForm>
);
};
export default CreateForm;
@@ -0,0 +1,41 @@
import { ProFormSelect, ProFormText, QueryFilter } from '@ant-design/pro-components';
import { TYPE_OPTIONS } from '../constants';
import React from 'react';
interface SearchFormProps {
tourismOptions: { label: string; value: number; }[];
onSearch: (values: Record<string, any>) => void;
}
const SearchForm: React.FC<SearchFormProps> = ({ tourismOptions, onSearch }) => {
return (
<QueryFilter
defaultCollapsed={false}
split
span={8}
className="query-filter"
onFinish={onSearch}
>
<ProFormText
name="description"
label="素材描述"
placeholder="请输入素材描述"
/>
<ProFormSelect
name="tourismId"
label="景区"
placeholder="请选择景区"
options={tourismOptions}
showSearch
/>
<ProFormSelect
name="type"
label="素材类型"
placeholder="请选择素材类型"
options={TYPE_OPTIONS}
/>
</QueryFilter>
);
};
export default SearchForm;
@@ -8,16 +8,16 @@ import {
} from '@ant-design/pro-components';
import { Button, Upload, Image, message } from 'antd';
import type { RcFile } from 'antd/lib/upload';
import React, { useState } from 'react';
import React, { useState, useEffect, useCallback } from 'react';
import { TOURISM_OPTIONS, TYPE_OPTIONS } from '../constants';
import styles from '../index.less';
import { tourism } from '@/services/orders/api';
interface UpdateFormProps {
onSubmit: (values: Partial<ORDERS.TourismFile>) => Promise<void>;
onVisibleChange: (visible: boolean) => void;
updateModalVisible: boolean;
values?: ORDERS.TourismFile;
tourismOptions: { label: string; value: number; }[];
}
const UpdateForm: React.FC<UpdateFormProps> = ({
@@ -25,9 +25,9 @@ const UpdateForm: React.FC<UpdateFormProps> = ({
onVisibleChange,
updateModalVisible,
values,
tourismOptions,
}) => {
const [imageUrl, setImageUrl] = useState<string>(values?.imageUrl || '');
const [tourismOptions, setTourismOptions] = useState<any[]>([]);
const handleUpload = async (file: RcFile) => {
const hide = message.loading('正在上传');
@@ -47,6 +47,33 @@ const UpdateForm: React.FC<UpdateFormProps> = ({
return false;
};
// 获取景区列表
const fetchTourismList = useCallback(async () => {
try {
const result = await tourism({
limit: 100,
page: 1,
});
if (result.data) {
const options = result.data.map(item => ({
label: item.tourismName,
value: item.id,
}));
setTourismOptions(options);
}
} catch (error) {
message.error('获取景区列表失败');
}
}, []);
// 在组件挂载和弹窗打开时获取数据
useEffect(() => {
if (updateModalVisible) {
fetchTourismList();
}
}, [updateModalVisible, fetchTourismList]);
return (
<ModalForm
title="修改素材"
@@ -64,7 +91,7 @@ const UpdateForm: React.FC<UpdateFormProps> = ({
>
<ProForm.Group>
<ProFormSelect
rules={[{ required: true, message: '景区不能为空' }]}
rules={[{ required: true, message: '请选择景区' }]}
width="md"
name="tourismId"
label="景区"
@@ -73,10 +100,12 @@ const UpdateForm: React.FC<UpdateFormProps> = ({
showSearch
fieldProps={{
loading: !tourismOptions.length,
filterOption: (input, option) =>
(option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
}}
/>
<ProFormSelect
rules={[{ required: true, message: '素材类型不能为空' }]}
rules={[{ required: true, message: '素材类型不为空' }]}
width="md"
name="type"
label="素材类型"
@@ -1 +1,20 @@
// 将常量配置抽离到单独文件
export const TYPE_OPTIONS = [
{ label: '展示大图', value: 4 },
{ label: '拍照引导图', value: 3 },
{ label: '拍照角度展示图', value: 2 },
{ label: '活动', value: 1 },
] as const;
export const STATUS_CONFIG = {
0: { color: '#52c41a', text: '启用' }, // 使用更友好的绿色
1: { color: '#ff4d4f', text: '未启用' }, // 使用更友好的红色
} as const;
export const TYPE_CONFIG = {
0: { color: '#faad14', text: '待审核' }, // 黄色
1: { color: '#1890ff', text: '活动' }, // 蓝色
2: { color: '#13c2c2', text: '拍照角度' }, // 青色
3: { color: '#722ed1', text: '引导' }, // 紫色
4: { color: '#52c41a', text: '大图' }, // 绿色
} as const;
@@ -14,7 +14,10 @@ import {
import { Typography, Popconfirm, Space, message, Image, Button, Tag, Upload } from 'antd';
import type { RcFile } from 'antd/lib/upload';
import React, { useRef, useState, useCallback, useEffect } from 'react';
import { STATUS_CONFIG, TYPE_CONFIG } from './constants';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import SearchForm from './components/SearchForm';
import styles from './index.less';
const { Link } = Typography;
@@ -118,32 +121,40 @@ const renderType = (type: {} | null | undefined) => {
const TableList: React.FC = () => {
const actionRef = useRef<ActionType>();
const [params, setParams] = useState<Record<string, string | number>>({});
const [createModalVisible, handleModalVisible] = useState<boolean>(false);
const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
const [currentRow, setCurrentRow] = useState<ORDERS.TourismFile>();
const [file, setFile] = useState<string>();
const [tourismOptions, setTourismOptions] = useState<{ label: string; value: number; }[]>([]);
const [tourismOptions, setTourismOptions] = useState<{ label: string; value: number; info?: any }[]>([]);
// 获取景区列表
const fetchTourismList = useCallback(async () => {
try {
console.log('开始获取景区列表...');
const result = await tourism({
pageSize: 100,
current: 1,
limit: 100,
page: 1,
});
if (result.resp_code === 0 && result.data) {
const options = result.data.records?.map(item => ({
label: item.name,
console.log('tourism接口返回数据:', result);
if (result.data) {
const options = result.data.map(item => ({
label: item.tourismName,
value: item.id,
})) || [];
}));
console.log('转换后的选项数据:', options);
setTourismOptions(options);
}
} catch (error) {
console.error('获取景区列表失败:', error);
message.error('获取景区列表失败');
}
}, []);
// 在组件挂载时获取景区列表
// 在组件挂载时获取数据
useEffect(() => {
fetchTourismList();
}, [fetchTourismList]);
@@ -157,13 +168,13 @@ const TableList: React.FC = () => {
switch (action) {
case 'add':
success = await handleAdd({ ...values, imageUrl: file } as ORDERS.TourismFile);
success && handleModalVisible(false);
success && setCreateModalVisible(false);
break;
case 'edit':
if (record) {
success = await handleEdit(record, values || {});
if (success) {
handleUpdateModalVisible(false);
setUpdateModalVisible(false);
setCurrentRow(undefined);
}
}
@@ -179,69 +190,85 @@ const TableList: React.FC = () => {
const columns: ProColumns<ORDERS.TourismFile>[] = [
{
title: '序号',
dataIndex: 'index',
valueType: 'indexBorder',
width: 48,
},
{
title: '景区名称',
dataIndex: 'tourismId',
dataIndex: 'tourismName',
ellipsis: true,
},
{
title: '素材',
title: '素材预览',
dataIndex: 'imageUrl',
render: (imageUrl) => <Image src={imageUrl} width={100} />
width: 120,
render: (imageUrl) => (
<Image
src={imageUrl as string}
width={80}
height={80}
style={{ objectFit: 'cover' }}
/>
),
},
{
title: '页面链接',
dataIndex: 'linkUrl',
ellipsis: true,
copyable: true,
},
{
title: '描述',
dataIndex: 'description',
ellipsis: true,
},
{
title: '状态',
dataIndex: 'status',
render: (status) => renderStatus(status),
width: 100,
render: renderStatus,
},
{
title: "类型",
dataIndex: 'type',
render: (type) => renderType(type)
width: 120,
render: renderType,
},
{
title: '创建时间',
dataIndex: 'createTime',
valueType: 'dateTime',
width: 180,
},
{
title: '操作',
key: 'action',
render: (_, entity) =>
<Space>
<Link
onClick={() => {
setCurrentRow(entity);
handleUpdateModalVisible(true);
}}
>
修改
</Link>
<Popconfirm
title={`确认删除素材[${entity.id}]?`}
onConfirm={async () => {
const success = await handleTableAction('delete', entity);
if (success) {
if (actionRef.current) {
actionRef.current.reload();
width: 120,
render: (_, record) => (
<Space>
<Link
onClick={() => {
setCurrentRow(record);
setUpdateModalVisible(true);
}}
>
修改
</Link>
<Popconfirm
title={`确认删除素材[${record.id}]?`}
onConfirm={async () => {
const success = await handleTableAction('delete', record);
if (success) {
actionRef.current?.reload();
}
}
}}
>
<Link>删除</Link>
</Popconfirm>
</Space>
}}
>
<Link>删除</Link>
</Popconfirm>
</Space>
),
},
];
@@ -250,12 +277,30 @@ const TableList: React.FC = () => {
<QueryFilter
defaultCollapsed
split
span={6}
span={8}
className="query-filter"
onFinish={async (values) => setParams(values)}
>
<ProFormText name="name" label="搜索" placeholder="输入关键字" />
<ProFormText
name="description"
label="素材描述"
placeholder="请输入素材描述"
/>
<ProFormSelect
name="tourismId"
label="景区"
placeholder="请选择景区"
options={tourismOptions}
showSearch
/>
<ProFormSelect
name="type"
label="素材类型"
placeholder="请选择素材类型"
options={TYPE_OPTIONS}
/>
</QueryFilter>
<ProTable<ORDERS.TourismFile>
rowKey="id"
headerTitle="素材列表"
@@ -267,30 +312,36 @@ const TableList: React.FC = () => {
pagination={{
showSizeChanger: true,
showQuickJumper: true,
defaultPageSize: 10,
pageSizeOptions: ['10', '20', '50'],
}}
toolBarRender={() => [
<>
<Button
type="primary"
onClick={() => {
handleModalVisible(true);
}}
>
<PlusOutlined /> 添加
</Button>
</>,
<Button
key="add"
type="primary"
onClick={() => setCreateModalVisible(true)}
>
<PlusOutlined /> 新增素材
</Button>,
]}
/>
<ModalForm
title="添加素材"
visible={createModalVisible}
onVisibleChange={handleModalVisible}
onVisibleChange={(visible) => {
console.log('Modal visible changed:', visible);
setCreateModalVisible(visible);
if (visible) {
fetchTourismList();
}
}}
modalProps={{ destroyOnClose: true }}
onFinish={(values) => handleTableAction('add', undefined, values)}
>
<ProForm.Group>
<ProFormSelect
rules={[{ required: true, message: '景区不为空' }]}
rules={[{ required: true, message: '请选择景区' }]}
width="md"
name="tourismId"
label="景区"
@@ -299,6 +350,8 @@ const TableList: React.FC = () => {
showSearch
fieldProps={{
loading: !tourismOptions.length,
filterOption: (input, option) =>
(option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
}}
/>
<ProFormSelect
@@ -342,9 +395,10 @@ const TableList: React.FC = () => {
</Upload>
</ProForm.Group>
</ModalForm>
<UpdateForm
onSubmit={(values) => handleTableAction('edit', currentRow, values)}
onVisibleChange={handleUpdateModalVisible}
onVisibleChange={setUpdateModalVisible}
updateModalVisible={updateModalVisible}
values={currentRow}
tourismOptions={tourismOptions}