import { create } from 'zustand'; import { api } from '@/lib/api'; import type { FlashProgress } from '@/types/device'; import { showApiError } from '@/lib/toast'; import { useActivityStore } from './activity-store'; // M4 fix: flash state 以 deviceId 區分,避免多裝置 UI 互相覆蓋。 // activeDeviceId 記錄當前正在 flash 的裝置,updateProgress 會比對確保不混。 interface FlashState { activeDeviceId: string | null; isFlashing: boolean; progress: FlashProgress | null; error: string | null; lastFlashParams: { deviceId: string; modelId: string } | null; startFlash: (deviceId: string, modelId: string) => Promise; updateProgress: (deviceId: string, progress: FlashProgress) => void; setError: (error: string) => void; retryFlash: () => Promise; reset: () => void; } export const useFlashStore = create((set, get) => ({ activeDeviceId: null, isFlashing: false, progress: null, error: null, lastFlashParams: null, startFlash: async (deviceId, modelId) => { set({ activeDeviceId: deviceId, isFlashing: true, progress: null, error: null, lastFlashParams: { deviceId, modelId } }); const res = await api.post(`/devices/${deviceId}/flash`, { modelId }); if (!res.success) { const errorMsg = res.error?.message || 'Flash failed'; showApiError(res.error); set({ isFlashing: false, error: errorMsg }); useActivityStore.getState().addActivity('flash_error', `Flash failed: ${errorMsg}`); } else { useActivityStore.getState().addActivity('flash_start', 'Flash started'); } }, updateProgress: (deviceId, progress) => { // M4 fix: 只更新對應裝置的 progress,忽略其他裝置的 WebSocket 訊息 if (get().activeDeviceId !== null && get().activeDeviceId !== deviceId) { return; } if (progress.error) { set({ isFlashing: false, error: progress.error }); useActivityStore.getState().addActivity('flash_error', `Flash failed: ${progress.error}`); return; } set({ progress }); if (progress.percent >= 100) { set({ isFlashing: false }); useActivityStore.getState().addActivity('flash_complete', 'Flash completed'); } }, setError: (error) => { set({ error, isFlashing: false }); }, retryFlash: async () => { const { lastFlashParams } = get(); if (!lastFlashParams) return; await get().startFlash(lastFlashParams.deviceId, lastFlashParams.modelId); }, reset: () => { set({ activeDeviceId: null, isFlashing: false, progress: null, error: null, lastFlashParams: null }); }, }));