import TabsView from '@/layouts/tabs/TabsView'
// import BlankView from '@/layouts/BlankView'
import PageView from '@/layouts/PageView'
// import { render } from 'nprogress'
import Vue from 'vue'
import Router from 'vue-router'
import Cookies from "js-cookie";
import store from '@/store'
// import { api } from "@/services/index"


Vue.use(Router)
// 路由配置
const router = new Router({
  routes: [
    {
      path: '/',
      name: '首页',
      component: TabsView,
      children: [
        // {
        //   path: '/home',
        //   name: '首页',
        //   component: () => import('@/pages/index/index')
        // },
        {
          path: '/financial/receivablesMessage',
          name: '每月详情',
          hidden: true,
          meta: { requiresAuth: true },

          component: () => import('@/pages/financial/receivablesMessage'),
        },
        {
          path: '/',
          name: '代理人统计',
          component: PageView,
          children: [
            {
              path: '/personnelManage/front/personnel/teammanage',
              name: '团队管理',
              hidden: true,
              meta: { requiresAuth: true },

              component: () => import('@/pages/personnelManage/front/teammanage'),

            },
            {
              path: '/personnelManage/front/task',
              name: '任务数据',
              hidden: true,
              meta: { requiresAuth: true },

              component: () => import('@/pages/personnelManage/front/task'),

            },
            {
              path: '/personnelManage/front/order',
              name: '订单数据',
              hidden: true,
              meta: { requiresAuth: true },

              component: () => import('@/pages/personnelManage/front/order'),

            }
          ]
        },
        {
          path: '/',
          name: '人力达标',
          component: PageView,
          children: [
            {
              path: '/personnelManage/front/resources/teammanage',
              name: '团队管理',
              hidden: true,
              meta: { requiresAuth: true },

              component: () => import('@/pages/personnelManage/front/teammanage'),

            },

          ]
        },
        {
          path: '/sales/message',
          name: '电销详情',
          hidden: true,
          meta: { requiresAuth: true },

          component: () => import('@/pages/sales/message'),

        },
        {

          path: '/verification',
          name: '费用校验',
          hidden: true,
          meta: { requiresAuth: true },

          component: PageView,
          children: [
            {
              path: '/verification/message',
              name: '费用校验详情',
              hidden: true,
              meta: { requiresAuth: true },

              component: () => import('@/pages/financial/verification/message'),
            }
          ]
        },


        {
          path: '/channel',
          name: '渠道人员统计',
          component: PageView,
          children: [
            {
              path: '/personnelManage/channel/message',
              name: '成员详情',
              hidden: true,
              meta: { requiresAuth: true },

              component: () => import('@/pages/personnelManage/channel/message'),

            },
            {
              path: '/personnelManage/channel/task',
              name: '任务数据',
              hidden: true,
              meta: { requiresAuth: true },

              component: () => import('@/pages/personnelManage/channel/task'),

            },
            {
              path: '/personnelManage/channel/order',
              name: '订单数据',
              hidden: true,
              meta: { requiresAuth: true },

              component: () => import('@/pages/personnelManage/channel/order'),

            }
          ]
        },
        {
          path: '/sales',
          name: '电销统计',
          component: PageView,
          children: [
            {
              path: '/personnelManage/sales/message',
              name: '成员详情',
              hidden: true,
              meta: { requiresAuth: true },

              component: () => import('@/pages/personnelManage/sales/message'),

            },
            {
              path: '/personnelManage/sales/task',
              name: '任务数据',
              hidden: true,
              meta: { requiresAuth: true },

              component: () => import('@/pages/personnelManage/sales/task'),

            },
            {
              path: '/personnelManage/sales/order',
              name: '订单数据',
              hidden: true,
              meta: { requiresAuth: true },

              component: () => import('@/pages/personnelManage/sales/order'),

            }
          ]
        },

        {
          path: '/business/sales/message',
          name: '保费详情',
          meta: { requiresAuth: true },

          component: () => import('@/pages/business/message'),
        },
        {
          path: '/business/agent/message',
          name: '保费详情',
          meta: { requiresAuth: true },

          component: () => import('@/pages/business/message'),
        },
        {
          path: '/business/channel/message',
          name: '保费详情',
          meta: { requiresAuth: true },

          component: () => import('@/pages/business/message'),
        },


      ]
    },
    {
      path: '/index',
      name: '首页',
      meta: { requiresAuth: true },
      component: () => import('@/pages/index/index')
    },

    {
      path: '/login',
      name: '登录页',
      meta: { requiresAuth: true },
      component: () => import('@/pages/login')
    },

    {
      path: '/403',
      name: '403',
      meta: { requiresAuth: true },
      component: () => import('@/pages/exception/403'),
    },

  ]
})
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
let hasRoles = true
router.beforeEach(async (to, from, next) => {
  // 登录界面登录成功之后，会把用户信息保存在会话
  // 存在时间为会话生命周期，页面关闭即失效。
  // let token = getToken()
  // let userName = sessionStorage.getItem('user')
  // let userName = Cookies.get('user')

  // if (to.path != from.path) {
  //   // next({ path: '/index' })
  // } else {
  //   next()
  // }

  await store.dispatch('setting/getUserLogin')


  let userInfo = store.state.setting.userInfo
  //console.log(to)
  // let token = Cookies.get('Authorization')

  if (!to.matched.some(record => record.meta.requiresAuth)) {
    next("/index")
    // next()
    // return

  }

  if (!userInfo.id) {
    // 如果访问非登录界面，且户会话信息不存在，代表未登录，则跳转到登录界面
    // next({ path: '/login' })
    alert("当前用户无权访问")
    window.location.href = process.env.VUE_APP_BASE_URL + "/#/login"

  } else {
    //加载动态菜单和路由
    // if()



    // for (let key in store.state.setting) {
    //   // console.log(key, store.state.setting[key])
    // }

    await store.dispatch('setting/getMenuList', userInfo.id)
    await store.dispatch('setting/getPermissionsAuth', userInfo.id)
    let menuData = store.state.setting.menuData

    let auth = store.state.setting.authType

    sessionStorage.setItem("user", userInfo.id);
    Cookies.set("user", userInfo.id);

    if (!auth) {
      alert("当前用户无权访问")
      window.location.href = process.env.VUE_APP_BASE_URL + "/#/login"
      return
    }
    // if (to.meta.requiresAuth)
    if (hasRoles) {
      // console.log(13)
      addDynamicMenuAndRoutes(menuData, to, next)
      hasRoles = false

      next({ to, replace: true })
    } else {
      next()

    }


    // const requiresAuth =router.getRoutes().some(record => record.meta.requiresAuth);
    // router.getRoutes().forEach((v) => {

    //   if (to.path === v.path) {
    //     // next({ to, replace: true })
    //     return
    //   } else {
    //     // next("/index")
    //   }
    // })





  }



})
/**
* 加载动态菜单和路由
*/
async function addDynamicMenuAndRoutes(menuData, to, next) {

  let menuRouteLoaded = store.state.app.menuRouteLoaded

  if (menuRouteLoaded) {

    next()
    return
  }
  // let userId = ""
  // await api.userService.getLoginUser().then((item) => {


  //   userId = item.data.code === 200 ? item.data.data.id : ''
  // })

  // await api.sysManage.getMenuList({ 'id': userId }).then(res => {
  // 添加动态路由
  // router.match = new Router({ ...router.options, routes: [] }).match

  let dynamicRoutes = addDynamicRoutes(menuData, to, next)
  router.options.routes[0].children = [].concat(dynamicRoutes);
  handleStaticComponent(router, dynamicRoutes)

  router.addRoute(...dynamicRoutes)



  // 保存加载状态
  store.commit('menuRouteLoaded', true)

  // 保存菜单树
  store.commit('setting/setMenuData', menuData)

  next();

  if (to.matched.length == 0) {

    router.push(to.path);

  }

}
/**
 * 处理路由到本地直接指定页面组件的情况
 * 比如'代码生成'是要求直接绑定到'Generator'页面组件
 */
function handleStaticComponent(router, dynamicRoutes) {
  for (let j = 0; j < dynamicRoutes.length; j++) {
    if (dynamicRoutes[j].name == '代码生成') {
      dynamicRoutes[j].component = ''
      break
    }
  }
  // console.log(router.options.routes[0], dynamicRoutes)
  router.options.routes[0].children = router.options.routes[0]?.children.concat(dynamicRoutes)
}

/**
* 添加动态(菜单)路由
* @param {*} menuList 菜单列表
* @param {*} routes 递归创建的动态(菜单)路由
*/
function addDynamicRoutes(menuList = [],) {
  // console.log(menuList)
  var temp = []
  // console.log(router)
  for (var i = 0; i < menuList.length; i++) {



    if (menuList[i].type == 0) {
      let mulu = {}
      mulu = {
        path: menuList[i].url,
        name: menuList[i].name,
        meta: {
          icon: menuList[i].icon,
          index: menuList[i].id,

        },
        component: PageView,

        children: []
      }
      temp.push(mulu)

      router.addRoute('首页', {
        path: menuList[i].url ? '/' + menuList[i].url : '',
        component: PageView,
        name: menuList[i].name,
        meta: {
          icon: menuList[i].icon,
          index: menuList[i].id,

        },
        children: []
      })



    } else if (menuList[i].type == 1) {

      let mulu = {}
      let url = menuList[i].url
      let parentPath = menuList[i].parentUrl

      mulu = {
        path: menuList[i].url,
        name: menuList[i].name,
        meta: { requiresAuth: true },

        // hidden: true,
        component: resolve => require([`@/` + `pages/${parentPath}/${url}`], resolve),

        // children: menuList[i].children instanceof Array && menuList[i].children.length ? addDynamicRoutes(menuList[i].children) : []
      }

      temp.push(mulu)

      router.addRoute(menuList[i].parentName, mulu)


    }
    if (menuList[i].children instanceof Array && menuList[i].children.length) {
      addDynamicRoutes(menuList[i].children)
    }





  }
  return temp

}


export default router
