import { constantRoutes } from '@/router'
import { validatenull } from '@/utils/validate'
import { postJson } from '@/api/common'
import Layout from '@/layout'
import Cookies from 'js-cookie'

function buildRouter(aMenu) {
  const aRouter = []
  aMenu.forEach(item => {
    if (!validatenull(item.component)) {
      const oRouter = {
        meta: { 'title': '', 'icon': '' },
        children: []
      }
      if (item.component !== 'Iframe') {
        if (item.component === 'Layout') {
          oRouter.component = Layout
        } else {
          oRouter.component = require('@/views/' + item.component + '.vue').default
        }
          oRouter.name = item.path
          oRouter.id = item.id || null
        if (item.redirect !== '') {
          oRouter.redirect = item.redirect || null
          oRouter.path = '/' + item.path
        } else {
          oRouter.path = item.path
        }
        oRouter.meta.icon = item.icon
        oRouter.meta.title = item.title
        oRouter.meta.noCache = true
        if(item.menu_type == 1){
          oRouter.children = validatenull(item.children) ? [] : buildRouter(item.children)
          aRouter.push(oRouter)
        }
      }
    }
  })
  return aRouter
}



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

const state = {
  routes: [],
  addRoutes: [],
  data1: {
    name: 'getmenu',
    idname: 'id',
    parammaps: { id: -1 }
  }
}

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 url = 'api/v1/system/user/permissions'
      let data = {}
      postJson(url,data).then(response => {
        if(response.code == 200){
          sessionStorage.setItem('buttonList', JSON.stringify(response.data.menu_buttons_path))   //所有按钮
          sessionStorage.setItem('pastureList', JSON.stringify(response.data.pasture_list))       //所属牧场
          if(response.data.pasture_list.length>0){
            Cookies.set('pastureId', response.data.pasture_list[0].id)
          }else{
            Cookies.set('pastureId', 0)
          }
          const menus = response.data.menu_list
          if (menus.length === 0) {
            reject('menus data is null')
          }
          const accessedRoutes = buildRouter(menus)

          accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
          sessionStorage.setItem('menuList', JSON.stringify(accessedRoutes))
          commit('SET_ROUTES', accessedRoutes)
          resolve(accessedRoutes)
        }else{
          const menus  = []
          if (menus.length == 0) {
            reject('当前用户角色未分配页面权限，无法登录')
          }
          const accessedRoutes = buildRouter(menus)
          accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
          commit('SET_ROUTES', accessedRoutes)
          resolve(accessedRoutes)
        }
      })
    })
  }
}

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