import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index.js'
import Index from '@/views/Index'
import {
  makeMap
} from '@/common/util.js';

Vue.use(VueRouter)

let IndexRoutePath = '/FactoryMonitoring'; // 首页即('/')跳转的页面路径，默认为机组监测，如果用户的角色没有这个页面的权限，会改为用户权限里的第一个页面

// 普通路由，这里的路由为初始路由，不能有角色控制，后面的为角色路由，角色字段为role，表示该数组内的角色都可以访问此路由，如果没有角色，则都可以访问
const normalRoutes = [{
  // 默认页
  path: '/',
}, {
  // 登录页
  path: '/login',
  name: 'Login',
  component: () => import('@/views/Login')
}, {
  // 电厂选择页
  path: '/factory',
  name: 'Factory',
  component: () => import('@/views/Factory')
}, {
  // 404
  path: '/404',
  name: '404',
  component: () => import('@/views/404')
}]

// 角色路由
const roleRoutes = [{
  // 全厂监测
  path: '/FactoryMonitoring',
  name: 'FactoryMonitoring',
  component: Index,
  redirect: '/FactoryMonitoring/index',
  children: [{
    path: 'index',
    component: () => import('@/views/FactoryMonitoring'),
  }]
}, {
  // 机组监测
  path: '/CrewMonitoring',
  name: 'CrewMonitoring',
  component: Index,
  redirect: '/CrewMonitoring/index',
  children: [{
    path: 'index',
    component: () => import('@/views/CrewMonitoring'),
  }]
}, {
  // 全厂数据一览
  path: '/FactoryInfo',
  name: 'FactoryInfo',
  component: Index,
  redirect: '/FactoryInfo/index',
  children: [{
    path: 'index',
    component: () => import('@/views/FactoryInfo'),
  }]
}, {
  // 趋势分析
  path: '/TrendAnalysis',
  name: 'TrendAnalysis',
  component: Index,
  redirect: '/TrendAnalysis/index',
  children: [{
    path: 'index',
    component: () => import('@/views/TrendAnalysis'),
  }]
}, {
  // 报警记录
  path: '/AlarmRecord',
  name: 'AlarmRecord',
  component: Index,
  redirect: '/AlarmRecord/index',
  children: [{
    path: 'index',
    component: () => import('@/views/AlarmRecord'),
  }]
}, {
  // 用户管理
  path: '/UserManage',
  name: 'UserManage',
  component: Index,
  redirect: '/UserManage/index',
  children: [{
    path: 'index',
    component: () => import('@/views/UserManage'),
  }]
}, {
  // 角色管理
  path: '/RoleManage',
  name: 'RoleManage',
  component: Index,
  redirect: '/RoleManage/index',
  children: [{
    path: 'index',
    component: () => import('@/views/RoleManage'),
  }]
}]

// 匹配其他所有路由，必须放在最后添加到路由里，所以单独建了一个
const anyRoutes = [{
  path: '*',
  redirect: '/404'
}]

// 过滤掉角色相关路由
function filterRoute(routes, checkPermission) {
  let newRoute = [];
  if (checkPermission) {
    routes.forEach(i => {
      let tmp = { ...i
      };
      if (!tmp.name || checkPermission(tmp.name)) newRoute.push(tmp);
      if (tmp.children) tmp.children = filterRoute(tmp.children, checkPermission); // 过滤子路由
    })
  }
  return newRoute
}

// 初始化路由方法，返回新路由对象，只包含基础路由，不包含角色，角色路由应该在登录以后调用initRoleRoute方法动态添加
const createRouter = () => new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes: normalRoutes,
})

const router = createRouter();

// 重置角色路由
function initRoleRoute() {
  let newRoleRoutes = roleRoutes;
  // 过滤角色路由
  if (store.state.$x_user?.checkPermission) {
    newRoleRoutes = filterRoute(roleRoutes, store.state.$x_user.checkPermission);
    // 如果该角色没有机组监测页(CrewMonitoring),则把该角色的第一个权限页改为默认页
    if (newRoleRoutes.length && !newRoleRoutes.find(i => i.path == IndexRoutePath)) IndexRoutePath = newRoleRoutes[0].path;
  }
  normalRoutes[0].redirect = IndexRoutePath;
  const newRouter = createRouter(); // 新建路由
  router.matcher = newRouter.matcher; // 置换router
  router.addRoutes([...newRoleRoutes, ...anyRoutes]);
  // console.log('路由初始化完成', newRoleRoutes);
}

// 初始化用户、电厂、机组列表，从本地读取，如果都存在并未过期，返回undefined，否则返回1或2
function initLocal() {
  // 获取用户信息
  let user = JSON.parse(localStorage.getItem('electric_user'));
  let token = localStorage.getItem('electric_user_token');
  // if (!user || !token || user.endTime < Date.now()) return 1; // 如果没有用户和token，或者过期，说明未登录，则返回1，意味着需要跳转到登录页
  if (!user || !token) return 1; // 如果没有用户和token，说明未登录，则返回1，意味着需要跳转到登录页
  user.data.token = token; // 将token放入user里，方便全局取
  user.data.checkPermission = makeMap(user.data.permission); // 添加一个查询权限的参数
  store.commit('user', user.data);
  // 获取电厂信息
  let factoryList = JSON.parse(localStorage.getItem('electric_factoryList'));
  let factory = JSON.parse(localStorage.getItem('electric_factory'));
  // if (!factory || !factoryList || factory.endTime < Date.now()) return 2; // 如果没有电厂和设备列表，或者过期，说明未选择电厂，则返回2，意味着需要跳转到电厂选择页
  if (!factory || !factoryList) return 2; // 如果没有电厂和设备列表，说明未选择电厂，则返回2，意味着需要跳转到电厂选择页
  store.commit('factory', factory.data);
  store.commit('factoryList', factoryList.data);
  initRoleRoute();
}

// 如果没有用户则跳转到登录
router.beforeEach((to, from, next) => {
  // 如果是已登录,放行
  if (to.path === '/login' || (store.state.$x_user && store.state.$x_factory)) {
    next();
  } else if (to.path === '/factory' && store.state.$x_user) {
    next();
    // 如果未登录,检查本地用户，并且添加角色路由后放行
  } else {
    const res = initLocal();
    if (res == 1) {
      next('/login');
    } else if (res == 2) {
      next('/factory');
    } else {
      next({ ...to
      })
    }
  }
})

export default router
