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) => {
  console.log(parent)
  return data.reduce((acc, { path, name, component, title, children }) => {
    const pth = [parent, path].join('/').replace('//', '/')
    const item = { path: pth, name, component, title, 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)
}, [])

// console.log(routes)

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

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

export default router