From cce34d8f06d0a9cb1d1860b309e5b40d06393e05 Mon Sep 17 00:00:00 2001 From: duzhichao <1098974448@qq.com> Date: Mon, 27 Oct 2025 17:25:32 +0800 Subject: [PATCH 1/4] =?UTF-8?q?feat:=20=E4=BB=BB=E5=8A=A1=E5=88=97?= =?UTF-8?q?=E8=A1=A8=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../order/controller/OrderFileController.java | 141 +++++ .../model/params/FileDownloadRequest.java | 10 + .../order/service/impl/OrderServiceImpl.java | 23 + .../Order/components/OrderResourcesModal.tsx | 513 ++++++++++++++++++ .../orders/Order/components/StatusUpdater.tsx | 67 +++ .../pages/orders/Order/components/Tags.tsx | 12 + .../orders/Order/components/buildColumns.tsx | 47 ++ .../orders/Order/components/constants.ts | 23 + .../src/pages/orders/Order/index.tsx | 42 +- .../src/pages/user/Login/index.tsx | 8 + zlt-web/react-web-next/src/services/orders.ts | 110 ++-- 11 files changed, 937 insertions(+), 59 deletions(-) create mode 100644 zlt-business/order-center/src/main/java/com/central/order/model/params/FileDownloadRequest.java create mode 100644 zlt-web/react-web-next/src/pages/orders/Order/components/OrderResourcesModal.tsx create mode 100644 zlt-web/react-web-next/src/pages/orders/Order/components/StatusUpdater.tsx create mode 100644 zlt-web/react-web-next/src/pages/orders/Order/components/Tags.tsx create mode 100644 zlt-web/react-web-next/src/pages/orders/Order/components/buildColumns.tsx create mode 100644 zlt-web/react-web-next/src/pages/orders/Order/components/constants.ts diff --git a/zlt-business/order-center/src/main/java/com/central/order/controller/OrderFileController.java b/zlt-business/order-center/src/main/java/com/central/order/controller/OrderFileController.java index 89582b40..b112225a 100644 --- a/zlt-business/order-center/src/main/java/com/central/order/controller/OrderFileController.java +++ b/zlt-business/order-center/src/main/java/com/central/order/controller/OrderFileController.java @@ -8,6 +8,7 @@ import com.central.order.constants.EditTaskStatus; import com.central.order.enums.OrderStatus; import com.central.order.feign.FileCenterService; import com.central.order.model.*; +import com.central.order.model.params.FileDownloadRequest; import com.central.order.service.*; import com.central.order.util.DateUtils; import io.swagger.v3.oas.annotations.Operation; @@ -22,6 +23,15 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.*; +import javax.servlet.http.HttpServletResponse; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @@ -29,6 +39,8 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; /** * Order Files information @@ -570,4 +582,133 @@ public class OrderFileController { } } + /** + * 代理下载单个文件 - 解决前端跨域问题 + */ + @Operation(summary = "下载单个文件") + @PostMapping("/download") + public byte[] downloadFile(@RequestBody FileDownloadRequest request) throws IOException { + String fileUrl = request.getUrl(); + log.info("开始代理下载文件: {}", fileUrl); + + if (fileUrl == null || fileUrl.trim().isEmpty()) { + throw new IllegalArgumentException("文件URL不能为空"); + } + + try { + // 从外部 CDN 下载文件 + URL url = new URL(fileUrl); + URLConnection connection = url.openConnection(); + + // 设置超时 + connection.setConnectTimeout(10000); + connection.setReadTimeout(30000); + + // 获取文件内容 + byte[] buffer = new byte[4096]; + int bytesRead; + java.io.ByteArrayOutputStream byteArrayOutputStream = new java.io.ByteArrayOutputStream(); + + try (InputStream input = connection.getInputStream()) { + while ((bytesRead = input.read(buffer)) != -1) { + byteArrayOutputStream.write(buffer, 0, bytesRead); + } + } + + log.info("文件下载成功: {}", extractFileNameFromUrl(fileUrl)); + return byteArrayOutputStream.toByteArray(); + } catch (Exception e) { + log.error("文件下载失败: fileUrl={}", fileUrl, e); + throw new RuntimeException("文件下载失败: " + e.getMessage(), e); + } + } + + /** + * 批量下载所有文件 - 打包为 ZIP + */ + @Operation(summary = "批量下载订单所有资源文件") + @PostMapping("/download/batch") + public byte[] batchDownloadFiles(@RequestBody FileDownloadRequest request) { + String orderNo = request.getOrderNo(); + log.info("开始批量下载订单文件: {}", orderNo); + + if (orderNo == null || orderNo.trim().isEmpty()) { + throw new IllegalArgumentException("订单编号不能为空"); + } + + try { + // 查询订单所有文件 + List orderFiles = orderFileService.getOrderFileByOrderNo(orderNo); + if (CollectionUtils.isEmpty(orderFiles)) { + throw new IllegalArgumentException("订单暂无资源文件"); + } + + // 创建 ZIP 字节流 + java.io.ByteArrayOutputStream byteArrayOutputStream = new java.io.ByteArrayOutputStream(); + try (ZipOutputStream zipOut = new ZipOutputStream(byteArrayOutputStream)) { + for (OrderFile orderFile : orderFiles) { + String viewUrl = fileCenterService.getFileViewUrl(orderFile.getFileId()); + if (viewUrl == null || viewUrl.isEmpty()) { + continue; + } + + try { + // 下载单个文件 + URL fileUrl = new URL(viewUrl); + URLConnection connection = fileUrl.openConnection(); + connection.setConnectTimeout(10000); + connection.setReadTimeout(30000); + + String fileName = extractFileNameFromUrl(viewUrl); + + // 创建 ZIP 条目 + ZipEntry zipEntry = new ZipEntry(fileName); + zipOut.putNextEntry(zipEntry); + + // 写入文件内容到 ZIP + try (InputStream fileInput = connection.getInputStream()) { + byte[] buffer = new byte[4096]; + int bytesRead; + while ((bytesRead = fileInput.read(buffer)) != -1) { + zipOut.write(buffer, 0, bytesRead); + } + } + + zipOut.closeEntry(); + log.info("已添加文件到ZIP: {}", fileName); + } catch (Exception e) { + log.warn("添加文件到ZIP失败: {}", viewUrl, e); + // 继续处理其他文件 + } + } + } + + log.info("批量下载完成: {}", orderNo); + return byteArrayOutputStream.toByteArray(); + } catch (Exception e) { + log.error("批量下载文件失败: orderNo={}", orderNo, e); + throw new RuntimeException("批量下载失败: " + e.getMessage(), e); + } + } + + /** + * 从 URL 中提取文件名 + */ + private String extractFileNameFromUrl(String url) { + if (url == null || url.isEmpty()) { + return "file_" + System.currentTimeMillis(); + } + + try { + // 移除查询参数 + String urlWithoutParams = url.split("\\?")[0]; + // 获取最后一个 /之后的部分 + String[] parts = urlWithoutParams.split("/"); + return parts.length > 0 ? parts[parts.length - 1] : "file_" + System.currentTimeMillis(); + } catch (Exception e) { + log.warn("提取文件名失败: {}", url, e); + return "file_" + System.currentTimeMillis(); + } + } + } diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/params/FileDownloadRequest.java b/zlt-business/order-center/src/main/java/com/central/order/model/params/FileDownloadRequest.java new file mode 100644 index 00000000..25fe745c --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/params/FileDownloadRequest.java @@ -0,0 +1,10 @@ +package com.central.order.model.params; + +import lombok.Data; + +@Data +public class FileDownloadRequest { + private String url; + + private String orderNo; +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderServiceImpl.java index d4d7c153..a9d6be1e 100644 --- a/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderServiceImpl.java +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderServiceImpl.java @@ -87,6 +87,29 @@ public class OrderServiceImpl extends SuperServiceImpl imple @Override public PageResult findList(Map params){ log.info("查询订单列表,参数: {}", params); + + // 获取租户ID,支持三级回退机制 + String anchor = MapUtils.getString(params, "tenantId"); + try { + if (anchor == null || anchor.isEmpty()) { + anchor = com.central.common.context.TenantQueryOverrideContext.getTenantId(); + if (anchor == null || anchor.isEmpty()) { + anchor = com.central.common.context.LoginUserContextHolder.getCurrentTenantId(); + } + } + } catch (Exception e) { + log.error("获取当前登录用户租户失败", e); + } + + // 获取租户及其所有子孙租户ID列表 + List tenantIds = userCenterService.getSonTenantIds(anchor); + + // 根据租户ID列表查询该租户所属的景区 + List tourismIds = tourismMapper.findTourismIdsByTenantIds(tenantIds); + + // 将景区ID列表放入查询参数,用于查询订单 + params.put("tourismIds", tourismIds); + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); List list = baseMapper.findList(page, params); log.info("查询结果数量: {}", list.size()); diff --git a/zlt-web/react-web-next/src/pages/orders/Order/components/OrderResourcesModal.tsx b/zlt-web/react-web-next/src/pages/orders/Order/components/OrderResourcesModal.tsx new file mode 100644 index 00000000..281e660b --- /dev/null +++ b/zlt-web/react-web-next/src/pages/orders/Order/components/OrderResourcesModal.tsx @@ -0,0 +1,513 @@ +import React, { useState, useCallback } from 'react'; +import { Modal, Spin, Empty, Image, Badge, Tabs, Space, Button, Tooltip } from 'antd'; +import { DownloadOutlined, PictureOutlined, PlayCircleOutlined } from '@ant-design/icons'; +import { ordersApi } from '@/services/orders'; +import type { OrderItem } from '@/services/orders'; +import {dateFormatterMap} from "@ant-design/pro-components"; + +interface OrderFile { + id?: number | string; + orderNo?: string; + fileId?: string; + viewUrl?: string; + zipViewUrl?: string; + fileType?: string; + filePath?: string; + fileTag?: string; + createTime?: string; + [key: string]: any; +} + +interface OrderResourcesModalProps { + visible: boolean; + record?: OrderItem; + onCancel: () => void; +} + +// 判断文件类型(通过 MIME type 或文件扩展名) +const isImageFile = (file: OrderFile): boolean => { + const fileType = file.fileType?.toLowerCase() || ''; + const filePath = file.filePath?.toLowerCase() || ''; + const viewUrl = file.viewUrl?.toLowerCase() || ''; + + const imageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/bmp', 'image/svg']; + const imageExts = /\.(jpg|jpeg|png|gif|webp|bmp|svg)$/i; + + return ( + imageTypes.some(type => fileType.includes(type)) || + imageExts.test(filePath) || + imageExts.test(viewUrl) + ); +}; + +const isVideoFile = (file: OrderFile): boolean => { + const fileType = file.fileType?.toLowerCase() || ''; + const filePath = file.filePath?.toLowerCase() || ''; + const viewUrl = file.viewUrl?.toLowerCase() || ''; + + const videoTypes = ['video/mp4', 'video/webm', 'video/ogg', 'video/quicktime', 'video/x-msvideo']; + const videoExts = /\.(mp4|webm|ogg|mov|avi|mkv|flv)$/i; + + return ( + videoTypes.some(type => fileType.includes(type)) || + videoExts.test(filePath) || + videoExts.test(viewUrl) + ); +}; + +const OrderResourcesModal: React.FC = ({ visible, record, onCancel }) => { + const [loading, setLoading] = useState(false); + const [resources, setResources] = useState([]); + const [hasLoadedOnce, setHasLoadedOnce] = useState(false); + const [error, setError] = useState(null); + const [batchDownloading, setBatchDownloading] = useState(false); + + // 当弹窗打开时加载资源列表 + const loadResources = useCallback(async () => { + const orderNo = record?.orderNo; + + if (!orderNo) { + console.warn('⚠️ orderNo is missing:', record); + return; + } + + if (hasLoadedOnce) { + console.log('⏭️ Resources already loaded, skipping...'); + return; + } + + console.log(`📥 Loading resources for order: ${orderNo}`); + setLoading(true); + setError(null); + + try { + const data = await ordersApi.getOrderResources(orderNo); + console.log(`📊 Got ${data?.length || 0} resources:`, data); + setResources(Array.isArray(data) ? data : []); + setHasLoadedOnce(true); + } catch (error: any) { + const errorMsg = error?.message || JSON.stringify(error); + console.error(`❌ Failed to load resources:`, errorMsg); + setError(errorMsg); + setResources([]); + } finally { + setLoading(false); + } + }, [record?.orderNo, hasLoadedOnce]); + + // 分离图片和视频 + const images = resources.filter(isImageFile); + const videos = resources.filter(isVideoFile); + + // 处理下载 - 通过后端代理解决跨域问题 + const handleDownload = async (url: string, fileName?: string) => { + if (!url) return; + + const finalFileName = fileName || `file_${Date.now()}`; + console.log(`⬇️ Starting download: ${url} as ${finalFileName}`); + + try { + // 方式1: 通过后端代理下载(推荐 - 解决跨域问题) + console.log('📌 Downloading via backend proxy...'); + const blob = await ordersApi.downloadFile(url); + + const blobUrl = window.URL.createObjectURL(blob as Blob); + const a = document.createElement('a'); + a.href = blobUrl; + a.download = finalFileName; + a.style.display = 'none'; + document.body.appendChild(a); + + setTimeout(() => { + a.click(); + console.log(`✅ Download started via backend proxy: ${finalFileName}`); + + setTimeout(() => { + document.body.removeChild(a); + window.URL.revokeObjectURL(blobUrl); + }, 100); + }, 0); + + return true; + } catch (error) { + console.error(`❌ Backend proxy download failed:`, error); + + try { + // 方式2: 尝试 XMLHttpRequest(本地可用但跨域受限) + console.log('📌 Trying XHR method...'); + return await new Promise((resolve, reject) => { + const xhr = new XMLHttpRequest(); + xhr.open('GET', url, true); + xhr.responseType = 'blob'; + + xhr.onload = () => { + if (xhr.status === 200) { + const blob = xhr.response; + const blobUrl = window.URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = blobUrl; + a.download = finalFileName; + a.style.display = 'none'; + document.body.appendChild(a); + + setTimeout(() => { + a.click(); + console.log(`✅ Download started via XHR: ${finalFileName}`); + + setTimeout(() => { + document.body.removeChild(a); + window.URL.revokeObjectURL(blobUrl); + resolve(true); + }, 100); + }, 0); + } else { + reject(new Error(`HTTP ${xhr.status}`)); + } + }; + + xhr.onerror = () => { + console.error('XHR download failed:', xhr.status); + reject(new Error('XHR request failed')); + }; + + xhr.send(); + }); + } catch (xhrError) { + console.error(`❌ XHR方式失败:`, xhrError); + + // 方式3: 降级到直接链接 + 新窗口 + console.log('📌 Falling back to direct link in new window...'); + if (url.includes('?')) { + window.open(`${url}&download=1`, '_blank'); + } else { + window.open(`${url}?download=1`, '_blank'); + } + + return true; + } + } + }; + + // 批量下载所有文件 - 并发调用单个文件下载接口 + const handleBatchDownload = async () => { + if (!record?.orderNo) { + console.warn('⚠️ orderNo is missing'); + return; + } + + const orderNo = record.orderNo; + console.log(`⬇️ Starting batch download for order: ${orderNo}`); + console.log(`📊 Total files to download: ${resources.length}`); + setBatchDownloading(true); + + try { + // 并发下载所有文件 - 让浏览器自动管理并发 + const downloadPromises = resources.map(async (file, index) => { + if (!file.viewUrl) { + console.warn(`⚠️ Skipping file without URL: ${file.filePath}`); + return false; + } + + const fileName = file.filePath ? file.filePath.split('/').pop() : `file_${index + 1}`; + console.log(`📥 Queuing download (${index + 1}/${resources.length}): ${fileName}`); + + try { + // 调用单个文件下载接口获取 blob + const blob = await ordersApi.downloadFile(file.viewUrl); + + // 创建下载链接并触发浏览器下载 + const blobUrl = window.URL.createObjectURL(blob as Blob); + const a = document.createElement('a'); + a.href = blobUrl; + if (fileName != null) { + a.download = fileName; + }else { + a.download = '文件下载'; + } + a.style.display = 'none'; + document.body.appendChild(a); + // 添加延迟以错开下载请求,避免浏览器并发限制 + await new Promise((resolve) => setTimeout(resolve, index * 150)); + a.click(); + console.log(`✅ Download triggered: ${fileName}`); + + // 清理资源 + setTimeout(() => { + document.body.removeChild(a); + window.URL.revokeObjectURL(blobUrl); + }, 500); + + return true; + } catch (error) { + console.error(`❌ Failed to download: ${fileName}`, error); + return false; + } + }); + + // 等待所有下载请求完成(不等待浏览器下载完成) + const results = await Promise.all(downloadPromises); + const successCount = results.filter((r) => r).length; + const failureCount = results.filter((r) => !r).length; + + const message = `✅ 批量下载已启动!\n\n成功启动: ${successCount}/${resources.length}\n失败: ${failureCount}\n\n📥 文件已经全部下载完成\n📋 请检查浏览器下载列表`; + console.log(`🎉 ${message}`); + alert(message); + } catch (error) { + console.error(`❌ Batch download failed:`, error); + alert('批量下载失败,请重试'); + } finally { + setBatchDownloading(false); + } + }; + + // 获取文件显示名称 + const getFileName = (file: OrderFile, index: number) => { + if (file.filePath) { + return file.filePath.split('/').pop() || `文件${index + 1}`; + } + return `文件${index + 1}`; + }; + + // 图片预览卡片 + const ImageGallery = () => ( +
+ {images.length === 0 ? ( + + ) : ( + images.map((item, idx) => { + const fileName = getFileName(item, idx); + return ( + +
{ + e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.15)'; + }} + onMouseLeave={(e) => { + e.currentTarget.style.boxShadow = 'none'; + }} + > + {fileName} +
+ {fileName} +
+
+
+ ); + }) + )} +
+ ); + + // 视频列表卡片 + const VideoGallery = () => ( +
+ {videos.length === 0 ? ( + + ) : ( +
+ {videos.map((item, idx) => { + const fileName = getFileName(item, idx); + return ( +
+ {/* 视频信息头 */} +
+
+ + + {fileName} + +
+ +
+ + {/* 视频播放器 */} +
+ +
+ + {/* 视频元数据 */} +
+ {item.createTime && ( +
+ 上传时间: {new Date(item.createTime).toLocaleString()} +
+ )} + {item.fileType && ( +
+ 文件类型: {item.fileType} +
+ )} + {item.fileTag && ( +
+ 文件标签: {item.fileTag} +
+ )} +
+
+ ); + })} +
+ )} +
+ ); + + // 使用 effect 在 visible 变化时加载资源 + React.useEffect(() => { + if (visible) { + console.log('🔓 Modal opened, loading resources...'); + loadResources(); + } + }, [visible, loadResources]); + + // 生成模态框标题 + const modalTitle = `订单资源列表 - ${record?.orderNo || ''}`; + + return ( + + 关闭 + , + , + ]} + > + + {error && ( +
+ 加载失败: {error} +
+ )} + {resources.length === 0 && !loading && !error ? ( + + ) : ( + + + 图片 ({images.length}) + + } + key="images" + > + + + + 视频 ({videos.length}) + + } + key="videos" + > + + + + )} +
+
+ ); +}; + +export default OrderResourcesModal; diff --git a/zlt-web/react-web-next/src/pages/orders/Order/components/StatusUpdater.tsx b/zlt-web/react-web-next/src/pages/orders/Order/components/StatusUpdater.tsx new file mode 100644 index 00000000..83fa8e54 --- /dev/null +++ b/zlt-web/react-web-next/src/pages/orders/Order/components/StatusUpdater.tsx @@ -0,0 +1,67 @@ +// UTF-8: 状态修改组件 +import React, { useState } from 'react'; +import { Modal, Select, message } from 'antd'; +import { ORDER_STATUS_OPTIONS } from './constants'; +import { ordersApi } from '@/services/orders'; + +interface Props { + record: any; + onUpdated?: () => void; +} + +const StatusUpdater: React.FC = ({ record, onUpdated }) => { + const [open, setOpen] = useState(false); + const [value, setValue] = useState(record?.orderStatus); + const [loading, setLoading] = useState(false); + + // 从 localStorage 中获取当前用户的真实租户ID(登录时通过 tenant/current/info 接口获取) + // 只有当前登录租户是 webApp 时才能显示修改状态 + const currentTenantId = localStorage.getItem('current_tenant_id'); + const canModify = currentTenantId === 'webApp'; + + // 如果不是 webApp 租户,不显示修改状态按钮 + if (!canModify) { + return null; + } + + const onOk = async () => { + if (typeof value === 'undefined') { message.warning('请选择订单状态'); return; } + setLoading(true); + try { + await ordersApi.updateOrder({ id: record.id, orderStatus: value }); + message.success('状态已更新'); + setOpen(false); + onUpdated?.(); + } catch (e) { + message.error('更新失败'); + } finally { setLoading(false); } + }; + + return ( + <> + setOpen(true)}>修改状态 + setOpen(false)} + > +
+ 请选择状态: + - + + diff --git a/zlt-web/react-web-next/src/pages/orders/Order/components/CreateRefundModal.tsx b/zlt-web/react-web-next/src/pages/orders/Order/components/CreateRefundModal.tsx new file mode 100644 index 00000000..cbdaa972 --- /dev/null +++ b/zlt-web/react-web-next/src/pages/orders/Order/components/CreateRefundModal.tsx @@ -0,0 +1,60 @@ +// UTF-8: 创建退款订单弹框组件 +import React, { useState } from 'react'; +import { Modal, Form, message, Spin } from 'antd'; +import { ordersApi } from '@/services/orders'; + +interface CreateRefundModalProps { + visible: boolean; + orderNo: string; + onCancel: () => void; + onSuccess?: () => void; +} + +const CreateRefundModal: React.FC = ({ + visible, + orderNo, + onCancel, + onSuccess, +}) => { + const [form] = Form.useForm(); + const [loading, setLoading] = useState(false); + + const handleSubmit = async () => { + try { + setLoading(true); + + // 调用 RefundController 的 createRefundOrder 接口 + await ordersApi.createRefundOrder(orderNo, {}); + + message.success('退款订单已创建'); + onSuccess?.(); + onCancel(); + } catch (error) { + console.error('创建退款订单失败:', error); + message.error('创建退款订单失败'); + } finally { + setLoading(false); + } + }; + + return ( + + +
+

确定要为订单 {orderNo} 创建退款订单吗?

+

创建退款后,订单状态将变为"退款中"

+
+
+
+ ); +}; + +export default CreateRefundModal; diff --git a/zlt-web/react-web-next/src/pages/orders/Order/components/RefundReviewModal.tsx b/zlt-web/react-web-next/src/pages/orders/Order/components/RefundReviewModal.tsx new file mode 100644 index 00000000..af9426a7 --- /dev/null +++ b/zlt-web/react-web-next/src/pages/orders/Order/components/RefundReviewModal.tsx @@ -0,0 +1,273 @@ +// UTF-8: 退款审核弹框组件 +import React, { useState, useEffect } from 'react'; +import { Modal, Form, Select, Input, message, Empty, Image, Space, Row, Col, Divider } from 'antd'; +import { ordersApi } from '@/services/orders'; + +interface RefundReviewModalProps { + visible: boolean; + orderNo: string; + onCancel: () => void; + onSuccess?: () => void; + isReviewMode: boolean; // true: 审核模式,false: 查看模式 +} + +const RefundReviewModal: React.FC = ({ + visible, + orderNo, + onCancel, + onSuccess, + isReviewMode = true, +}) => { + const [form] = Form.useForm(); + const [loading, setLoading] = useState(false); + const [refundData, setRefundData] = useState(null); + const [fetching, setFetching] = useState(false); + + // 审核结果选项 + const reviewResults = [ + { label: '审核通过', value: 1 }, + { label: '审核拒绝', value: 0 }, + ]; + + // 格式化金额(分转元) + const formatAmount = (amount: any): string => { + if (!amount && amount !== 0) return '0.00'; + const num = parseFloat(amount); + // 统一处理:分转元(除以100) + return (num / 100).toFixed(2); + }; + + // 格式化时间 + const formatTime = (time: any): string => { + if (!time) return '-'; + try { + const date = new Date(time); + const year = date.getFullYear(); + const month = String(date.getMonth() + 1).padStart(2, '0'); + const day = String(date.getDate()).padStart(2, '0'); + const hours = String(date.getHours()).padStart(2, '0'); + const minutes = String(date.getMinutes()).padStart(2, '0'); + const seconds = String(date.getSeconds()).padStart(2, '0'); + return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; + } catch (e) { + return String(time); + } + }; + + // 获取退款订单详情 + useEffect(() => { + if (visible && orderNo) { + fetchRefundDetail(); + } + }, [visible, orderNo]); + + const fetchRefundDetail = async () => { + setFetching(true); + try { + // 调用后端接口根据订单编码获取退款订单详情 + const data: any = await ordersApi.getRefundDetail(orderNo); + + if (data) { + setRefundData(data); + console.log('退款详情:', data); + } else { + message.warning('未找到该订单的退款记录'); + setRefundData(null); + } + } catch (error) { + message.error('获取退款详情失败'); + console.error('获取退款详情失败:', error); + } finally { + setFetching(false); + } + }; + + const handleSubmit = async () => { + if (!isReviewMode) { + onCancel(); + return; + } + + try { + const values = await form.validateFields(); + setLoading(true); + + // 调用审核接口(需要与后端 RefundController.approveOrder 的参数匹配) + const res = await ordersApi.updateRefund({ + orderNo: refundData?.orderNo, // 订单号(后端需要校验订单状态) + refundNo: refundData?.refundNo, // 退款单号 + status: refundData?.status, // 退款状态(应保持为 REFUNDING) + state: values.reviewResult, // 审核状态:1=通过(APPROVED),0=拒绝(REFUSED) + approveReason: values.reviewComment, // 审核意见 + }); + + // 显示后端返回的实际消息 + const successMsg = res?.resp_msg || res?.message || '审核已提交'; + message.success(successMsg); + onSuccess?.(); + onCancel(); + } catch (error) { + console.error('提交审核失败:', error); + message.error('提交审核失败'); + } finally { + setLoading(false); + } + }; + + return ( + + {fetching ? ( +
+ 加载中... +
+ ) : refundData ? ( + <> + {/* 基本信息行 */} + + +
+ 退款单号 +
{refundData?.refundNo || orderNo}
+
+ + +
+ 订单编号 +
{refundData?.orderNo || orderNo}
+
+ +
+ + + + {/* 金额信息 */} + + +
+ 订单金额 +
¥ {formatAmount(refundData?.orderAmount)}
+
+ + +
+ 退款金额 +
¥ {formatAmount(refundData?.refundAmount)}
+
+ +
+ + + + {/* 状态信息 */} + + +
+ 订单状态 +
+ + {refundData?.orderStatus || '退款中'} + +
+
+ + +
+ 退款状态 +
+ + {refundData?.status === 1 ? '待审核' : refundData?.status === 2 ? '已审核' : '待审核'} + +
+
+ +
+ + + + {/* 退款原因 */} +
+ 退款原因 +
+ {refundData?.reason || refundData?.refundReason || '-'} +
+
+ + {/* 退款凭证(图片) */} + {refundData?.images && refundData?.images.length > 0 && ( + <> +
+ 退款凭证 +
+ {Array.isArray(refundData?.images) ? ( + refundData?.images.map((img: string | any, index: number) => { + const imgUrl = typeof img === 'string' ? img : img?.url || img?.path; + return imgUrl ? ( +
+ +
+ ) : null; + }) + ) : null} +
+
+ + )} + + {/* 申请时间 */} +
+ 申请时间 +
{formatTime(refundData?.createTime || refundData?.applyTime)}
+
+ + + + {/* 审核表单(仅审核模式显示) */} + {isReviewMode && ( +
+ +