import {
  asyncRoutes,
  constantRoutes,
  resetRouter
} from '@/router'
import {
  getRoule
} from '@/model/indexRx'
import {
  clearStorage
} from '../../utils/auth'
/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param routes asyncRoutes
 * @param roles 传递参数-用户权限内容
 */
function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const currentRoute = {
      ...route
    }
    if (currentRoute.meta && currentRoute.meta.module) {
      const routeModule = currentRoute.meta.module
      // console.log(roles)
      if (roles.some(role => role.indexOf(routeModule) === 0)) {
        if (Array.isArray(currentRoute.children) && currentRoute.children.length > 0) {
          currentRoute.children = filterAsyncRoutes(currentRoute.children, roles)
        }
        res.push(currentRoute)
      }
    } else {
      res.push(currentRoute)
    }
  })
  // console.log(routes)
  return res
}

/**
 * 权限添加 日后优化
 * @param {*} roles
 * @param {*} res
 * @param {*} parentModule
 */
function handleRoles(roles, res, parentModule) {
  // console.log(roles, res, parentModule)
  roles.forEach((role) => {
    if (Array.isArray(role.children) && role.children.length > 0) {
      handleRoles(role.children, res, parentModule + role.name + '.')
    } else {
      const lastIndex = role.name.lastIndexOf('.')
      if (parentModule.indexOf(role.name.split('.')[0]) != -1) {
        res.push(`${parentModule}${role.name.substring(lastIndex + 1)}`)
      } else {
        res.push(`${parentModule}${role.name}`)
      }
    }
  })
}
const state = {
  routes: [],
  menu: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    const routerList = constantRoutes.concat(routes)
    // console.log(routerList)
    state.menu = leftMenu(routerList, {})
    state.routes = routerList
    // console.log(routerList)
  },
  SET_MENU: (state, menu) => {
    state.menu = menu
  }
}

const group = (routerChild = []) => {
  const groupChild = []
  routerChild.forEach(item => {
    const routerGroup = [
      item.path,
      ...group(item.children || [])
    ]
    groupChild.push(...routerGroup)
  })
  return groupChild.filter(item => item)
}
const formatUrl = (url = '') => {
  return url.replace(/\/\//g, '/')
}
/**
 * 获取左侧菜单列表 数据模型  供日后后台提供接口使用
 * @param {*} menuList 按权限区分出来的集合
 * @param {*} param1 {path=''} 父节点路径
 */
const leftMenu = (menuList, {
  path = ''
}) => {
  const res = []
  menuList.filter(item => !item.hidden).forEach(route => {
    // console.info(route, 'route.children')
    const currentRoute = {
      'alias': 'menu',
      'code': route.name,
      'name': route.meta ? route.meta.title : route.name,
      'path': formatUrl(path + (route.path.indexOf('/') > -1 ? '' : '/') + route.path),
      'source': route.meta ? `iconfont icon${route.meta.icon}` : '',
      'sort': 1,
      'category': 1,
      'isOpen': 1,
      'children': leftMenu(route.children || [], route),
      'hasChildren': false,
      'actionName': '',
      'isOpenName': '',
      'group': group(route.children || [])
    }
    res.push(currentRoute)
  })
  // console.info(JSON.stringify(res), 'luyou')
  return res
}

const actions = {
  generateRoutes({
    commit
  }) {
    return new Promise(async resolve => {
      const data = await getRoule().toPromise()
        .catch((err) => {
          clearStorage()
          resetRouter()
          window.location.href = 'https://test1.eliangeyun.com'
        })

      const roles = []
      handleRoles(data, roles, '')
      // console.log(roles)
      const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      commit('user/SET_ROLES', roles, {
        root: true
      })
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

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