/**
 * @description 路由拦截状态管理，目前两种模式：all模式与intelligence模式，其中partialRoutes是菜单暂未使用
 */
import Vue from 'vue'
import { asyncRoutes, constantRoutes, resetRouter } from '@/router'
import { getList, getSysInfo } from '@/api/router' // 路由接口 和路由信息
import { convertRouter, filterRoutes } from '@/utils/routes'
import { authentication, rolesControl } from '@/config'
import { isArray } from 'vue-plugin-utils'

function getRedirectUrl(redirectUrl, roules) {
  if (redirectUrl === undefined || redirectUrl === null) {
    redirectUrl = roules[0].children[0].component
  } else {
    roules = roules[0].children
    redirectUrl = roules[0].children[0].children[0]
    return getRedirectUrl(redirectUrl, roules)
  }
  return redirectUrl.substr(7)
}

const state = () => ({
  configs: {},
  routes: [],
  cachedRoutes: [],
  activeName: '',
})
const getters = {
  configs: (state) => state.configs,
  routes: (state) => state.routes,
  cachedRoutes: (state) => state.cachedRoutes,
  activeName: (state) => state.activeName,
}
const mutations = {
  /**
   * @description 系统设置
   * @param {*} state
   * @param {*} configs
   */
  setConfigs(state, configs) {
    state.configs = configs
  },
  /**
   * @description 多模式设置路由
   * @param {*} state
   * @param {*} routes
   */
  setRoutes(state, routes) {
    state.routes = routes
  },
  /**
   * @description 设置缓存Name数组
   * @param {*} state
   * @param {*} routes
   */
  setCachedRoutes(state, routes) {
    state.cachedRoutes = routes
  },
  /**
   * @description 修改Meta
   * @param {*} state
   * @param options
   */
  changeMenuMeta(state, options) {
    function handleRoutes(routes) {
      return routes.map((route) => {
        if (route.name === options.name) Object.assign(route.meta, options.meta)
        if (route.children && route.children.length)
          route.children = handleRoutes(route.children)
        return route
      })
    }

    state.routes = handleRoutes(state.routes)
  },
  /**
   * @description 修改 activeName
   * @param {*} state
   * @param activeName 当前激活菜单
   */
  changeActiveName(state, activeName) {
    state.activeName = activeName
  },
}
const actions = {
  /**
   * @description 多模式设置路由
   * @param {*} { commit }
   * @param mode
   * @returns
   */
  async setRoutes({ commit }, mode = 'none') {
    // 默认前端路由
    let routes = [...asyncRoutes]
    // 设置游客路由关闭路由拦截(不需要可以删除)
    const control = mode === 'visit' ? false : rolesControl
    // 设置后端路由(不需要可以删除)
    if (authentication === 'all') {
      const sys_res = await getSysInfo()
      console.log(sys_res);
      if (sys_res.status == 200) {
        commit('setConfigs', sys_res.data)
      }

      const { data } = await getList()
      const list = data
      if (!isArray(list) && list.length < 1)
        Vue.prototype.$baseMessage(
          '路由格式返回有误！',
          'error',
          false,
          'vab-hey-message-error'
        )
      let redirectUrl = list[0].children[0].children[0]
      redirectUrl = getRedirectUrl(redirectUrl, list)
      list.push({ path: '*', redirect: redirectUrl, meta: { hidden: true } })
      routes = convertRouter(list)
    }
    // 根据权限和rolesControl过滤路由
    const finallyRoutes = filterRoutes([...constantRoutes, ...routes], control)
    // 设置菜单所需路由
    commit('setRoutes', finallyRoutes)
    // 根据可访问路由重置Vue Router
    await resetRouter(finallyRoutes)
  },

  /**
   * @description 设置缓存Name数组
   * @param {*} { commit }
   * @param {*} routes
   */
  setCachedRoutes({ commit }, routes) {
    commit('setCachedRoutes', routes)
  },
  /**
   * @description 修改Route Meta
   * @param {*} { commit }
   * @param options
   */
  changeMenuMeta({ commit }, options = {}) {
    commit('changeMenuMeta', options)
  },
  /**
   * @description 修改 activeName
   * @param {*} { commit }
   * @param activeName 当前激活菜单
   */
  changeActiveName({ commit }, activeName) {
    commit('changeActiveName', activeName)
  },
  setConfigs: ({ commit }, configs) => {
    commit('setConfigs', configs)
  },
}
export default { state, getters, mutations, actions }
