import { asyncRouterMap, constantRouterMap, asynsingle } from '@/router'

const ret = {
  arr: [],
  pos(value) {
    return this.arr.indexOf(value)
  },
  setArr() {
    if (this.arr.length < 2) {
      return this.route()
    }
    if (this.pos('0') !== -1) {
      this.arr.splice(this.pos('0'), 1)
      this.arr.push('0')
    }
    if (this.pos('7') !== -1) {
      this.arr.splice(this.pos('7'), 1)
      if (this.pos('1') !== -1) {
        this.arr.splice(0, 1, '1', '7')
      } else {
        this.arr.unshift('7')
      }
    }
    return this.route()
  },
  route() {
    for (let i = 0; i < this.arr.length; i++) {
      if (asyncRouterMap[0][this.arr[i]]) {
        this.arr[i] = asyncRouterMap[0][this.arr[i]]
      }
    }
    return [...this.arr, ...asynsingle]
  }
}
const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = [...constantRouterMap, ...routers]
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        ret.arr = data.sort((par1, par2) => par1 - par2)
        const accessedRouters = ret.setArr()
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    }
  }
}

export default permission
