import * as instanceService from '../../services/sys/instances';

export default {
  namespace: 'instances',
  state: {
    list: [],
    total: 0,
    currentItem: {},
    modalVisible: false,
    mode: 'create',
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {
        if (location.pathname === '/sys/instances') {
        }
      });
    },
  },

  effects: {
    * query({ payload }, { call, put }) {
      const data = yield call(instanceService.query, payload);
      if (data.success) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.data.rows,
            total: data.data.total,
          },
        });
      } else {
        throw data;
      }
    },

    * getSingle({ payload }, { select, call, put }) {
      const details = yield select(({ instances }) => instances.list);
      const selected = details.filter(d => d.prcId === payload.id);
      yield put({
        type: 'showModal',
        payload: {
          currentItem: selected[0],
          mode: payload.mode,
        },
      });
    },

    * delete({ payload }, { call, put }) {
      const data = yield call(instanceService.remove, payload.ids[0]);
      if (data.success) {
        yield put({ type: 'query' });
      } else {
        throw data;
      }
    },

    * view({ payload }, { put }) {
      yield put({ type: 'hideModal' });
    },

    * hideModal({ payload }, { put }) {
      yield put({
        type: 'updateState',
        payload: {
          modalVisible: false,
          currentItem: {},
        },
      });
    },

  },

  reducers: {

    querySuccess(state, action) {
      const { list, total } = action.payload;
      return {
        ...state,
        list,
        total,
      };
    },

    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    showModal(state, action) {
      return { ...state, ...action.payload, modalVisible: true };
    },

  },
};
