import { queryInfo, updateInfo } from '../../services/common/personal';
import { message } from 'antd';

export default {
  namespace: 'userInfo',
  state: {
    formData: {},
  },

  subscriptions: {
    setup({ dispatch, history }) {
      dispatch({ type: 'query' });
    },
  },

  effects: {
    * query({ payload }, { put, call, select }) {
      const data = yield call(queryInfo, payload);
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            formData: data.data,
          },
        });
      } else {
        throw data;;
      }
    },
    * save({ payload }, { put, call, select }) {
      const { formData } = yield select(({ userInfo }) => userInfo);
      const data = yield call(updateInfo, formData);
      if (data.success) {
        message.success('操作成功');
      } else {
        throw data;;
      }
    },

  },

  reducers: {
    updateForm(state, { payload }) {
      const { key, value } = payload;
      const { formData } = state;
      const newFormData = Object.assign({}, formData);
      newFormData[key] = value;
      return {
        ...state,
        formData: newFormData,
      };
    },
    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
