import {
  getMenus
} from '@/api/menu'
import {
  getToken
} from '@/utils/auth'
import {
  constantRoutes,
  dynamicRoutes
} from '@/router/index'

const getDefaultState = () => {
  return {
    token: getToken(),
    menuList: []
  }
}

const state = getDefaultState()

const mutations = {
  SET_MENUS: (state, menu) => {
    state.menuList = menu
  }
}
// 动态菜单还是定义在前端，后台只会返回有权限的菜单列表，通过遍历我们预先在路由表里定义好的菜单数据，没有的将对于菜单进行隐藏
export function generaMenu(routes, srvMenus) {
  for (let i = 0; i < routes.length; i++) {
    const routeItem = routes[i]
    var showItem = false
    for (let j = 0; j < srvMenus.length; j++) {
      const srvItem = srvMenus[j]
      // 前后端数据通过 url 属性来匹配
      if (routeItem.url !== undefined && routeItem.url === srvItem.url) {
        showItem = true
        routes[i]['hidden'] = false
        break
      }
    }
    if (showItem === false) {
      routes[i]['hidden'] = true
    }

    if (routeItem['children'] !== undefined && routeItem['children'].length > 0) {
      generaMenu(routes[i]['children'], srvMenus)
    }
  }
}

const actions = {

  getMenus({
    commit
  }) {
    return new Promise((resolve, reject) => {
      getMenus(state.token).then(response => {
        const {
          data
        } = response

        console.log(response)
        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const srvMenus = data
        let pushRouter = dynamicRoutes
        generaMenu(pushRouter, srvMenus)
        commit('SET_MENUS', constantRoutes.concat(pushRouter)) //将创建完成的路由表存在menuList中
        resolve(pushRouter)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

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