import { fetch, apis } from '@/utils/request';
import { setAllBtnAuth, setUserBtnAuth } from '@/components/AuthButton';

const getCurrentUser = fetch(apis.user.current)

const UserModel = {
  namespace: 'user',
  state: {
    currentUser: {},
    menuList: [],
    buttonList: [],
  },
  effects: {
    // *fetch(_, { call, put }) {
    //   const response = yield call(queryUsers);
    //   yield put({
    //     type: 'save',
    //     payload: response,
    //   });
    // },

    *fetchCurrent(_, { call, put }) {
      const response = yield call(getCurrentUser);

      yield put({
        type: 'saveCurrentUser',
        payload: response,
      });
    },
  },
  reducers: {
    saveCurrentUser(state, { payload }) {
      const { taUser = {} , menuList = [], buttonList = [] } = payload || {}
      const currentUser = { ...taUser, roles: (taUser.roles || []).map(x => x.roleId) }

      setAllBtnAuth(buttonList)
      setUserBtnAuth(currentUser.buttons)

      return { ...state, currentUser, menuList, buttonList };
    },
    changeNotifyCount(
      state = {
        currentUser: {},
      },
      action,
    ) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload.totalCount,
          unreadCount: action.payload.unreadCount,
        },
      };
    },
  },
};
export default UserModel;
