import * as payOrderService from '../../../../services/cooperate/order/payOrder';
import { routerRedux } from 'dva/router';
import pathToRegexp from 'path-to-regexp';
import { dataUtils } from '@utils';

export default {
  namespace: 'payOrderDetail',
  state: {
    formData: {},
    mode: 'view',
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        const match = pathToRegexp('/cooperate/order/pyo/:id').exec(location.pathname);
        if (match) {
          dispatch({ type: 'updateState', payload: dataUtils.queryStringToJSON(location.search) || { from: '' } });
          dispatch({ type: 'querySingle', payload: { id: match[1] } });
        }
      });
    },
  },

  effects: {
    * querySingle({ payload }, { call, put }) {
      const data = yield call(payOrderService.getSingle, payload.id);
      if (data.success) {
        const formatter = (value) => {
          return value ? `${parseFloat(value).toFixed(2)}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',') : '';
        };

        data.data.payAmt = formatter(data.data.payAmt);
        data.data.netAmt = formatter(data.data.netAmt);
        yield put({
          type: 'updateState',
          payload: {
            formData: data.data,
          },
        });
      } else {
        throw data;
      }
    },

    * cancel({ payload }, { put }) {
      yield put(routerRedux.goBack());
    },

    * clean({ payload }, { call, put }) {
      yield put({
        type: 'updateState',
        payload: {
          formData: {},
          mode: 'view',
        },
      });
    },
  },

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

  },
};
