import { config } from "@/router";
import user from "./user";
import { watch, ref } from "vue";

// 不加入导航条的页面
const NOT_JOIN_NAVS = [];
// 所有权限都有的router
const MUST_JOIN_NAVS = ["viewLayout"];
// router对应的icon
const ICON_MAP = { viewLayout: "el-icon-s-home" };

const getNames = (config) => {
  let names = [];
  config.forEach((item) => {
    names.push(item.name);
    item.children && names.push(...getNames(item.children));
  });
  return names;
};

const _getNavs = (items, notJoinNavs) => {
  let ret = [];
  for (let i = 0; i < items.length; i++) {
    if (~notJoinNavs.indexOf(items[i].name)) {
      continue;
    } else {
      let item = {
        ...items[i],
        children: items[i].children ? _getNavs(items[i].children, notJoinNavs) : null,
        icon: ICON_MAP[items[i].name],
      };

      delete item.component;
      ret.push(item);
    }
  }
  console.log(ret,'ret');
  return ret;
};

const getNavs = () => {
  let names = getNames(config);
  let noShowNames = ['login']
  if (user.value.role == 3) {
    let layout = config.find((item) => item.name == "viewLayout");
    layout.children.forEach((item) => {
      if (item.name != "shop" && item.name != "scene") {
        noShowNames.push(item.name);
      }
    });
  }
  console.log(noShowNames,'noShowNames');
  let notJoinNavs = names.filter((name) => ~NOT_JOIN_NAVS.indexOf(name) || (
    ~noShowNames.indexOf(name) && 
    !~MUST_JOIN_NAVS.indexOf(name)
  ));
  console.log(notJoinNavs,'itemitem');

  return _getNavs(config, notJoinNavs);
};

const navs = ref([]);

watch(
  () => user.value.role,
  () => (navs.value = getNavs())
);
setTimeout(() => (navs.value = getNavs()));

export default navs;
