/* eslint-disable */

import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

import indexLogin from './index/login'
import indexCamp from './index/camp'
import {
  getCam
} from "r/index/login";
import {
  Message
} from 'element-ui';
Vue.prototype.$message = Message;

Vue.use(VueRouter)



const routes = [{
    path: '/login',
    name: 'loginIndex',
    meta: {
      title: '登录'
    },
    component: () =>
      import('v/index/login/Index.vue'),
    children: [...indexLogin]
  },
  {
    path: '/',
    name: 'cerificateIndex',
    meta: {
      title: '营地报名'
    },
    // redirect: '/cerificate/signUp',
    component: () =>
      import('v/index/camp/Index.vue'),
    children: [...indexCamp]
  },
  {
    path: '/:code',
    name: 'recruit',
    meta: {
      title: '招生简章'
    },

    component: () =>
      import('v/index/recruit/Index.vue')
  },
  {
    path: "/404",
    name: "notFound",
    component: () =>
      import('v/index/notFound.vue'),
  }, {
    path: "*", // 此处需特别注意置于最底部
    redirect: "/404"
  }

]


const router = new VueRouter({
  mode: 'history',
  // base: process.env.BASE_URL,
  routes
})


const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

//   运用vue-router的错误处理函数 onError 捕获错误(当捕获到了Loading chunk {n} failed的错误时，重新渲染目标页面。)
router.onError((error) => {
  const pattern = /Loading chunk (\d)+ failed/g;
  const isChunkLoadFailed = error.message.match(pattern);
  // const targetPath = router.history.pending.fullPath;
  // 用路由的replace方法，并没有相当于F5刷新页面，失败的js文件并没有从新请求，会导致一直尝试replace页面导致死循环，
  // 而用 location.reload 方法，相当于触发F5刷新页面，虽然用户体验上来说会有刷新加载察觉，但不会导致页面卡死及死循环，从而曲线救国解决该问题
  if (isChunkLoadFailed) {
    location.reload();
    // router.replace(targetPath);
  }
})

function checkCam(code, cb) {
  if (!code) {
    Message({
      message: "请访问正确的营地链接地址",
      type: 'waring'
    });
    cb && cb(false);
    return false;
  }
  getCam(code).then((res) => {
    if (res.data.code != 200) {
      Message({
        message: "请访问正确的营地链接地址",
        type: 'waring'
      });
      cb && cb(false);
      return false;
    }
    code && window.localStorage.setItem("index-identity", code);
    // this.$message.success(res.data.message);
    let root = document.querySelector(":root");
    root.style.setProperty("--color", res.data.system_color);
    root.style.setProperty("--bk_pic", res.data.background_picture); //当前营地的背景图
    window.localStorage.setItem("bk_pic", res.data.background_picture);
    //当前营地logo
    window.localStorage.setItem("system_logo", res.data.system_logo);
    window.localStorage.setItem(
      "doubt_code",
      res.data.fill_individual_Invitationcode
    ); //是否填写邀请码
    window.localStorage.setItem(
      "doubt_info",
      res.data.fill_individual_information
    ); //是否填写个人资料
    window.localStorage.setItem(
      "doubt_check",
      res.data.audit_individual_information
    ); //是否审核个人资料
    store.state.info = res.data;
    cb && cb(true);
  }).catch(() => {
    cb && cb(false);
  })
}

router.beforeEach((to, from, next) => {
  let tokenKey = "index-token",
    toLogin = "/login",
    toRegister = "/register",
    toReset = "/reset"
  let token = localStorage.getItem(tokenKey);
  let code = false;
  document.title = to.meta.title;
  if (to.path == toLogin || to.path == toRegister || to.path == toReset) {
    // nextUrl = false;
    code = to.params.code ? to.params.code : to.query.code;
    checkCam(code, (res) => {
      if (res) {
        //检查登陆情况
        if(token){
          next("/"+code);
        }else {
          return next();
        }
      }
    });
  } else if (to.name == "recruit") {
    code = to.params.code;
    checkCam(code, (res) => {
      if (res) {
        return next();
      }

    });
  } else {
    if (!token) {
      return next(toLogin);
    } else {
      code = to.params.code ? to.params.code : to.query.code;
      checkCam(code, (res) => {
        if (res) {
          if(token){
            return next();
          }else {
            next("/"+code);
          }
        }
      });
    }
  }
  // return nextUrl ? next(nextUrl) : next();
})

// 页面跳转之后页面回滚到顶部
router.afterEach((to, from, next) => {
  // console.log(to,'to')

  window.scrollTo(0, 0)
});
export default router
