import { ReduxAction, ReduxSagaEffects } from '@interfaces';
import * as usersService from '@services/sys/users';

export default {
  namespace: 'entUserModel',
  state: {
    list: [],
    total: 0,
    filterParams: {},
  },

  effects: {
    * query({ payload }: ReduxAction, { call, put, select }: ReduxSagaEffects) {
      const { filterParams } = yield select(({ entUserModel }) => entUserModel);
      const data = yield call(usersService.queryEntUsers, { ...filterParams, ...payload });
      if (data.success) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.data.rows,
            total: data.data.total,
            filterParams: { ...filterParams, ...payload },
          },
        });
      } else {
        throw data;
      }
    },

    * getSingle({ payload }: ReduxAction, { put }: ReduxSagaEffects) {
      if (payload.mode === 'create') {
        yield put({
          type: 'users/showModal',
          payload: {
            mode: payload.mode,
          },
        });
      } else {
        yield put({ type: 'users/querySingle', payload });
      }
    },

    * disable({ payload }: ReduxAction, { call, put }: ReduxSagaEffects) {
      const data = yield call(usersService.disable, payload.id);
      if (data.success) {
        yield put({ type: 'query' });
      } else {
        throw data;
      }
    },

    * enable({ payload }: ReduxAction, { call, put }: ReduxSagaEffects) {
      const data = yield call(usersService.enable, payload.id);
      if (data.success) {
        yield put({ type: 'query' });
      } else {
        throw data;
      }
    },

    * clean({ payload }: ReduxAction, { call, put }: ReduxSagaEffects) {
      yield put({
        type: 'updateState',
        payload: {
          list: [],
          total: 0,
          filterParams: {},
        },
      });
    },

  },

  reducers: {
    querySuccess(state: object, action: ReduxAction) {
      const { list, total, filterParams } = action.payload;
      return {
        ...state,
        list,
        total,
        filterParams,
      };
    },

    updateState(state: object, { payload }: ReduxAction) {
      return {
        ...state,
        ...payload,
      };
    },

  }
};
