import { constantRoutes, routerMap } from '@/router'
import user from './user.js'
import request from '@/utils/request'
import el from 'element-ui/src/locale/lang/el'

// 将本地routerMap映射到ajax获取到的serverRouterMap;
function generateAsyncRouter(routerMap, serverRouterMap) {
  // console.log("111",serverRouterMap);
  serverRouterMap.forEach(function(item, index) {
    // console.log('item', item)
    // console.log(item.component);
    if (item.component == 'Layout') {
      item.component = routerMap[item.component]
    } else if (routerMap[item.component] == undefined) {
      item.hidden = false
      item.component = import('@/views/dashboard/index')
    } else {
      // console.log(item.component);
      // console.log(routerMap[item.component].component);
      if(routerMap[item.component].hidden){
        item.hidden = routerMap[item.component].hidden
      }

      item.component = routerMap[item.component].component
    }
    // console.log('item2', item)
    // console.log('routerMap', routerMap)
    if (item.children && item.children.length > 0) {
      generateAsyncRouter(routerMap, item.children)
    }
  })
  // console.log('serverRouterMap',serverRouterMap);
  return serverRouterMap
}

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  // console.log(routes)
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}
// 路由找不到返回404页面
const notFoundRouter = {
  path: '', redirect: '/404', hidden: true
}

const permission = {
  state: {
    routes: [],
    addRoutes: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    }
  },
  actions: {
    generateRoutes({ commit }, roles) {
      return new Promise(resolve => {
        let accessedRoutes
        // request({
        //   url: '/system/index',
        //   method: 'post'
        // }).then(response => {
        //   console.log(user);
        // var data = response.data.menus
        var data = user.state.menus
        // console.log('menus', data)
        var dataRouter = []
        for (var i = 0; i < data.length; i++) {
          var datas = data[i]
          var icon = ''
          if (datas.icon) {
            icon = datas.icon
          } else {
            icon = 'example'
          }
          var parentMenu = {
            path: '/' + datas.createTime,
            component: 'Layout',
            redirect: '',
            name: datas.route,
            meta: { title: datas.menuName, icon: icon },
            hidden: false,
            children: [],
            runKind: data.runKind,
            delphiPackage: data.delphiPackage,
            delphiParams: data.delphiParams
          }
          for (var j = 0; j < datas.children.length; j++) {
            var menuItem = datas.children[j]
            var path = ''
            if (menuItem.runKind === 1) {
              path = menuItem.delphiPackage
            } else {
              path = '#'
            }
            var childrenMenu = {
              path: menuItem.url ? menuItem.url : path,
              name: menuItem.route,
              component: menuItem.route ? menuItem.route : 'menu',
              meta: { title: menuItem.menuName, icon: '' },
              hidden: menuItem.visible ? false : true,
              children: [],
              runKind: menuItem.runKind,
              delphiPackage: menuItem.delphiPackage,
              delphiParams: menuItem.delphiParams
            }
            if (menuItem.children.length > 0) {
              for (var g = 0; g < menuItem.children.length; g++) {
                var Grandsons = menuItem.children[g]
                var GrandsonMenu = {
                  path: Grandsons.url ? Grandsons.url : '#',
                  name: Grandsons.route,
                  component: menuItem.route ? menuItem.route : 'menu',
                  hidden: Grandsons.visible ? false : true,
                  meta: { title: Grandsons.menuName, icon: '' },
                  runKind: Grandsons.runKind,
                  delphiPackage: Grandsons.delphiPackage,
                  delphiParams: Grandsons.delphiParams
                }
                childrenMenu.children.push(GrandsonMenu)
              }
            }
            parentMenu.children.push(childrenMenu)
          }
          // console.log(dataRouter);
          dataRouter.push(parentMenu)
          // dataRouter.push(notFoundRouter)
        }
        // console.log('dataRouter', dataRouter)
        var asyncRouterMap = generateAsyncRouter(routerMap, dataRouter)
        accessedRoutes = asyncRouterMap || []
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)

        // })

        // else {
        //   accessedRoutes = filterAsyncRoutes(asyncRouterMap, roles)
        // }
      })
    }
  }
}

export default permission
