import router from './router'
import store from './store'
import {Message} from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {getToken, hasLogin} from '@/utils/auth' // getToken from cookie
import Layout from "@/views/layout/Layout";

NProgress.configure({showSpinner: false})// NProgress Configuration

// permission judge function
function hasPermission(perms, permissions) {
  if (perms.indexOf('*') >= 0) return true // admin permission passed directly
  if (!permissions) return true
  return perms.some(perm => permissions.indexOf(perm) >= 0)
}

const whiteList = ['/login', '/auth-redirect']// no redirect whitelist

console.log('check login and power');


router.beforeEach((to, from, next) => {
  // console.log(to);
  // console.log(1)
  // console.log(from);
  NProgress.start() // start progress bar
  if (getToken() && hasLogin()) { // determine if there has token
    /* has token*/
    if (to.path === '/login') {
      next('/dashboard')
      NProgress.done()
    } else {
      //   if (store.getters.perms.length === 0) {
      //   let list=[  {
      //     path: "/report",
      //     redirect: "login",
      //     alwaysShow: true,
      //     name: "userManage",
      //     meta: {
      //       title: "报表系统",
      //       icon: "people"
      //     },
      //     component: Layout,
      //     children: [
      //       {
      //         path: "collectData",
      //         name: "user",
      //         meta: {
      //           perms: ["GET /admin/user/list"],
      //           title: "服务gmv",
      //           noCache: true,
      //           icon: "user",
      //           keepAlive: true
      //         }
      //       },
      //       {
      //         path: "saleGmv",
      //         name: "address",
      //         meta: {
      //           perms: ["GET /admin/address/list"],
      //           title: "销售看板",
      //           noCache: true,
      //           icon: "tree",
      //           keepAlive: true
      //         }
      //       },
      //       {
      //         path: "businessData",
      //         name: "collect",
      //         meta: {
      //           perms: ["GET /admin/collect/list"],
      //           title: "招商看板",
      //           noCache: true,
      //           icon: "clipboard",
      //           keepAlive: true
      //         }
      //       },
      //       {
      //         path: "serviceAbilityDetail",
      //          meta: {
      //           perms: ["GET /admin/collect/list"],
      //           title: "服务力明细",
      //           noCache: true,
      //           icon: "clipboard",
      //           keepAlive: true
      //         }
      //       }

      //     ]
      //   },

      //   {
      //     path: "/jzmall/order",
      //     redirect: "noredirect",
      //     alwaysShow: true,
      //     name: "mallManage",
      //     meta: {
      //       title: "商场系统",
      //       icon: "shopping"
      //     },
      //     component: Layout,
      //     children: [
      //       {
      //         path: "order",
      //         name: "order",
      //         meta: {
      //           perms: [

      //           ],
      //           title: "订单管理",
      //           noCache: true,
      //           icon: "order",
      //           keepAlive: true
      //         }
      //       },
      //       {
      //         path: "schedulingP",
      //         name: "schedulingP",
      //         meta: {
      //           perms: [
      //             'POST /admin/workerOccupy/selectOccupyByQuery'
      //           ],
      //           title: "档期管理",
      //           noCache: true,
      //           icon: "form",
      //           keepAlive: true
      //         }
      //       },
      //       {
      //         path: "addressCheck",
      //         name: "addressCheck",
      //         meta: {
      //           perms: [
      //             'GET /admin/addressCheck/getCalendarStockByAddress'
      //           ],
      //           title: "服务区域查询",
      //           noCache: true,
      //           icon: "guide",
      //           keepAlive: true
      //         }
      //       },
      //     ]}
      //       ];
      //   router.addRoutes(list);
      //   store.state.user.perms=[1,2,3];
      //   next({ ...to, replace: true })
      // }else{
      //   next();
      // }
      console.log(6)
      console.log(store)
      if (store.getters.perms.length === 0) { // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetUserInfo').then(res => { // 拉取user_info
          console.log(res);
          // const perms = res.data.data.perms // note: perms must be a array! such as: ['GET /aaa','POST /bbb']
          // store.dispatch('GenerateRoutes', { perms }).then(() => { // 根据perms权限生成可访问的路由表
          //   router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
          //   next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
          // })
          let userSysMenu = res.data.data.userSysMenu;
          let menuList = [];

          //报表
          let reportMenu = [];
          if (userSysMenu.report.length > 0) {
            let reportMenuCur = userSysMenu.report[0].children;
            reportMenuCur.forEach(item => {
              let obj = JSON.parse(JSON.stringify(item));
              obj.path = "/report" + obj.path;
              obj.name = "/report" + obj.name;
              obj.component = Layout,
                reportMenu.push(obj);
            });
            console.log(4);
            console.log(reportMenu);
            menuList = menuList.concat(reportMenu);
          }

          //商城
          let mallMenu = [];
          if (userSysMenu.mallMenu.length > 0) {
            let mallMenuCur = userSysMenu.mallMenu[0].children;
            mallMenuCur.forEach(item => {
              let obj = JSON.parse(JSON.stringify(item));
              obj.path = "/jzmall" + obj.path;
              obj.name = "/jzmall" + obj.name;
              obj.component = Layout,
                mallMenu.push(obj);
            });
            console.log(mallMenu);
            menuList = menuList.concat(mallMenu);
          }

          //服务者
          let workerMenu = [];
          if (userSysMenu.servant.length > 0) {
            console.log(userSysMenu);
            let workerMenuCur = userSysMenu.servant[0].children;
            console.log(workerMenuCur);
            workerMenuCur.forEach(item => {
              let obj = JSON.parse(JSON.stringify(item));
              obj.path = "/worker" + obj.path;
              obj.name = "/worker" + obj.name;
              obj.component = Layout,
                workerMenu.push(obj);
              console.log(obj)
            });
            console.log(workerMenu);
            menuList = menuList.concat(workerMenu);
          }

          //客户crm
          let customerMenu = [];
          if (userSysMenu.cusCrmMenu.length > 0) {
            console.log(userSysMenu);
            let customerMenuCur = userSysMenu.cusCrmMenu[0].children;
            console.log(customerMenuCur);
            customerMenuCur.forEach(item => {
              let obj = JSON.parse(JSON.stringify(item));
              obj.path = "/customer" + obj.path;
              obj.name = "/customer" + obj.name;
              obj.component = Layout,
                customerMenu.push(obj);
              console.log(obj)
            });
            console.log(customerMenu);
            menuList = menuList.concat(customerMenu);
          }


          //动态设置路由
          store.state.user.user = {
            report: reportMenu,
            jzmall: mallMenu,
            worker: workerMenu,
            customer: customerMenu
          };
          // console.log('生成动态路由');
          // console.log(menuList);
          router.addRoutes(menuList);
          store.state.user.perms = [1, 2, 3];
          next({...to, replace: true});
        }).catch((err) => {
          store.dispatch('FedLogOut').then(() => {
            Message.error(err || 'Verification failed, please login again')
            next({path: '/'});
          })
        })
      } else {
        // 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓
        if (hasPermission(store.getters.perms, to.meta.perms)) {
          next()
        } else {
          next({path: '/401', replace: true, query: {noGoBack: true}})
        }
        // 可删 ↑
      }

    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})


router.afterEach(() => {
  NProgress.done() // finish progress bar
})
