/* 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 personalInfo from './index/personalInfo'
import {
  getCam,
  getCamInfo
} 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: '/Info',
    name: 'Info',
    meta: {
      title: '个人信息'
    },
    // redirect: '/cerificate/signUp',
    component: () =>
      import('v/index/Info/Index.vue'),
    children: [...personalInfo]
  },
  {
    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) {
  // console.log(code, 'code')
  // console.log(cb, 'cb')
  // const code=store.status.indexIdentity
  store.state.indexIdentity = code;
  // console.log(code, 'code11111')
  if (!code) {
    Message({
      message: "请访问正确的营地链接地址",
      type: 'waring'
    });
    cb && cb(false);
    return false;
  }

  getCam(code).then((res) => {
    // console.log(res)
    // if (res.data.code != 200) {
    //   Message({
    //     message: "请访问正确的营地链接地址",
    //     type: 'waring'
    //   });

    // if (res.data.code == 400034 || res.data.code == 400035 || res.data.code == 400001 || res.data.code == 400002 || res.data.code == 400003) {
    //   Message({
    //     message: res.data.message,
    //     type: 'waring'
    //   });
    //   cb && cb(false);
    //   return false;
    // }
    // }

    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" + code, res.data.background_picture);
    //当前营地logo
    window.localStorage.setItem("system_logo" + code, res.data.system_logo);
    window.localStorage.setItem(
      "doubt_code" + code,
      res.data.fill_individual_Invitationcode
    ); //是否填写邀请码
    window.localStorage.setItem(
      "doubt_info" + code,
      res.data.fill_individual_information
    ); //是否填写个人资料
    window.localStorage.setItem(
      "doubt_check" + code,
      res.data.audit_individual_information
    ); //是否审核个人资料
    store.state.info = res.data;
    cb && cb(true);
  }).catch(() => {
    cb && cb(false);
  })
}

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

    });
  } else {
    code = to.params.code ? to.params.code : to.query.code;
    let token = window.localStorage.getItem("index-token" + code);
    if (!token) {
      checkCam(code, (res) => {
        if (res) {
          return next(toLogin);
        }
      });
    } else {
      checkCam(code, (res) => {
        if (res) {
          if (token) {
            return next();
          } else {
            next("/" + code);
          }
        }
      });
    }
  }
})

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

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