import Vue from 'vue';
import Router from 'vue-router';
import routes from './routes';
import store from '@/store';

import axios from 'axios';
console.log(routes);
Vue.use(Router);

let router = new Router({
  base: '/marketing/',
  routes,
  // scrollBehavior: () => ({ y: 0 })
  //使用keep-alive标签后部分安卓机返回缓存页位置不精确问题
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition && to.meta.keepAlive) {
      return savedPosition;
    }
    const layoutRight = document.querySelector('.layout-right');
    if (layoutRight) {
      layoutRight.scrollTo(0, 0);
    }
  }
});

router.beforeEach((to, from, next) => {
  // 获取是否限流
  let path = to.path;

  Object.keys(to.params).map(key => {
    path = path.replace(to.params[key], `:${key}`);
  });

  axios
    .get(`/api-plug/rate-limit?requestPath=${path}&enterpriseId=${store.state.marketing.enterpriseId}`)
    .then(limitRes => {
      // 这个接口不规范 不用封装的request
      // code: 0正常 1必填参数未填写 2限流
      if (limitRes.data.resultCode == 1) {
        store.commit('updateLimit', true); // 更新正在限流
        next({ path: '/limit' });
      } else {
        store.commit('updateLimit', false);
        if (to.path == '/limit') {
          next('/');
        }
        next();
      }
    })
    .catch(() => {
      next();
    });
});

export default router;
