<template>
  <div class="sidebar">
    <el-menu id="menu-aside" :default-active="defaultActive" class="sidebar-el-menu" background-color="#000" @open="handleOpen" @close="handleClose" @select="handleSelect">
      <template v-for="menu in tree" :key="menu._id">
        <el-menu-item-group v-if="menu.isGroup" :title="id2MenuName[menu.menuId]">
          <template #header>
            <div class="menu-group-title">{{ id2MenuName[menu.menuId] }}</div>
          </template>
          <el-menu-item v-for="child in menu.children" :index="child.path" :key="child._id">
            <el-icon v-if="child.icon">
              <component v-if="child.icon === 'Group'" :is="Group"></component>
              <svg-icon v-if="selfIcons.some((i) => i === child.icon)" :name="child.icon" />
              <component v-else :is="child.icon"></component>
            </el-icon>
            <span v-if="child.iconfont" class="el-icon" :class="child.iconfont"></span>
            <span slot="title">{{ id2MenuName[child.menuId] }}</span>
          </el-menu-item>
        </el-menu-item-group>
        <el-menu-item v-else :index="menu.path">
          <el-icon v-if="menu.icon">
            <component :is="menu.icon"></component>
          </el-icon>
          <span v-if="menu.iconfont" class="el-icon" :class="child.iconfont"></span>
          <span slot="title">{{ id2MenuName[child.menuId] }}</span>
        </el-menu-item>
      </template>
    </el-menu>
  </div>
</template>
<script setup>
import { computed, onMounted, ref, toRaw, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { storeToRefs } from "pinia";
import { memberStore } from "@/store/member";
import { tagsStore } from "@/store/tags";
import { getRoutes } from "@/router";
import { getMenuList as getMenuListUrl } from "@/api/system.js";
import { getRolesByRoleId } from "@/api/corp";
import Group from "@/assets/icons/icon-group.vue";
import { teamStore } from "@/store/team";
import SvgIcon from "@/components/svg-icon";

const selfIcons = ["userGroupmsg", "teamGroupmsg", "corpGroupmsg", "corpCustomer", "iconHuoma", "corpGroup", "memberChat", "up-chart", "rate", "kehulianxiren", "jifenguanli", "keshiguanli", "zixunjiedai", "wangdianbaobei", "zixunfenzhen", "zhiliaohuakou", "taocanguanli", "friendStats", "huihuatongji"];
const router = useRouter();
const route = useRoute();
const routes = getRoutes();
const defaultActive = ref("");
const { addTag, setMenus } = tagsStore();
const { selectTag, tags, menus } = storeToRefs(tagsStore());
const id2MenuName = computed(() =>
  menus.value.reduce((acc, item) => {
    acc[item.menuId] = item.customMenuName || item.menuName;
    return acc;
  }, {})
);
const routeValid = routes.some((i) => i.name && i.name === route.name);
onMounted(async () => {
  const { menuRoute } = await getMenuRoute();
  const tagRoute = routeValid ? route : menuRoute;
  if (tagRoute) {
    addTag({
      name: tagRoute.meta.title,
      routeName: tagRoute.name,
      path: tagRoute.fullPath,
      multTag: Boolean(tagRoute.meta.multTag),
    });
    defaultActive.value = tagRoute.name;
  }
  if (tagRoute && !routeValid) router.replace({ name: tagRoute.name });
});
watch(selectTag, (n) => {
  const item = tags.value.find((i) => i.path === n);
  defaultActive.value = item ? item.routeName : "";
});
function handleSelect(name) {
  router.push({ name });
}
// 找到当前用户菜单中第一个有对应路由的菜单路由
async function getMenuRoute() {
  // await getMenuList();
  const routeNames = routes.map((i) => i.name);
  const firstMenu = menus.value.find((i) => routeNames.includes(i.path));
  const menuRoute = firstMenu ? router.resolve({ name: firstMenu.path }) : null;
  return { menuRoute };
}
const tree = computed(() => {
  const tree = getTree();
  return tree.filter((i) => (i.isGroup && i.children.length) || !i.isGroup);
});
async function getMenuList() {
  const { memberInfo } = memberStore();
  let { roleIds = [] } = memberInfo;
  let menuIdList = [];
  let { data: list } = await getRolesByRoleId(roleIds);
  let roleList = list.data;
  const currentTeam = teamStore().currentTeam;
  const myUserId = sessionStorage.getItem("userId");
  const isTeamLeader = myUserId && currentTeam && Array.isArray(currentTeam.memberLeaderList) && currentTeam.memberLeaderList.some((i) => i === myUserId);
  if (!isTeamLeader) {
    // 去除团队负责人角色
    roleList = roleList.filter((i) => !i.roleId || i.roleId !== "memberLeader");
  } else {
    // 团队负责人角色
    roleList = roleList.filter((i) => !i.roleId || i.roleId !== "member");
  }

  roleList.forEach((item) => {
    const array = item.menuList;
    menuIdList = [...new Set([...menuIdList, ...array])];
  });
  const { data, success } = await getMenuListUrl(menuIdList);
  if (success) {
    setMenus(data.data);
  } else {
    setMenus([]);
  }
}
function getTree() {
  const map = menus.value.reduce((val, menu) => ((val[menu.menuId] = menu), val), {});
  const relationships = {};
  menus.value.forEach((item) => {
    const { parentId, menuId } = item;
    if (!relationships[parentId]) relationships[parentId] = [];
    relationships[parentId].push(menuId);
  });

  const buildTree = (parentId) => {
    const children = relationships[parentId];
    if (!children) return null;
    return children
      .map((child) => ({
        ...(map[child] || {}),
        parentId,
        menuId: child,
        children: buildTree(child),
      }))
      .sort((a, b) => a.sort - b.sort);
  };

  const roots = relationships[0] || [];
  return roots
    .map((root) => ({
      ...(map[root] || {}),
      parentId: 0,
      isGroup: !("path" in (map[root] || {})),
      menuId: root,
      children: buildTree(root) || [],
    }))
    .sort((a, b) => a.sort - b.sort);
}
</script>
<style lang="scss">
$menu-text-active-color: #1261ff;
$menu-item-bg-color: #eef4ff;
$menu-text-color: #333;

.menu-group-title {
  font-size: 12px;
  color: #999;
}

.el-menu-item-group .el-menu-item:last-of-type {
  margin-bottom: 7px;
}

.sidebar {
  height: calc(100% - var(--app-header-height));
  float: left;
  width: 150px;
  position: absolute;
  padding: 0 10px;
  box-sizing: border-box;
  top: var(--app-header-height);
  bottom: 0;
  left: 0;
  background: #262f3e; // version 1
  background: #fff; // version 2
  overflow: auto;
  z-index: 10;

  #menu-aside {
    background: none;
    border-right: none;
    padding-top: 10px;

    > .el-menu-item,
    li > .el-sub-menu__title {
      height: 40px;
      line-height: 40px;
      font-size: 14px;

      i {
        color: $menu-text-color;
      }
    }

    .el-menu {
      .el-menu-item {
        font-size: 14px;
      }
    }

    .el-sub-menu {
      position: relative;
    }

    .el-menu-item {
      position: relative;
      min-width: 0;

      &:before {
        content: "";
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        border-left: 6px solid#3598d9;
        -webkit-transform: scaleY(0.0001);
        -ms-transform: scaleY(0.0001);
        transform: scaleY(0.0001);
        // opacity: 0;
        transition: opacity 0.15s cubic-bezier(0.215, 0.61, 0.355, 1), -webkit-transform 0.15s cubic-bezier(0.215, 0.61, 0.355, 1);
        transition: transform 0.15s cubic-bezier(0.215, 0.61, 0.355, 1), opacity 0.15s cubic-bezier(0.215, 0.61, 0.355, 1);
        /*transition: transform 0.15s cubic-bezier(0.215, 0.61, 0.355, 1), opacity 0.15s cubic-bezier(0.215, 0.61, 0.355, 1), -webkit-transform 0.15s cubic-bezier(0.215, 0.61, 0.355, 1);*/
      }
    }

    ul .el-menu-item {
      height: 40px;
      line-height: 40px;
      padding-left: 20px;
      // padding-left: 54px !important;
    }

    .i-menu {
      float: left;
      display: inline-block;
      vertical-align: top;
      width: 22px;
      height: 22px;
      margin-right: 4px;
      margin-top: 14px;
    }

    .el-sub-menu__icon-arrow {
      margin-top: -6px;
    }

    .el-sub-menu__title,
    .el-menu-item {
      // opacity: 0.65;
      background: none;
      transition: opacity 0.1s;
    }

    .el-sub-menu__icon-arrow,
    .el-sub-menu__title,
    .el-menu-item {
      color: $menu-text-color;
    }

    .el-sub-menu.is-opened .el-sub-menu__icon-arrow,
    .el-sub-menu.is-opened .el-sub-menu__title {
      color: $menu-text-color;

      .sidebarIcon {
        color: $menu-text-color;
      }
    }

    .el-sub-menu__title:hover,
    .el-menu-item:hover,
    .el-sub-menu__title:hover .el-sub-menu__icon-arrow {
      background: $menu-item-bg-color;
      color: $menu-text-active-color;

      .sidebarIcon {
        color: $menu-text-active-color;
      }

      .el-icon {
        color: $menu-text-active-color;
      }
    }

    .el-sub-menu__title:active,
    .el-menu-item:active {
      background: $menu-text-active-color;
      color: #fff;
    }

    .el-menu-item.is-active {
      background: $menu-item-bg-color;
      color: $menu-text-active-color;
      font-weight: 600;
      border-radius: 6px;

      .el-icon {
        color: $menu-text-active-color;
      }
    }

    .el-sub-menu.is-active:not(.is-opened) {
      .sidebarIcon {
        color: $menu-text-color;
      }

      &:before {
        content: "";
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        border-left: 6px solid#3598d9;
        -webkit-transform: scaleY(0.0001);
        -ms-transform: scaleY(0.0001);
        transform: scaleY(0.0001);
        // opacity: 0;
        transition: opacity 0.15s cubic-bezier(0.215, 0.61, 0.355, 1), -webkit-transform 0.15s cubic-bezier(0.215, 0.61, 0.355, 1);
        transition: transform 0.15s cubic-bezier(0.215, 0.61, 0.355, 1), opacity 0.15s cubic-bezier(0.215, 0.61, 0.355, 1);
        transform: scaleY(1);
        /*transition: transform 0.15s cubic-bezier(0.215, 0.61, 0.355, 1), opacity 0.15s cubic-bezier(0.215, 0.61, 0.355, 1), -webkit-transform 0.15s cubic-bezier(0.215, 0.61, 0.355, 1);*/
      }
    }
  }

  .sidebarIcon {
    padding-right: 15px;
    font-size: 20px;
  }
}

.sidebar::-webkit-scrollbar {
  width: 0;
}

.el-menu-item [class^="el-icon"] {
  display: inline-block;
  /* width: 24px !important;
  height: 24px !important; */
  margin-right: 7px !important;
  font-size: 20px !important;
}
</style>
