<template>
  <div class="workbench-bos" :class="isOpen ? 'workbench-bos1' : 'workbench-bos2'">
    <!-- 展开状态 -->
    <div class="workbench-box1" v-if="isOpen">
      <div class="workbench-expand1 flex-row-start" @click="onOpen">
        <img src="@/assets/images/layout/workbench.png" alt="" />
        <div>收起菜单</div>
      </div>
      <!-- <div class="workbench-expand1 flex-row-start" @click="onPath('/indexDataDiy')">
        <img src="@/assets/images/layout/workbench.png" alt="" />
        <div>首页</div>
      </div> -->
      <!-- 修改点1: 增加 v-if="item1.show" 过滤无权限菜单 -->
      <template v-for="(item1, index1) in menuList" :key="index1">
        <div class="menu-list1" v-if="item1.show" @click="toggleMenu(item1.path)">
          <div class="menu-head1 flex-row-between">
            <div class="menu-title1 flex-row-start">
              <img :src="item1.icon" alt="" />
              <div>{{ item1.title }}</div>
            </div>
            <el-icon v-if="openedMenus.includes(item1.path)" size="14">
              <ArrowDown />
            </el-icon>
            <el-icon v-else size="14">
              <ArrowRight />
            </el-icon>
          </div>
          <div class="menu-item" v-show="openedMenus.includes(item1.path)">
            <template v-for="(item2, index2) in item1.children" :key="index2">
              <div @click.stop="onPath(item2.path)" class="menu-box" :class="{ 'menu-hig': activeMenu == item2.path }">
                {{ item2.title }}
              </div>
            </template>
          </div>
        </div>
      </template>
    </div>

    <!-- 收起状态 -->
    <div v-else class="workbench-box2">
      <div class="workbench-expand2 flex-row-center" @click="onOpen">
        <div class="menu-icon flex-row-center">
          <img src="@/assets/images/layout/workbench.png" alt="" />
        </div>
      </div>

      <!-- 修改点2: 增加 v-if="item1.show" 过滤无权限菜单 -->
      <template v-for="(item1, index1) in menuList" :key="index1">
        <div class="workbench-expand2 flex-row-center" v-if="item1.show">
          <el-popover placement="right">
            <template #reference>
              <div class="menu-icon flex-row-center" :class="{ 'hig': openedMenus.includes(item1.path) }">
                <img :src="item1.icon" alt="" />
              </div>
            </template>
            <div class="popover-bos">
              <div class="popover-title">{{ item1.title }}</div>
              <template v-for="(item2, index2) in item1.children" :key="index2">
                <div class="popover-list" :class="{ 'popover-hig': activeMenu == item2.path }" @click="onPath(item2.path)">
                  {{ item2.title }}
                </div>
              </template>
            </div>
          </el-popover>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import workbench1 from '@/assets/images/layout/workbench1.png';
import workbench2 from '@/assets/images/layout/workbench2.png';
import workbench3 from '@/assets/images/layout/workbench3.png';
import workbench4 from '@/assets/images/layout/workbench4.png';
import workbench5 from '@/assets/images/layout/workbench5.png';
import workbench6 from '@/assets/images/layout/workbench6.png';
import workbench7 from '@/assets/images/layout/workbench7.png';
import { getWorkbenchMenuList } from '@/api/pc/system/index';
import { onPath } from '@/utils/siteConfig';
import { useRouter } from 'vue-router';
import { getInfo } from '@/api/login';
import { el } from 'element-plus/es/locale/index.mjs';

const router = useRouter();
const isOpen = ref(false);
const openedMenus = ref<string[]>([]);
const route = useRoute();
const menuIndex = ref<any>(0);

interface MenuItemChild {
  path: string;
  title: string;
}

interface MenuItem {
  path: string;
  title: string;
  icon: string;
  children?: MenuItemChild[];
  show?: boolean;
}

// 注意：这里定义的是完整的全量菜单结构，后续会根据权限动态修改 children 和 show
const menuLists = ref<any>([]);
const menuList = ref<MenuItem[]>([
  {
    path: '/enterprise',
    title: '企业账户',
    icon: workbench1,
    show: false,
    children: [
      { path: '/enterprise/companyInfo', title: '企业信息' },
      { path: '/enterprise/messageNotice', title: '企业公告' }, // 接口没返这个，应该被过滤
      { path: '/easybuv', title: '地址管理' },
      { path: '/enterprise/invoiceManage', title: '发票抬头管理' },
      { path: '/enterprise/purchasePlan', title: '专属采购方案' },
      { path: '/enterprise/agreementSupply', title: '协议供货' },
      { path: '/enterprise/myCollection', title: '我的收藏' },
      { path: '/enterprise/purchaseHistory', title: '历史购买' },
      { path: '/enterprise/myFootprint', title: '我的足迹' }
    ]
  },
  {
    path: '/order',
    title: '交易管理',
    icon: workbench2,
    show: false,
    children: [
      { path: '/order/orderManage', title: '订单管理' },
      { path: '/order/orderAudit', title: '审核订单' },
      { path: '/order/afterSale', title: '售后服务' },
      { path: '/order/batchOrder', title: '批量下单' },
      { path: '/order/orderEvaluation', title: '订单评价' }
    ]
  },
  {
    path: '/organization',
    title: '组织管理',
    icon: workbench3,
    show: false,
    children: [
      { path: '/i', title: '个人信息' },
      { path: '/organization/deptManage', title: '部门管理' },
      { path: '/organization/staffManage', title: '人员管理' },
      { path: '/organization/roleManage', title: '角色管理' },
      { path: '/organization/approvalFlow', title: '审批流程' },
      { path: '/organization/groupEnterprise', title: '集团关联企业' }
    ]
  },
  {
    path: '/cost',
    title: '成本管理',
    icon: workbench4,
    show: false,
    children: [
      { path: '/cost/itemExpense', title: '分项费用' },
      { path: '/cost/quotaControl', title: '额度控制' }
    ]
  },
  {
    path: '/reconciliation',
    title: '对账管理',
    icon: workbench5,
    show: false,
    children: [
      { path: '/reconciliation/billManage', title: '对账单管理' },
      { path: '/reconciliation/invoiceManage', title: '开票管理' }
    ]
  },
  {
    path: '/valueAdded',
    title: '增值服务',
    icon: workbench6,
    show: false,
    children: [
      { path: '/valueAdded/maintenance', title: '维保服务' },
      { path: '/valueAdded/complaint', title: '投诉与建议' }
    ]
  },
  {
    path: '/analysis',
    title: '采购分析',
    icon: workbench7,
    show: false,
    children: [
      { path: '/analysis/orderAnalysis', title: '订单交易分析' },
      { path: '/analysis/purchaseDetail', title: '商品采购明细' },
      { path: '/analysis/orderStatus', title: '订单执行状态' },
      { path: '/analysis/settlementStatus', title: '对账结算状况' },
      { path: '/analysis/deptPurchase', title: '部门采购金额' }
    ]
  }
]);

const activeMenu = computed(() => route.path);
const userInfo = ref<any>({});

const onOpen = () => {
  isOpen.value = !isOpen.value;
};

const allowedPaths = ref<Set<string>>(new Set());

const processMenuPermissions = (apiMenuList: any[]) => {
  // 1. 收集接口返回的所有合法 path
  const paths = new Set<string>();
  const traverse = (items: any[]) => {
    items.forEach((item) => {
      // 统一格式：确保以 / 开头
      const p = item.path.startsWith('/') ? item.path : `/${item.path}`;
      paths.add(p);
      if (item.children && item.children.length > 0) {
        traverse(item.children);
      }
    });
  };
  traverse(apiMenuList);
  allowedPaths.value = paths;

  // 2. 更新本地 menuList：过滤子菜单并设置父级显示状态
  menuList.value.forEach((menu) => {
    if (!menu.children) {
      menu.show = false;
      return;
    }

    // 【核心修改】过滤出有权限的子菜单
    const permittedChildren = menu.children.filter((child) => {
      const childPath = child.path.startsWith('/') ? child.path : `/${child.path}`;
      return paths.has(childPath);
    });

    // 将过滤后的子菜单重新赋值给 menu.children
    // 这样模板里 v-for 循环时就只有有权限的子项了
    menu.children = permittedChildren;

    // 如果过滤后还有子菜单，则显示父级；否则隐藏父级
    menu.show = permittedChildren.length > 0;
  });

  checkCurrentRoutePermission();

  // 权限处理完后，重新计算展开状态
  initOpenedMenus();
};

const checkCurrentRoutePermission = () => {
  const currentPath = route.path;
  const publicPaths = ['/', '/login', '/404'];
  if (!publicPaths.includes(currentPath) && !allowedPaths.value.has(currentPath) && menuLists.value.includes(currentPath)) {
    console.log('jinlai');
    onPath('/');
  }
};

onMounted(() => {
  if (window.innerWidth > 1420) {
    isOpen.value = true;
  } else {
    isOpen.value = false;
  }
  window.addEventListener('resize', handleResize);

  menuList.value.forEach((item1: any) => {
    item1.children.forEach((item2: any) => {
      menuLists.value.push(item2.path);
    });
  });

  getInfo().then((res1) => {
    if (res1.code == 200) {
      userInfo.value = res1.data;
      if (res1.data && res1.data.user?.userSonType == 4) {
        menuList.value.forEach((item1: any) => {
          if (item1.path == '/enterprise') {
            item1.show = false;
          } else {
            item1.show = true;
          }
          item1.children.forEach((item2: any) => {
            item2.show = true;
          });
        });
        initOpenedMenus();
      } else {
        getWorkbenchMenuList().then((res: any) => {
          const apiData = res.data || res;
          if (Array.isArray(apiData)) {
            processMenuPermissions(apiData);
          }
        });
      }
    }
  });
});

const handleResize = () => {
  if (window.innerWidth > 1420) {
    isOpen.value = true;
  } else {
    isOpen.value = false;
  }
};

const initOpenedMenus = () => {
  const currentPath = route.path;
  openedMenus.value = [];

  for (const menu of menuList.value) {
    if (!menu.show) continue;

    // 此时 menu.children 已经是过滤后的干净数据
    const hasActiveChild = menu.children?.some((child) => {
      const childPath = child.path.startsWith('/') ? child.path : `/${child.path}`;
      return currentPath === childPath || currentPath.startsWith(childPath + '/');
    });

    if (hasActiveChild) {
      openedMenus.value = [menu.path];
      return;
    }
  }
};

const toggleMenu = (path: string) => {
  const index = openedMenus.value.indexOf(path);
  if (index > -1) {
    openedMenus.value.splice(index, 1);
  } else {
    openedMenus.value = [path];
  }
};

watch(
  () => route.path,
  () => {
    initOpenedMenus();
    if (userInfo.value && userInfo.value.user.userSonType != 4) {
      checkCurrentRoutePermission();
    }
  }
);
</script>

<style lang="scss" scoped>
/* 样式保持不变 */
.workbench-bos {
  // position: absolute;
  // top: 0;

  //展开的
  .workbench-box1 {
    background: #ffffff;
    border-radius: 10px;
    padding: 10px 8px;
    width: 180px;

    .workbench-expand1 {
      height: 42px;
      width: 100%;
      font-size: 14px;
      color: #1d2129;
      padding-left: 12px;
      cursor: pointer;

      &:hover {
        color: #e60012;
      }

      img {
        height: 16px;
        width: 16px;
        margin-right: 8px;
      }
    }

    .menu-list1 {
      width: calc(100% - 24px);
      border-bottom: 1px #e5e6eb solid;
      margin: 0 12px;

      &:nth-last-child(1) {
        border-bottom: none;
      }

      .menu-head1 {
        height: 54px;
        width: 100%;
        color: #1d2129;
        cursor: pointer;

        &:hover {
          color: #e60012;
        }

        .menu-title1 {
          font-size: 14px;

          img {
            height: 16px;
            width: 16px;
            margin-right: 8px;
          }
        }
      }

      .menu-item {
        padding-bottom: 5px;

        .menu-box {
          width: 100%;
          height: 36px;
          border-radius: 3px;
          font-size: 13px;
          color: #4e5969;
          padding-left: 12px;
          line-height: 36px;
          cursor: pointer;

          &.menu-hig {
            background: #f7f8fa;
            color: #e60012;
          }

          &:hover {
            color: #e60012;
          }
        }
      }
    }
  }

  //收起的
  .workbench-box2 {
    background: #ffffff;
    border-radius: 10px;
    padding: 10px 8px;
    width: 50px;

    .workbench-expand2 {
      width: 34px;
      height: 36px;
      cursor: pointer;
      position: relative;

      .menu-icon {
        width: 24px;
        height: 24px;

        &.hig {
          background-color: #ffe8e8;
        }

        img {
          height: 16px;
          width: 16px;
        }
      }

      .menu-open {
        position: absolute;
        right: -168px;
        top: 0;
        width: 148px;
        background-color: #ffffff;
        z-index: 99;
        padding: 10px 18px;
        border-radius: 10px;
      }
    }
  }

  &.workbench-bos1 {
    left: -200px;
  }

  &.workbench-bos2 {
    left: -70px;
  }
}

.popover-bos {
  .popover-title {
    font-size: 12px;
    color: #9095a0;
    margin-bottom: 7px;
    padding-left: 4px;
  }

  .popover-list {
    width: 120px;
    height: 32px;
    font-size: 14px;
    color: #1c2c49;
    line-height: 32px;
    padding-left: 4px;
    cursor: pointer;

    &:hover {
      color: var(--el-color-primary);
    }

    &.popover-hig {
      background: #ffe8e8;
    }
  }
}
</style>
