import { constantRoutes } from '@/router'
import Layout from '@/layout'
import TrialsLayout from '@/views/trials/trials-layout'
// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap = [], lastRouter = false, type = false) {
  return asyncRouterMap.filter(route => {
    delete route.ParentId
    delete route.MenuId
    delete route.ApiPath
    if (route.Redirect) {
      route.redirect = route.Redirect
      delete route.Redirect
    }
    if (route.IsInTabDisplay) {
      route.tabHiddn = route.IsInTabDisplay
      delete route.IsInTabDisplay
    }
    if (route.MenuName) {
      route.name = route.MenuName
      delete route.MenuName
    }
    if (route.IsDisplay) {
      route.hidden = route.IsDisplay
      delete route.IsDisplay
    }
    if (route.Path) {
      route.path = route.Path
      if (route.IsExternalLink && ~route.Path.indexOf('http')) {
        route.path = route.Path
      } else if (route.IsExternalLink) {
        route.path = `${window.location.protocol}//${window.location.host}${route.Path}`
      } else {
        route.path = route.Path
      }
      delete route.Path
    }
    route.meta = { icon: route.MenuIcon }
    if (route.Meta) {
      // eslint-disable-next-line
      route.meta = eval('(' + route.Meta + ')')
      route.meta.icon = route.MenuIcon
      delete route.Meta
    }
    delete route.MenuIcon
    if (type && route.Children) {
      route.children = filterChildren(route.Children)
    }
    // Layout ParentView 组件特殊处理
    if (route.Component === '') {
      if (route.name === 'Trials') {
        route.component = TrialsLayout
      } else {
        route.component = Layout
      }
    } else {
      route.component = loadView(route.Component)
    }
    delete route.Component
    if (route.Children != null && route.Children && route.Children.length) {
      route.children = filterAsyncRouter(route.Children, route, type)
      delete route['Children']
    } else {
      delete route['Children']
      delete route['redirect']
    }
    return true
  })
}

function filterChildren(childrenMap, lastRouter = false) {
  var children = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView' && !lastRouter) {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + '/' + el.path
    }
    children = children.concat(el)
  })
  return children
}

export const loadView = (view) => {
  // if (process.env.NODE_ENV === 'development') {
  return (resolve) => require([`@/${view}.vue`], resolve)
  // } else {
  //   // 使用 import 实现生产环境的路由懒加载
  //   return () => import(`@/${view}`)
  // }
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
    // zzSessionStorage.setItem('Menus', JSON.stringify(state.routes))
  }
}

const actions = {
  generateRoutes({ commit }) {
    return new Promise(resolve => {
      var newTree = JSON.parse(zzSessionStorage.getItem('newTree'))
      const sidebarRoutes = filterAsyncRouter(newTree || [])
      commit('SET_ROUTES', sidebarRoutes)
      resolve(sidebarRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
