feat: 任务列表优化

This commit is contained in:
2025-10-27 17:25:32 +08:00
parent c4fc11fd34
commit cce34d8f06
11 changed files with 937 additions and 59 deletions
@@ -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<OrderResourcesModalProps> = ({ visible, record, onCancel }) => {
const [loading, setLoading] = useState(false);
const [resources, setResources] = useState<OrderFile[]>([]);
const [hasLoadedOnce, setHasLoadedOnce] = useState(false);
const [error, setError] = useState<string | null>(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 = () => (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(150px, 1fr))', gap: '16px', padding: '16px 0' }}>
{images.length === 0 ? (
<Empty description="暂无图片资源" />
) : (
images.map((item, idx) => {
const fileName = getFileName(item, idx);
return (
<Tooltip key={item.id || idx} title={fileName}>
<div
style={{
position: 'relative',
overflow: 'hidden',
borderRadius: '4px',
border: '1px solid #f0f0f0',
backgroundColor: '#fafafa',
cursor: 'pointer',
transition: 'all 0.3s ease',
}}
onMouseEnter={(e) => {
e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.15)';
}}
onMouseLeave={(e) => {
e.currentTarget.style.boxShadow = 'none';
}}
>
<Image
src={item.viewUrl}
preview={{ mask: '预览' }}
style={{ width: '100%', height: '120px', objectFit: 'cover', display: 'block' }}
alt={fileName}
fallback="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMIAAADDCAYAAADQvc6ZAAABRklEQVR4Xu3QQQEAAADCoPVPbQhfoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB4NehrD5aKxbkB/QAAAAASUVORK5CYII="
/>
<div style={{
padding: '4px 8px',
fontSize: '11px',
color: '#666',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
minHeight: '16px'
}}>
{fileName}
</div>
<Button
type="primary"
size="small"
icon={<DownloadOutlined />}
onClick={async (e) => {
e.stopPropagation();
if (item.viewUrl) {
await handleDownload(item.viewUrl, fileName);
}
}}
style={{
position: 'absolute',
top: '4px',
right: '4px',
opacity: 0.8
}}
/>
</div>
</Tooltip>
);
})
)}
</div>
);
// 视频列表卡片
const VideoGallery = () => (
<div style={{ padding: '16px 0' }}>
{videos.length === 0 ? (
<Empty description="暂无视频资源" />
) : (
<div style={{ display: 'grid', gap: '16px' }}>
{videos.map((item, idx) => {
const fileName = getFileName(item, idx);
return (
<div
key={item.id || idx}
style={{
border: '1px solid #f0f0f0',
borderRadius: '4px',
overflow: 'hidden',
backgroundColor: '#fafafa',
padding: '12px',
}}
>
{/* 视频信息头 */}
<div style={{
marginBottom: '12px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<PlayCircleOutlined style={{ fontSize: '18px', color: '#1890ff' }} />
<span style={{ fontWeight: 500, maxWidth: '400px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{fileName}
</span>
</div>
<Button
type="primary"
size="small"
icon={<DownloadOutlined />}
onClick={async () => {
if (item.viewUrl) {
await handleDownload(item.viewUrl, fileName);
}
}}
>
下载
</Button>
</div>
{/* 视频播放器 */}
<div style={{
marginBottom: '12px',
borderRadius: '4px',
overflow: 'hidden',
backgroundColor: '#000',
}}>
<video
controls
style={{
width: '100%',
maxHeight: '500px',
display: 'block',
}}
controlsList="nodownload"
>
<source src={item.viewUrl} type="video/mp4" />
您的浏览器不支持 HTML5 视频播放
</video>
</div>
{/* 视频元数据 */}
<div style={{ fontSize: '12px', color: '#999', display: 'grid', gap: '4px' }}>
{item.createTime && (
<div>
上传时间: {new Date(item.createTime).toLocaleString()}
</div>
)}
{item.fileType && (
<div>
文件类型: {item.fileType}
</div>
)}
{item.fileTag && (
<div>
文件标签: {item.fileTag}
</div>
)}
</div>
</div>
);
})}
</div>
)}
</div>
);
// 使用 effect 在 visible 变化时加载资源
React.useEffect(() => {
if (visible) {
console.log('🔓 Modal opened, loading resources...');
loadResources();
}
}, [visible, loadResources]);
// 生成模态框标题
const modalTitle = `订单资源列表 - ${record?.orderNo || ''}`;
return (
<Modal
title={modalTitle}
visible={visible}
onCancel={onCancel}
width={1000}
footer={[
<Button key="cancel" onClick={onCancel}>
关闭
</Button>,
<Button
key="batch-download"
type="primary"
icon={<DownloadOutlined />}
loading={batchDownloading}
disabled={resources.length === 0 || loading}
onClick={handleBatchDownload}
>
下载全部文件
</Button>,
]}
>
<Spin spinning={loading}>
{error && (
<div style={{ padding: '16px', background: '#fff2e8', border: '1px solid #ffbb96', borderRadius: '4px', marginBottom: '16px', color: '#d4380d' }}>
<strong>加载失败:</strong> {error}
</div>
)}
{resources.length === 0 && !loading && !error ? (
<Empty description="该订单暂无资源" />
) : (
<Tabs
defaultActiveKey="images"
>
<Tabs.TabPane
tab={
<Badge
count={images.length}
style={{ backgroundColor: '#52c41a' }}
>
<span>图片 ({images.length})</span>
</Badge>
}
key="images"
>
<ImageGallery />
</Tabs.TabPane>
<Tabs.TabPane
tab={
<Badge
count={videos.length}
style={{ backgroundColor: '#1890ff' }}
>
<span>视频 ({videos.length})</span>
</Badge>
}
key="videos"
>
<VideoGallery />
</Tabs.TabPane>
</Tabs>
)}
</Spin>
</Modal>
);
};
export default OrderResourcesModal;
@@ -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<Props> = ({ record, onUpdated }) => {
const [open, setOpen] = useState(false);
const [value, setValue] = useState<number | undefined>(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 (
<>
<a onClick={() => setOpen(true)}>修改状态</a>
<Modal
title={`修改订单状态 - ${record?.orderNo || record?.id}`}
open={open}
onOk={onOk}
okText="确定"
cancelText="取消"
confirmLoading={loading}
onCancel={() => setOpen(false)}
>
<div>
<span style={{ marginRight: 8 }}>请选择状态:</span>
<Select
value={value}
onChange={setValue}
options={ORDER_STATUS_OPTIONS.map(o => ({ label: o.label, value: o.value }))}
style={{ minWidth: 200 }}
placeholder="请选择订单状态"
/>
</div>
</Modal>
</>
);
};
export default StatusUpdater;
@@ -0,0 +1,12 @@
// UTF-8: 标签渲染组件
import React from 'react';
import { Tag } from 'antd';
import { ORDER_STATUS_OPTIONS, PAY_TYPE_OPTIONS, findColor, findLabel } from './constants';
export const PayTypeTag: React.FC<{ value?: number }> = ({ value }) => (
<Tag color={findColor(PAY_TYPE_OPTIONS, value)}>{findLabel(PAY_TYPE_OPTIONS, value)}</Tag>
);
export const OrderStatusTag: React.FC<{ value?: number }> = ({ value }) => (
<Tag color={findColor(ORDER_STATUS_OPTIONS, value)}>{findLabel(ORDER_STATUS_OPTIONS, value)}</Tag>
);
@@ -0,0 +1,47 @@
// UTF-8: 订单列表列定义(按截图样式)
import React, { useState } from 'react';
import type { ProColumns } from '@ant-design/pro-components';
import { Space, Typography } from 'antd';
import { PayTypeTag, OrderStatusTag } from './Tags';
import StatusUpdater from './StatusUpdater';
import OrderResourcesModal from './OrderResourcesModal';
import type { OrderItem } from '@/services/orders';
const { Link } = Typography;
// 资源列表操作组件
const ResourcesActionCell: React.FC<{ record: OrderItem; onReload?: () => void }> = ({ record, onReload }) => {
const [resourceModalVisible, setResourceModalVisible] = useState(false);
return (
<>
<Space size="small" wrap style={{ minWidth: 120 }}>
<Link onClick={() => setResourceModalVisible(true)}>资源列表</Link>
<StatusUpdater record={record} onUpdated={onReload} />
</Space>
<OrderResourcesModal
visible={resourceModalVisible}
record={record}
onCancel={() => setResourceModalVisible(false)}
/>
</>
);
};
export const buildOrderColumns = (onReload?: () => void): ProColumns<OrderItem>[] => [
{ dataIndex: 'index', valueType: 'indexBorder', width: 56 },
{ title: '订单ID', dataIndex: 'id', width: 100, copyable: true },
{ title: '景区名称', dataIndex: 'tourismName', width: 180, render: (v) => (<span>{v || '-'}</span>) },
{ title: '订单编号', dataIndex: 'orderNo', width: 180, copyable: true, ellipsis: true },
{ title: '状态', dataIndex: 'orderStatus', width: 100, render: (v) => <OrderStatusTag value={v as number} /> },
{ title: '支付类型', dataIndex: 'payType', width: 100, render: (v) => <PayTypeTag value={v as number} /> },
{ title: '用户手机号', dataIndex: 'mobile', width: 140, copyable: true },
{ title: '二维码ID', dataIndex: 'codeId', width: 120, copyable: true },
{ title: '设备编号', dataIndex: 'deviceSn', width: 160, copyable: true, ellipsis: true },
{ title: '创建时间', dataIndex: 'createTime', width: 180, valueType: 'dateTime' },
{title: '支付时间', dataIndex: 'payTime', width: 180, valueType: 'dateTime'},
{
title: '操作', valueType: 'option', width: 140, fixed: 'right',
render: (_, record) => <ResourcesActionCell record={record} onReload={onReload} />
},
];
@@ -0,0 +1,23 @@
// UTF-8: 常量映射 - 订单支付方式与订单状态
// 注意:仅用于前端展示,可根据需要在此新增/调整
export const PAY_TYPE_OPTIONS: { label: string; value: number; color?: string }[] = [
{ label: '微信支付', value: 1, color: 'green' },
{ label: '优惠券支付', value: 2, color: 'blue' },
];
export const ORDER_STATUS_OPTIONS: { label: string; value: number; color?: string }[] = [
{ label: '待支付', value: 0, color: 'default' },
{ label: '排队中', value: 1, color: 'gold' },
{ label: '已取消', value: 2, color: 'default' },
{ label: '设备执行完成', value: 3, color: 'cyan' },
{ label: '服务中', value: 4, color: 'blue' },
{ label: '素材上传中', value: 5, color: 'geekblue' },
{ label: '任务完成', value: 6, color: 'green' },
{ label: '退款中', value: 7, color: 'orange' },
{ label: '退款成功', value: 8, color: 'lime' },
{ label: '退款失败', value: 9, color: 'red' },
];
export const findLabel = (arr: { label: string; value: number }[], v?: number) => arr.find(o => o.value === v)?.label || '未知';
export const findColor = (arr: { color?: string; value: number }[], v?: number) => arr.find(o => o.value === v)?.color;
@@ -1,35 +1,16 @@
import React, { useRef, useState } from 'react';
import React, { useRef, useMemo, useState } from 'react';
import { PageContainer, ProFormSelect, ProFormText, ProTable } from '@ant-design/pro-components';
import type { ActionType } from '@ant-design/pro-components';
import { Tag } from 'antd';
import { ordersApi, OrderItem } from '@/services/orders';
import { GlassCard, SearchBarPlus } from '@/components/ui';
const STATUS_OPTIONS = [
{ label: '未支付', value: 0 },
{ label: '已支付', value: 1 },
{ label: '已退款', value: 2 },
{ label: '已取消', value: 3 },
];
const PAY_TYPE_OPTIONS = [
{ label: '微信支付', value: 1 },
{ label: '优惠券支付', value: 2 },
];
import { ORDER_STATUS_OPTIONS, PAY_TYPE_OPTIONS } from './components/constants';
import { buildOrderColumns } from './components/buildColumns';
const OrderPage: React.FC = () => {
const [params, setParams] = useState<Record<string, any>>({});
const actionRef = useRef<ActionType>();
const [searchParams, setSearchParams] = useState<Record<string, any>>({});
const columns: any[] = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
{ title: '订单编号', dataIndex: 'orderNo' },
{ title: '金额', dataIndex: 'amount' },
{ title: '支付方式', dataIndex: 'payType', render: (v: number) => <Tag color={v === 1 ? 'green' : 'blue'}>{PAY_TYPE_OPTIONS.find(o => o.value === v)?.label || '未知'}</Tag> },
{ title: '状态', dataIndex: 'orderStatus', render: (v: number) => <Tag>{STATUS_OPTIONS.find(o => o.value === v)?.label || '未知'}</Tag> },
{ title: '旅游项目', dataIndex: 'tourismName' },
{ title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime' },
];
const columns = useMemo(() => buildOrderColumns(() => actionRef.current?.reload?.()), []);
return (
<PageContainer header={{ title: '订单管理' }}>
@@ -37,11 +18,15 @@ const OrderPage: React.FC = () => {
defaultCollapsed={false}
split
span={6}
onTenantChanged={() => actionRef.current?.reload()}
onFinish={async (values) => setParams(values)}
onTenantChanged={() => actionRef.current?.reload?.()}
onFinish={async (values) => {
setSearchParams(values);
actionRef.current?.reload?.();
}}
>
<ProFormText name="orderNo" label="订单编号" placeholder="请输入订单编号" />
<ProFormSelect name="orderStatus" label="订单状态" options={STATUS_OPTIONS} allowClear />
{/*<ProFormText name="mobile" label="用户手机号" placeholder="请输入手机号" />*/}
<ProFormSelect name="orderStatus" label="订单状态" options={ORDER_STATUS_OPTIONS} allowClear />
<ProFormSelect name="payType" label="支付方式" options={PAY_TYPE_OPTIONS} allowClear />
</SearchBarPlus>
@@ -50,10 +35,11 @@ const OrderPage: React.FC = () => {
rowKey="id"
headerTitle="订单列表"
actionRef={actionRef}
request={(p) => ordersApi.order({ ...p, ...params } as any)}
request={(p) => ordersApi.order({ ...p, ...searchParams } as any)}
columns={columns}
search={false}
pagination={{ showSizeChanger: true, showQuickJumper: true, defaultPageSize: 20 }}
scroll={{ x: 1500 }}
/>
</GlassCard>
</PageContainer>
@@ -39,6 +39,14 @@ const LoginPage: React.FC = () => {
const { ensureTenantCacheTokenGuard, setTenantTreeCache } = await import('@/utils/tenantCache');
const { tenantApi } = await import('@/services/tenant');
ensureTenantCacheTokenGuard();
// 获取当前用户的真实租户ID
const currentTenantRes: any = await tenantApi.getCurrentTenant();
const currentTenantId = currentTenantRes?.data?.tenantId || currentTenantRes?.tenantId;
if (currentTenantId) {
localStorage.setItem('current_tenant_id', currentTenantId);
}
const treeRes: any = await tenantApi.getAccessibleTenants();
let list: any[] = [];
if (typeof treeRes?.success !== 'undefined') list = treeRes.success ? (treeRes.data || []) : [];