import Vue from 'vue';
import iView from 'iview';
import axios from 'axios';
import VueRouter from 'vue-router';
import routes from './routes';
import { getToken } from 'service/auth';

Vue.use(iView);
Vue.use(VueRouter);

const scrollBehavior = (to, from, savedPosition) => {
  if (savedPosition) {
    return savedPosition;
  } else {
    return { x: 0, y: 0 };
  }
};

// 路由配置
const router = new VueRouter({
  mode: 'history',
  base: __dirname,
  routes,
  scrollBehavior
});

router.beforeEach((to, from, next) => {
  iView.LoadingBar.start();
  // pageTitle(to.meta.title);

  // 判断是否需要登录才能访问
  if (to.matched.some(record => record.meta.auth)) {
    if (getToken()) {
      next();
    } else {
      next({ name: 'Login', query: { redirect: encodeURIComponent(to.fullPath) } });
    }
  } else {
    // 已经登录且前往的是登录页,跳转到首页去
    if (getToken() && to.name == 'Login') {
      next({ name: 'Home' });
    } else {
      next();
    }
  }

  // 进入页面，取消前页面的axios请求
  if (window._source) {
    window._source.cancel();
  }

  // 设置每个页面axios取消请求配置
  window._source = axios.CancelToken.source();
});

router.afterEach((to, from, next) => {
  iView.LoadingBar.finish();
  window.scrollTo(0, 0);
});

export default router;
