import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'; import { fetchBodyParts, BodyPart, BodyPartParams } from '../API/bodyPart'; import { AxiosError } from 'axios'; import { setCurrentPatientType } from './patientTypeSlice'; interface BodyPartState { items: BodyPart[]; loading: boolean; error: string | null; byPatientType: BodyPart[]; } const initialState: BodyPartState = { items: [], loading: false, error: null, byPatientType: [], }; export const getBodyParts = createAsyncThunk( 'bodyPart/getBodyParts', async ( { params, token }: { params: BodyPartParams; token: string }, { rejectWithValue } ) => { try { const data = await fetchBodyParts(params, token); return data; } catch (err: unknown) { let errorMessage = 'Failed to fetch body parts'; console.log(errorMessage); if ( err && typeof err === 'object' && 'message' in err && typeof (err as AxiosError).message === 'string' ) { errorMessage = (err as AxiosError).message; } return rejectWithValue(errorMessage); } } ); const bodyPartSlice = createSlice({ name: 'bodyPart', initialState, reducers: { // setBodyPartsByPatientType: (state, action: PayloadAction<{ patientTypeId: string }>) => { // // state.byPatientType[action.payload.patientTypeId] = action.payload.bodyParts; // }, }, extraReducers: (builder) => { builder .addCase(setCurrentPatientType, (state, action) => { console.log( '当前 patient type 变化-- bodyPart接收到信号:', action.payload ); if (action.payload) { const patientTypeId = action.payload.patient_type_id; console.log( '基于 patient type过滤 bodyPart byPatientType:', patientTypeId ); state.byPatientType = state.items.filter( (item) => item.patient_type === patientTypeId ); console.log('过滤后的 bodyPart byPatientType:', state.byPatientType); } }) .addCase(getBodyParts.pending, (state) => { state.loading = true; state.error = null; }) .addCase(getBodyParts.fulfilled, (state, action) => { state.loading = false; state.items = action.payload; }) .addCase(getBodyParts.rejected, (state, action) => { state.loading = false; state.error = action.payload as string; }); }, }); export default bodyPartSlice.reducer;