87 lines
2.6 KiB
TypeScript
87 lines
2.6 KiB
TypeScript
import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
|
|
import { CircumferenceAnalysisData, CircumferencePeriod, getCircumferenceAnalysis } from '@/services/circumferenceAnalysis';
|
|
|
|
export type CircumferenceState = {
|
|
data: Record<CircumferencePeriod, CircumferenceAnalysisData[]>;
|
|
loading: Record<CircumferencePeriod, boolean>;
|
|
error: string | null;
|
|
lastFetch: Record<CircumferencePeriod, number>;
|
|
};
|
|
|
|
const initialState: CircumferenceState = {
|
|
data: {
|
|
week: [],
|
|
month: [],
|
|
year: [],
|
|
},
|
|
loading: {
|
|
week: false,
|
|
month: false,
|
|
year: false,
|
|
},
|
|
error: null,
|
|
lastFetch: {
|
|
week: 0,
|
|
month: 0,
|
|
year: 0,
|
|
},
|
|
};
|
|
|
|
// 获取围度分析数据
|
|
export const fetchCircumferenceAnalysis = createAsyncThunk(
|
|
'circumference/fetchAnalysis',
|
|
async (period: CircumferencePeriod, { rejectWithValue }) => {
|
|
try {
|
|
const data = await getCircumferenceAnalysis(period);
|
|
return { period, data };
|
|
} catch (error: any) {
|
|
return rejectWithValue(error?.message || '获取围度分析数据失败');
|
|
}
|
|
}
|
|
);
|
|
|
|
const circumferenceSlice = createSlice({
|
|
name: 'circumference',
|
|
initialState,
|
|
reducers: {
|
|
clearError: (state) => {
|
|
state.error = null;
|
|
},
|
|
},
|
|
extraReducers: (builder) => {
|
|
builder
|
|
.addCase(fetchCircumferenceAnalysis.pending, (state, action) => {
|
|
const period = action.meta.arg;
|
|
state.loading[period] = true;
|
|
state.error = null;
|
|
})
|
|
.addCase(fetchCircumferenceAnalysis.fulfilled, (state, action) => {
|
|
const { period, data } = action.payload;
|
|
state.loading[period] = false;
|
|
state.data[period] = data;
|
|
state.lastFetch[period] = Date.now();
|
|
})
|
|
.addCase(fetchCircumferenceAnalysis.rejected, (state, action) => {
|
|
const period = action.meta.arg;
|
|
state.loading[period] = false;
|
|
state.error = action.payload as string;
|
|
});
|
|
},
|
|
});
|
|
|
|
export const { clearError } = circumferenceSlice.actions;
|
|
|
|
// Selectors
|
|
export const selectCircumferenceData = (state: { circumference: CircumferenceState }, period: CircumferencePeriod) =>
|
|
state.circumference.data[period];
|
|
|
|
export const selectCircumferenceLoading = (state: { circumference: CircumferenceState }, period: CircumferencePeriod) =>
|
|
state.circumference.loading[period];
|
|
|
|
export const selectCircumferenceError = (state: { circumference: CircumferenceState }) =>
|
|
state.circumference.error;
|
|
|
|
export const selectLastFetch = (state: { circumference: CircumferenceState }, period: CircumferencePeriod) =>
|
|
state.circumference.lastFetch[period];
|
|
|
|
export default circumferenceSlice.reducer; |