// redux状态初始化、切片
import { createSlice } from '@reduxjs/toolkit';
import {getCurrentUser, login, logout, setCurrentUser} from './thunks.js';
import {useInjectReducer} from "../../utils/@reduxjs/injectReducer";

export const initialState = {
  loggedInUser: null,
  loginLoading: false,
  touring:false,
  tourName:null,
  tabs:[{
    tab: '欢迎',
    key: '/welcome',
  }],
  pathname:null,
  // systemInfo: null,
  // setupLoading: false,
  // registerLoading: false,
  // saveProfileLoading: false,
  // modifyPasswordLoading: false,
  // oauth2Clients: [],
};

/**
 * dispatch(themeSlice.actions.changeTheme('dark'));
 */
const slice = createSlice({
  name: 'app',
  initialState,
  reducers: {
    setupTour(state, { payload }) {
      state.tourName = payload;
    },
    startTour(state, { payload }) {
      state.touring = payload;
    },
    updateTabs(state, { payload }) {
      state.tabs = payload;
    },
    updatePathname(state, { payload }) {
      state.pathname = payload;
    }
  },
  extraReducers: builder => {
    // login
    builder.addCase(login.pending, state => {
      state.loginLoading = true;
    });
    builder.addCase(login.fulfilled, (state) => {
      state.loginLoading = false;
    });
    builder.addCase(login.rejected, state => {
      state.loginLoading = false;
    });

    // logout
    builder.addCase(logout.fulfilled, state => {
      state.loggedInUser = null;
    });

    // getCurrentUser
    builder.addCase(getCurrentUser.fulfilled, (state, action) => {
      state.loggedInUser = action.payload;
    });

    // setCurrentUser
    builder.addCase(setCurrentUser.fulfilled, (state, action) => {
        state.loggedInUser = action.payload;
      },
    );
  },
});

/**
 * 暴露Action、reducer 用于测试用例
 */
export const { actions: appActions, reducer } = slice;

/**
 * 当dispatch此thunk时自动注入Reducer
 */
export const useAppSlice = () => {
  useInjectReducer({ key: slice.name, reducer: slice.reducer });
  return { actions: slice.actions };
};
