// queryUsers
import { queryCurrent, homeInfo, apiBusinessDetail } from '@/services/user';
import localStorage from '@/utils/localStorage';
import sessionStorage from '@/utils/sessionStorage';

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

    *fetchCurrent(_, { call, put }) {
      const response = yield call(queryCurrent);
      if (response.code === 2000) {
        if (response.data && !response.data.name) {
          response.data.name = sessionStorage.get('account');
        }
        localStorage.set('user', JSON.stringify(response.data));
      }
      yield put({
        type: 'saveCurrentUser',
        payload: response.data,
      });
    },
    *fetchBusinessInfo(_, { call, put }) {
      const response = yield call(apiBusinessDetail);
      if (response.code === 2000) {
        localStorage.set('business-info', JSON.stringify(response.data));
      }
      yield put({
        type: 'saveCurrentBusiness',
        payload: response.data,
      });
    },
    *homeInfo(_, { call, put }) {
      const response = yield call(homeInfo);
      yield put({
        type: 'saveData',
        payload: {
          homeInfo: response.data,
        },
      });
    },
  },
  reducers: {
    saveCurrentUser(state, action) {
      return { ...state, currentUser: action.payload || {} };
    },
    saveCurrentBusiness(state, action) {
      return { ...state, businessInfo: action.payload || {} };
    },
    saveData(state, action) {
      const data = action.payload;
      return { ...state, ...data };
    },

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