import { asyncRoutes, constantRoutes } from '@/router'
import { getUserMenus } from '@/api/router'
import user from './user'
import { Message } from 'element-ui'
import Layout from '@/layout'
import Empty from '@/layout/Empty'
import store from '@/store'

/**
 * 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
  }
}

/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * @param routes
 */
export function generaMenu(routes, data, curPath = '') {
  let iconName = ''
  data.forEach(item => {
    if (item.title === '信用评价') {
      iconName = 'dict'
    } else if (item.title === '信用修复') {
      iconName = 'dashboard'
    } else if (item.title === '信用惩戒') {
      iconName = 'form'
    } else if (item.title === '信用风险分类监管') {
      iconName = 'example'
    } else if (item.title === '联合惩戒') {
      iconName = 'link'
    } else if (item.title === '市场所协同') {
      iconName = 'nested'
    } else if (item.title === '总局一体化平台') {
      iconName = 'druid'
    } else if (item.title === '数据勘误') {
      iconName = 'tree'
    } else if (item.title === '系统管理') {
      iconName = 'user'
    } else if (item.title === '年报管理') {
      iconName = 'template'
    } else {
      iconName = 'default'
    }
    let component = () => import('@/views/iframe/index')
    if (item.children && item.children.length > 0) {
      if (item.level === 1) {
        component = Layout
      } else {
        component = Empty
      }
    }
    const menu = {
      path: (curPath === '/' ? '' : curPath) + item.path,
      component,
      redirect: !item.pid ? (curPath === '/' ? '' : curPath) + item.path + (item.children.length > 0 ? item.children[0].path : '') : '',
      children: [],
      name: item.path,
      meta: { title: item.title, id: item.sysMenuId, icon: iconName }
    }
    if (item.children) {
      generaMenu(menu.children, item.children, menu.path)
    }
    routes.push(menu)
  })
}

/**
 * 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
}

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

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise((resolve, reject) => {
      // let accessedRoutes
      // console.log('222', roles)
      // roles = ['admin']
      // if (roles.includes('admin')) {
      //   // 假如是admin则表示所有页面都可以访问，可自定义，可要可不要。
      //   accessedRoutes = asyncRoutes || []
      // } else {
      //   accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      //   console.log(',111', accessedRoutes)
      // }
      // commit('SET_ROUTES', accessedRoutes)
      // resolve(accessedRoutes)
      const loadMenuData = []
      const data = {
        userId: user.state.keys
      }
      // 先查询后台并返回左侧菜单数据并把数据添加到路由
      getUserMenus(data).then(response => {
        let data = response
        if (response.code !== 0) {
          Message.warning('获取用户菜单失败')
          store.dispatch('user/logout').finally(() => {
            reject()
          })
        } else {
          data = response.data.filter((item) => {
            return item.path
          })
          Object.assign(loadMenuData, data)
          generaMenu(asyncRoutes, loadMenuData)
          console.log('动态路由', asyncRoutes)
          let accessedRoutes
          roles = ['admin']
          if (roles.includes('admin')) {
            accessedRoutes = asyncRoutes || []
          } else {
            accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
          }
          commit('SET_ROUTES', accessedRoutes)
          resolve(accessedRoutes)
        }
        // generaMenu(asyncRoutes, data)
      }).catch(error => {
        console.log(error)
      })
    })
  }
}

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