import router, { constantRoutes } from '@/router'
import { user_power } from '@/api/user/user'
import { getALLRouter } from '@/utils'

const state = {
  routes: [],
  addRoutes: [],
  // 存储home页区块路由，下拉选项路由
  roleData: {},
  opts: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_ROLE_DATA: (state, data) => {
    state.roleData = data
  },
  SET_OPTS: (state, opt) => {
    state.opts = opt
  },
  RESET_STATE: (state) => {
    state.routes = []
    state.addRoutes = []
    state.roleData = {}
    state.opts = []
  }
}

const actions = {
  generateRoutes({ commit }) {
    return new Promise((resolve, reject) => {
      user_power().then(res => {
        const { asyncRoutes, option } = getALLRouter(res.data)
        commit('SET_OPTS', option)
        commit('SET_ROLE_DATA', res.data)
        commit('SET_ROUTES', asyncRoutes)
        router.addRoutes(asyncRoutes)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  }
}

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