import { asyncRoutes, constantRoutes } from '@/router'
import { getMenu } from '@/api/user'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

/**
 * Filter constant routes by checking meta.hidden
 * @param routes constantRoutes
 */
export function filterConstantRoutes(routes) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }

    // Filter out routes with meta.hidden: true
    if (tmp.meta && tmp.meta.hidden) {
      return
    }

    // Recursively filter child routes
    if (tmp.children) {
      tmp.children = filterConstantRoutes(tmp.children)
    }

    res.push(tmp)
  })

  return res
}

/**
 * Convert backend route data to Vue Router format
 * @param routeData
 */
export function convertToRoutes(routeData) {
  return routeData.map(item => {
    // Ensure the url exists, use default path if empty
    const path = item.url && item.url.trim() !== '' ? item.url.replace('/#', '') : `/default-path-${item.id}`

    const route = {
      path, // Path
      name: item.label || `route_${item.id}`, // Use id to generate unique name if label is empty
      component: resolve => require([`@/views${path}`], resolve), // Dynamically load component
      meta: {
        title: item.label || `Unnamed Route ${item.id}`, // Ensure title in meta
        icon: item.icon || 'default-icon', // Set default icon if not provided
        selected_icon : item.selected_icon || 'default-icon', //选中时候的icon
        hidden: item.hidden === '1'
      },
      children: []
    }

    // Ensure each child route has a unique key
    if (!route.name || route.name.trim() === '') {
      route.name = `route_${item.id}` // Use unique id as route name
    }

    // Recursively handle child routes
    if (item.children && item.children.length > 0) {
      route.children = convertToRoutes(item.children)
    }

    return route
  })
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    // Filter constantRoutes to exclude hidden ones
    const filteredConstantRoutes = filterConstantRoutes(constantRoutes)
    state.routes = filteredConstantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, token) {
    return new Promise((resolve, reject) => {
      getMenu(token).then(response => {
        const { data } = response
        let accessedRoutes

        // Convert backend route data to Vue Router format
        accessedRoutes = convertToRoutes(data)

        // Commit the routes to Vuex state
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

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