import Vue from 'vue'
import Router from 'vue-router'
import routerData from './router'
import store from './../store/index'

Vue.use(Router)

const flatten = (parent, data) => {
  return data.reduce((acc, { path, name, component, MenuName, children }) => {
    const pth = [parent, path].join('/').replace('//', '/')
    const item = { path: pth, name, component, MenuName, children: [] }
    // console.log('children:', children)
    if (children && children.length) {
      return acc.concat(item, flatten(pth, children))
    }

    return acc.concat(item)
  }, [])
}

// route 数据, 展平二级路由
const routes = routerData.reduce((acc, r) => {
  const { children, ...rest } = r
  if (children && children.length) {
    return acc.concat({ ...rest, children: flatten('', children) })
  }

  return acc.concat(r)
}, [])

const router = new Router({
  routes,
  linkActiveClass: 'active',
})

router.beforeEach((to, from, next) => {
  store.commit('updateBread', { routerData, Url: to.name })
  next()
})

export default router
