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

const getCurrentUser = fetch(apis.user.current);

const UserModel = {
  namespace: 'user',
  state: {
    currentUser: {},
    menuList: [],
    buttonList: [],
  },
  effects: {
    *fetchCurrent(_, { call, put }) {
      try {
        const response = yield call(getCurrentUser);

        yield put({
          type: 'saveCurrentUser',
          payload: response,
        });
      } catch (err) {
        console.error(err);
      }
    },
    *fetchOrganization(payload, { call, put }) {
      console.log('-------');
      try {
        // const response = yield call(getCurrentUser);

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

      setAllBtnAuth(buttonList);
      setUserBtnAuth(currentUser.buttons);

      setAuthority(currentUser.roles);

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