import { asyncRouterMap, constantRouterMap } from '@/router'
import { getUserRolesPermissions } from '@/api/login'
import Storage from '@/utils/storage'
import tagsView from './tagsView'
import router from '@/router';
const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: [],
    routersAlls: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      console.log( state.addRouters);
      state.routers = constantRouterMap.concat(routers)
    },
    SET_ROUTERS_ALL: (state, routers) => {
      state.routersAlls = routers
    }
  },
  actions: {
    GenerateRoutes({ commit, dispatch }) {
      let user = Storage.getItem('admin_user')
      if (!user) return Promise.reject()
      user = JSON.parse(user)
      let role_id = user.role_id
      if (user.founder === 1) role_id = 0
      return new Promise((resolve, reject) => {
        if (role_id === 0) {
          commit('SET_ROUTERS_ALL', ['*:*:*'])
          commit('SET_ROUTERS', asyncRouterMap)
          resolve()
        } else {
          getUserRolesPermissions(role_id).then(response => {
            let accessedRouters = filterRoleRouter(asyncRouterMap, response)
            commit('SET_ROUTERS_ALL', response)
            commit('SET_ROUTERS', accessedRouters)
            resolve()
          }).catch(reject)
        }
      })
    }
  }
}

/**
 * 递归筛选出有权限的路由
 * @param routers
 * @param names
 * @returns {Array}
 */
function filterRoleRouter(routers, names) {
  const _routers = []
  const newNames = []
  names.forEach(child => {
    // 将接口返回权限数据转为驼峰格式 用于路由判断
    if (child.split(':')[1]) {
      let str = child.split(':')[1]
      str = str.replace(str[0], str[0].toUpperCase())
      // 补充详情页面路由权限
      const detailChild = `${child.split(':')[0]}Detail`
      if (!newNames.includes(detailChild)) {
        newNames.push(detailChild)
      }
      child = `${child.split(':')[0]}${str}`
    }
    newNames.push(child)
  })
  routers.forEach(item => {
    if (newNames.includes(item.name)) {
      if (item.children) {
        item.children = filterRoleRouter(item.children, names)
      }
      _routers.push(item)
    }
  })
  return _routers
}

export default permission
