import { Effect, Reducer } from 'umi';

import { queryCurrent, query as queryUsers} from '@/services/user';

export interface CurrentUser {
  avatar?: string;
  token?: string;
  userid?: string;
  name?: string;
  permission?: [];
}


export interface UserModelState {
  currentUser?: CurrentUser;
}

export interface UserModelType {
  namespace: 'user';
  state: UserModelState;
  effects: {
    fetch: Effect;
    fetchCurrent: Effect;
    deleteCurrent: Effect;
  };
  reducers: {
    saveCurrentUser: Reducer<UserModelState>;
    deleteCurrentUser:Reducer<UserModelState>;
    changeNotifyCount: Reducer<UserModelState>;
  };
}

const UserModel: UserModelType = {
  namespace: 'user',

  state: {
    currentUser: {},
  },

  effects: {


    *fetch(_, { call, put }) {

      console.log(call)
      // const response = yield call(queryUsers);
      // console.error(response)
      // yield put({
      //   type: 'save',
      //   payload: response,
      // });
    },
    *fetchCurrent({ playload }, { call, put }) {
      console.log("response")
      const response = yield call(queryCurrent,playload);
      console.log(response)
      yield put({
        type: 'saveCurrentUser',
        payload: response,
      });
    },
    *deleteCurrent({playload}, { call, put }) {
      yield put({
        type: 'deleteCurrentUser',
      });
    },
  },

  reducers: {
    saveCurrentUser(state, action) {
      return {
        ...state,
        currentUser: action.payload || {},
      };
    },
    deleteCurrentUser(state, action) {
      return {
        ...state,
        currentUser: {},
      };
    },
    changeNotifyCount(
      state = {
        currentUser: {},
      },
      action,
    ) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload.totalCount,
          unreadCount: action.payload.unreadCount,
        },
      };
    },
  },
};

export default UserModel;
