249 lines
9.7 KiB
TypeScript
249 lines
9.7 KiB
TypeScript
import { useCallback, useEffect, useState } from 'react';
|
||
import { Badge, Modal } from 'antd';
|
||
import type { Dayjs } from 'dayjs';
|
||
import dayjs from 'dayjs';
|
||
import isBetween from 'dayjs/plugin/isBetween';
|
||
|
||
import { useToast } from '../../contexts/ToastContext';
|
||
import { useDataCutoffDate } from '../../hooks/useDataCutoffDate';
|
||
import { request } from '../../utils/request';
|
||
import { NasaDownloadView } from './nasa-download/NasaDownloadView';
|
||
import type { CelestialBody, DateRange, GroupedBodies, PositionRow, ViewingDateData } from './nasa-download/types';
|
||
|
||
dayjs.extend(isBetween);
|
||
|
||
export function NASADownload() {
|
||
const [loading, setLoading] = useState(false);
|
||
const [bodies, setBodies] = useState<GroupedBodies>({});
|
||
const [selectedBodies, setSelectedBodies] = useState<string[]>([]);
|
||
const [dateRange, setDateRange] = useState<DateRange>([dayjs().startOf('month'), dayjs().endOf('month')]);
|
||
const [availableDates, setAvailableDates] = useState<Map<string, Set<string>>>(new Map());
|
||
const [loadingDates, setLoadingDates] = useState(false);
|
||
const [downloading, setDownloading] = useState(false);
|
||
const [deleting, setDeleting] = useState(false);
|
||
const [downloadProgress, setDownloadProgress] = useState({ current: 0, total: 0 });
|
||
const [activeBodyForCalendar, setActiveBodyForCalendar] = useState<string | null>(null);
|
||
const [viewingDateData, setViewingDateData] = useState<ViewingDateData | null>(null);
|
||
const [loadingDateData, setLoadingDateData] = useState(false);
|
||
const toast = useToast();
|
||
const { cutoffDate } = useDataCutoffDate();
|
||
// 静态 Modal.confirm 读不到 ConfigProvider 的深色主题,改用带上下文的实例。
|
||
const [modal, modalContextHolder] = Modal.useModal();
|
||
|
||
const loadBodies = useCallback(async () => {
|
||
setLoading(true);
|
||
try {
|
||
const { data } = await request.get('/celestial/positions/download/bodies');
|
||
const activeBodies: GroupedBodies = {};
|
||
Object.keys(data.bodies || {}).forEach((type) => {
|
||
const active = data.bodies[type].filter((body: CelestialBody) => body.is_active);
|
||
if (active.length > 0) activeBodies[type] = active;
|
||
});
|
||
setBodies(activeBodies);
|
||
} catch {
|
||
toast.error('加载天体列表失败');
|
||
} finally {
|
||
setLoading(false);
|
||
}
|
||
}, [toast]);
|
||
|
||
const loadAvailableDates = useCallback(async () => {
|
||
if (selectedBodies.length === 0) return;
|
||
setLoadingDates(true);
|
||
try {
|
||
const datesByBody = new Map<string, Set<string>>();
|
||
for (const bodyId of selectedBodies) {
|
||
const { data } = await request.get('/celestial/positions/download/status', {
|
||
params: { body_id: bodyId, start_date: dateRange[0].format('YYYY-MM-DD'), end_date: dateRange[1].format('YYYY-MM-DD') },
|
||
});
|
||
datesByBody.set(bodyId, new Set<string>(data.available_dates));
|
||
}
|
||
setAvailableDates(datesByBody);
|
||
} catch {
|
||
toast.error('加载数据状态失败');
|
||
} finally {
|
||
setLoadingDates(false);
|
||
}
|
||
}, [dateRange, selectedBodies, toast]);
|
||
|
||
useEffect(() => {
|
||
void loadBodies();
|
||
}, [loadBodies]);
|
||
|
||
useEffect(() => {
|
||
if (selectedBodies.length === 0) {
|
||
setAvailableDates(new Map());
|
||
setActiveBodyForCalendar(null);
|
||
return;
|
||
}
|
||
void loadAvailableDates();
|
||
if (!activeBodyForCalendar || !selectedBodies.includes(activeBodyForCalendar)) setActiveBodyForCalendar(selectedBodies[0]);
|
||
}, [activeBodyForCalendar, dateRange, loadAvailableDates, selectedBodies]);
|
||
|
||
const handleBodySelect = (bodyId: string, checked: boolean) => {
|
||
setSelectedBodies((current) => checked ? [...current, bodyId] : current.filter((id) => id !== bodyId));
|
||
};
|
||
|
||
const handleTypeSelectAll = (type: string, checked: boolean) => {
|
||
const bodyIds = bodies[type].map((body) => body.id);
|
||
setSelectedBodies((current) => checked ? [...new Set([...current, ...bodyIds])] : current.filter((id) => !bodyIds.includes(id)));
|
||
};
|
||
|
||
const handleDateRangeChange = (dates: [Dayjs | null, Dayjs | null] | null) => {
|
||
if (dates?.[0] && dates[1]) setDateRange([dates[0], dates[1]]);
|
||
};
|
||
|
||
const getDatesInRange = (excludeFuture: boolean) => {
|
||
const result: string[] = [];
|
||
let current = dateRange[0];
|
||
while (current.isBefore(dateRange[1]) || current.isSame(dateRange[1], 'day')) {
|
||
if (!excludeFuture || !current.isAfter(dayjs(), 'day')) result.push(current.format('YYYY-MM-DD'));
|
||
current = current.add(1, 'day');
|
||
}
|
||
return result;
|
||
};
|
||
|
||
const handleDownload = async (selectedDate?: Dayjs) => {
|
||
if (selectedBodies.length === 0) {
|
||
toast.warning('请先选择至少一个天体');
|
||
return;
|
||
}
|
||
if (selectedDate?.isAfter(dayjs(), 'day')) {
|
||
toast.warning('不能下载未来日期的数据');
|
||
return;
|
||
}
|
||
|
||
const dates = selectedDate ? [selectedDate.format('YYYY-MM-DD')] : getDatesInRange(true);
|
||
if (dates.length === 0) {
|
||
toast.warning('所选日期范围内没有可下载的数据');
|
||
return;
|
||
}
|
||
|
||
setDownloading(true);
|
||
setDownloadProgress({ current: 0, total: dates.length });
|
||
try {
|
||
if (selectedDate) {
|
||
const { data } = await request.post('/celestial/positions/download', { body_ids: selectedBodies, dates });
|
||
setDownloadProgress({ current: dates.length, total: dates.length });
|
||
if (data.total_success > 0) {
|
||
toast.success(`成功下载 ${data.total_success} 条数据${data.total_failed > 0 ? `,${data.total_failed} 条失败` : ''}`);
|
||
await loadAvailableDates();
|
||
} else {
|
||
toast.error('下载失败');
|
||
}
|
||
} else {
|
||
await request.post('/celestial/positions/download-async', { body_ids: selectedBodies, dates });
|
||
toast.success('批量下载任务已启动,请前往“系统任务”查看进度');
|
||
}
|
||
} catch {
|
||
toast.error('请求失败');
|
||
} finally {
|
||
setDownloading(false);
|
||
setDownloadProgress({ current: 0, total: 0 });
|
||
}
|
||
};
|
||
|
||
const handleDelete = () => {
|
||
if (selectedBodies.length === 0) {
|
||
toast.warning('请先选择至少一个天体');
|
||
return;
|
||
}
|
||
const dates = getDatesInRange(false);
|
||
if (dates.length === 0) return;
|
||
|
||
modal.confirm({
|
||
title: '确认删除',
|
||
content: `确定要删除 ${selectedBodies.length} 个天体在 ${dates.length} 天内的所有位置数据吗?此操作不可恢复。`,
|
||
okText: '确认删除',
|
||
okType: 'danger',
|
||
cancelText: '取消',
|
||
onOk: async () => {
|
||
setDeleting(true);
|
||
try {
|
||
const { data } = await request.post('/celestial/positions/delete', { body_ids: selectedBodies, dates });
|
||
toast.success(data.message || '数据已删除');
|
||
await loadAvailableDates();
|
||
} catch {
|
||
toast.error('删除失败');
|
||
} finally {
|
||
setDeleting(false);
|
||
}
|
||
},
|
||
});
|
||
};
|
||
|
||
const dateCellRender = (value: Dayjs) => {
|
||
if (!activeBodyForCalendar || !value.isBetween(dateRange[0], dateRange[1], 'day', '[]')) return null;
|
||
return <div style={{ textAlign: 'center', padding: '4px 0' }}><Badge status={availableDates.get(activeBodyForCalendar)?.has(value.format('YYYY-MM-DD')) ? 'success' : 'default'} text="" /></div>;
|
||
};
|
||
|
||
const loadDateData = async (date: string) => {
|
||
setLoadingDateData(true);
|
||
try {
|
||
const bodyIds = selectedBodies.filter((bodyId) => availableDates.get(bodyId)?.has(date));
|
||
if (bodyIds.length === 0) {
|
||
setViewingDateData({ date, bodies: [] });
|
||
return;
|
||
}
|
||
|
||
const { data } = await request.get('/celestial/positions', {
|
||
params: { body_ids: bodyIds.join(','), start_time: `${date}T00:00:00Z`, end_time: `${date}T00:00:00Z` },
|
||
});
|
||
const allBodies = Object.values(bodies).flat();
|
||
const rows: PositionRow[] = [];
|
||
data.bodies?.forEach((bodyData: { id: string; name?: string; positions?: PositionRow[] }) => {
|
||
const position = bodyData.positions?.[0];
|
||
if (!position) return;
|
||
const body = allBodies.find((item) => item.id === bodyData.id);
|
||
rows.push({ ...position, id: bodyData.id, name: body?.name_zh || body?.name || bodyData.name || bodyData.id });
|
||
});
|
||
setViewingDateData({ date, bodies: rows });
|
||
} catch {
|
||
toast.error('加载数据失败');
|
||
} finally {
|
||
setLoadingDateData(false);
|
||
}
|
||
};
|
||
|
||
const handleCalendarDateClick = async (date: Dayjs) => {
|
||
if (!date.isBetween(dateRange[0], dateRange[1], 'day', '[]')) {
|
||
toast.warning('请选择在日期范围内的日期');
|
||
return;
|
||
}
|
||
if (date.isAfter(dayjs(), 'day') || !activeBodyForCalendar) return;
|
||
const dateString = date.format('YYYY-MM-DD');
|
||
if (availableDates.get(activeBodyForCalendar)?.has(dateString)) await loadDateData(dateString);
|
||
else await handleDownload(date);
|
||
};
|
||
|
||
return (
|
||
<>
|
||
{modalContextHolder}
|
||
<NasaDownloadView
|
||
cutoffDate={cutoffDate}
|
||
loading={loading}
|
||
bodies={bodies}
|
||
selectedBodies={selectedBodies}
|
||
dateRange={dateRange}
|
||
loadingDates={loadingDates}
|
||
downloading={downloading}
|
||
deleting={deleting}
|
||
downloadProgress={downloadProgress}
|
||
activeBodyForCalendar={activeBodyForCalendar}
|
||
viewingDateData={viewingDateData}
|
||
loadingDateData={loadingDateData}
|
||
onBodySelect={handleBodySelect}
|
||
onTypeSelectAll={handleTypeSelectAll}
|
||
onDateRangeChange={handleDateRangeChange}
|
||
onDelete={handleDelete}
|
||
onDownload={() => void handleDownload()}
|
||
onActiveBodyChange={setActiveBodyForCalendar}
|
||
onCalendarDateClick={(date) => void handleCalendarDateClick(date)}
|
||
onDateCellRender={dateCellRender}
|
||
onCloseDateData={() => setViewingDateData(null)}
|
||
disabledDate={(date) => date.isAfter(dayjs(), 'day')}
|
||
/>
|
||
</>
|
||
);
|
||
}
|