import { asyncRoutes, constantRoutes } from '@/router'
import store from '../../store'
import Layout from '@/layout'
import ParentView from '@/components/ParentView'
import { functionObj } from "@/utils/functionObj";

function sortIndex(a, b) {
  return a.sort - b.sort
}
export function setRouterData() {
  let resourcesList = []

  if (store == undefined)
    return null
  //if(store.state.user.status){
  store.state.user.status = false
  let resources1 = store.state.user.resource
  let resources = []

  if (resources1) {
    resources1.forEach(item1 => {
      functionObj.forEach(item2 => {
        if ((item1.menuId == item2.id) && (item2.menuType.toLowerCase() == "menu")) {
          item1 = {
            parentId: item1.parentId,
            sort: item1.sort,
            remark: item1.menuName,
            menuType: item2.menuType,
            redirect: item2.redirect,

            id: item2.id,
            path: item2.router,
            name: item2.name,
            component: item2.component == "Layout" ? Layout : item2.component == "ParentView" ? ParentView : resolve => { require(['@/views' + item2.component + '.vue'], resolve) }, //view(item2.component),
            meta: { title: item1.menuName, icon: item2.icon },
            hidden: item2.hidden == 1 ? true : false,
            alwaysShow: item2.component == 'Layout' || item2.component == 'ParentView' ? true : false
          };
          resources.push(item1);
        }
        if ((item1.menuId == item2.id) && (item2.menuType.toLowerCase() == "button")) {
          item1 = {
            id: item2.id,
            menuType: item2.menuType,
            remark: item1.menuName,
            parentId: item1.parentId,
            sort: item1.sort,
          };
          resources.push(item1);
        }
      });
    });

    resources.sort(sortIndex);
  }
  let resultDate = []
  setMenuDate(resultDate, resources, 0)
  resourcesList = resultDate
  return resourcesList
}

function setMenuDate(resultDate, data, index) {
  //获取接口数据生成tree数据
  if (data.length == 0) {
    return;
  }
  if (index == 0) {
    for (let i = 0; i < data.length; i++) {
      if (data[i].parentId == 0) {
        resultDate.push(data[i]);
        data.splice(i, 1);
        i--;
      }
    }
  }
  for (let i = 0; i < data.length; i++) {
    for (let j = 0; j < resultDate.length; j++) {
      if (data.length > 0 && resultDate[j].id == data[i].parentId) {
        if (!resultDate[j].hasOwnProperty("children")) {
          resultDate[j].children = [];
        }

        if (resultDate[j].children.length > 0) {
          find = resultDate[j].children.filter(function (key) {
            return key.id === data[i].id;
          });
        }
        let find = resultDate[j].children.filter((item) => {
          return item.id == data[i].id;
        });
        if (find.length == 0 && data[i].menuType.toLowerCase() == "menu") resultDate[j].children.push(data[i]);
      }
      if (resultDate[j].hasOwnProperty("children")) {
        setMenuDate(resultDate[j].children, data, 1, i);
      }
    }
  }
  return resultDate;
}


/**
 * 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: [],
}

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

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      let getRouterD = setRouterData()
      accessedRoutes = accessedRoutes.concat(getRouterD)
      if (!store.getters.topNav) {
        commit('SET_ROUTES', accessedRoutes)
      }

      resolve(accessedRoutes)
    })
  }
}

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