import * as bpmFaultsService from '../../services/sys/bpmFaults';

export default {
  namespace: 'bpmFaults',
  state: {
    list: [],
    total: 0,
    remark: '',
    modalVisible: false,
    currentItem: null,
  },

  subscriptions: {
    setup({ dispatch, history }) {
    },
  },

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

    * close({ payload }, { call, put, select }) {
      const { remark, currentItem } = yield select(({ bpmFaults }) => bpmFaults);
      const data = yield call(bpmFaultsService.closeFault, { id: currentItem, remark });
      if (data.success) {
        yield put({ type: 'query' });
        yield put({
          type: 'updateState',
          payload: {
            remark: '',
            modalVisible: false,
          },
        });
      } else {
        throw data;
      }
    },

    * clean({ payload }, { call, put }) {
      yield put({
        type: 'updateState',
        payload: {
          list: [],
          total: 0,
          remark: '',
          modalVisible: false,
        },
      });
    },
  },

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

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

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

    hideModal(state) {
      return {
        ...state,
        remark: '',
        modalVisible: false,
        currentItem: null,
      };
    }
  },
};
