import * as deployService from '@services/deploy/deploy';

export default {
  namespace: 'suppAccount',
  state: {
    accounts: [],
    total: 0,
    showUploadModal: false,
  },

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

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

    * syncSuppAccount({ payload }, { call, put }) {
      const data = yield call(deployService.syncSuppAccount);
      if (data.success) {
        yield put({ type: 'query' });
      } else {
        throw data;
      }
    },

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

    * syncPerformance({ payload }, { call, put }) {
      const data = yield call(deployService.syncPerformance);
      if (data.success) {
        console.log(data);
      } else {
        throw data;
      }
    },

    * clean({ payload }, { put }) {
      yield put({
        type: 'updateState',
        payload: {
          accounts: [],
          total: 0,
        },
      });
    },

  },

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

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

    showUploadModal(state, action) {
      return { ...state, showUploadModal: action.payload };
    },

  },

};
