import * as payOrderService from '../../../../services/cooperate/order/payOrder';
import { routerRedux } from 'dva/router';
import { stringUtils, enums } from '@utils';
const { entType } = enums;

export default {
  namespace: 'payOrder',
  state: {
    list: [],
    total: 0,
    currentItem: {},
    mode: 'view',
    supplier: {},
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === '/cooperate/order/pyo') {
          dispatch({ type: 'pageDataClean' });
        }
      });
    },
  },

  effects: {
    * query({ payload }, { call, select, put }) {
      const data = yield call(payOrderService.query, { ...payload });
      if (data.success) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.data.rows,
            total: data.data.total,
          },
        });
        yield put(routerRedux.replace({
          pathname: location.pathname,
          search: '?' + stringUtils.JSON2QueryString(payload),
        }));
      } else {
        throw data;
      }
    },

    * getSingle({ payload }, { put }) {
      const redirect = `/cooperate/order/pyo/${payload.id}?mode=${payload.mode}`;
      if (payload.mode === 'view') {
        yield put({
          type: 'updateState',
          payload: {
            mode: payload.mode,
          },
        });
        yield put(routerRedux.push(redirect));
      }
    },

    * pageDataClean({ payload }, { put, call, select, take }) {
      const { user } = yield select(({ app }) => app.user);
      yield put({
        type: 'updateState',
        payload: {
          supplier: {
            supplier: user.entType === entType.SUPP,
            suppName: user.name,
            docNo: stringUtils.queryURL('docNo'),
            docStatus: stringUtils.queryURL('docStatus'),
            suppCode: stringUtils.queryURL('suppCode'),
            ouCodeName: stringUtils.queryURL('ouCodeName'),
            docDateFrom: stringUtils.queryURL('docDateFrom'),
            docDateTo: stringUtils.queryURL('docDateTo'),
            payDateFrom: stringUtils.queryURL('payDateFrom'),
            payDateTo: stringUtils.queryURL('payDateTo'),
          },
        },
      });
    },

  },

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

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

  },
};
