import Vue from 'vue';
import { Store } from 'vuex';
import VueWait from 'vue-wait';

Vue.use(VueWait);

const wait = new VueWait({
  useVuex: true,
});

// 由于微信小程序的运行机制问题，需声明如下一行，H5和APP非必填
Vue.prototype.$wait = wait;

export const createVueWait = () => (store: Store<any>): void => {
  // 当 store 初始化后调用
  store.subscribeAction({
    // 发起一个action 之前会走这里
    before: (action) => {
      // console.log(`before action ${action.type}`, action);
      if (!action.type.startsWith('wait/')) {
        wait.start(action.type);
      }
    },
    // 发起一个action 之后会走这里
    after: (action) => {
      // console.log(`after action ${action.type}`, action);
      if (!action.type.startsWith('wait/')) {
        wait.end(action.type);
      }
    },
    error: (action) => {
      // console.log(`error action ${action.type}`, action);
      if (!action.type.startsWith('wait/')) {
        wait.end(action.type);
      }
    },
  });
};

export default wait;
