<template>
  <div class="max-box sidebar-container" :class="flexibleType?'flexibleTypeTrue':'flexibleTypeFalse'">
    <el-scrollbar class="router-button-box" :class="settings.sideTheme" wrap-class="scrollbar-wrapper">
      <el-menu
        :default-active="activeMenu"
        :collapse="isCollapse"
        :unique-opened="true"
        :active-text-color="settings.theme"
        :collapse-transition="false"
        mode="vertical"
      >
        <sidebar-item
          v-for="(route, index) in sidebarRouters"
          :key="route.path + index"
          :item="route"
          :base-path="route.path"
        />
      </el-menu>
    </el-scrollbar>
    <p style="height:30px;"></p>
    <p class="sidebar-position-p" @click="flexibleButton()"
       :class="flexibleType?'el-icon-s-fold sidebar-position-p-1':'el-icon-s-unfold sidebar-position-p-2'"></p>
  </div>
</template>

<script>
  import { mapGetters, mapState } from "vuex";
  import SidebarItem from "./SidebarItem";
  import { judgmentNetworkReturnOutAddress } from "@/utils/ruoyi";

  export default {
    data() {
      return {
        flexibleType: true,
      }
    },
    components: {
      SidebarItem
    },
    computed: {
      ...mapState(["settings"]),
      ...mapGetters(["sidebarRouters", "sidebar", "avatar", "name"]),
      activeMenu() {
        const route = this.$route;
        const { meta, path } = route;
        if (meta.activeMenu) {
          return meta.activeMenu;
        }
        // 注意：setTagsType 方法需要在父组件中定义，这里保留原逻辑
        if (this.$parent.setTagsType) {
          this.$parent.setTagsType(path);
        }
        return path;
      },
      showLogo() {
        return this.$store.state.settings.sidebarLogo;
      },
      isCollapse() {
        // return !this.sidebar.opened;
      },
      setting: {
        get() {
          return this.$store.state.settings.showSettings
        },
        set(val) {
          this.$store.dispatch('settings/changeSetting', {
            key: 'showSettings',
            value: val
          })
        }
      },
    },
    watch: {
      // 监听路由变化，实现页面内跳转时左侧菜单也能刷新
      '$route': {
        handler(newRoute) {
          let activePath = newRoute.path;
          // 解析出顶级菜单的 path，逻辑与顶部菜单保持一致
          if (newRoute.path.lastIndexOf("/") > 0) {
            const tmpPath = newRoute.path.substring(1);
            activePath = "/" + tmpPath.substring(0, tmpPath.indexOf("/"));
          }
          this.updateSidebarByPath(activePath);
        },
        immediate: true // 组件创建时立即执行一次
      }
    },
    methods: {
      flexibleButton(){
        this.$set(this,'flexibleType',!this.flexibleType);
      },
      //退出登录
      async logout() {
        this.$confirm('确定注销并退出系统吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('LogOut').then(() => {
            let list = [];
            list.push(this.$store.state.tagsView.visitedViews[0]);
            this.$store.state.tagsView.visitedViews = [];
            this.$store.state.tagsView.visitedViews.push(list[0]);
            if(process.env.VUE_APP_LOGIN_TYPE === 'skip'){
              window.location.href = judgmentNetworkReturnOutAddress();
            }else{
              this.$router.push({ path:"/login" }).catch(()=>{});
            }
          })
        }).catch(() => {});
      },

      // 👇 新增方法：根据顶级菜单的 path 更新侧边栏数据
      updateSidebarByPath(path) {
        // 1. 获取所有路由。这里假设所有路由都存放在 permission 模块的 routers 中
        // 请根据你的项目实际 store 结构调整，例如可能是 topbarRouters 或其他
        const allRouters = this.$store.state.permission.routers || this.$store.state.permission.topbarRouters;

        if (!allRouters) return;

        let routes = [];

        // 2. 筛选出当前顶级菜单下的所有子菜单
        allRouters.forEach(menu => {
          if (menu.path === path && menu.children) {
            menu.children.forEach(child => {
              // 复制顶部菜单 activeRoutes 中的 path 处理逻辑
              if (child.parentPath === undefined) {
                if(menu.path === "/") {
                  child.path = "/redirect/" + child.path;
                } else {
                  if(!this.ishttp(child.path)) {
                    child.path = menu.path + "/" + child.path;
                  }
                }
                child.parentPath = menu.path;
              }
              routes.push(child);
            });
          }
        });

        // 3. 提交 mutation 更新侧边栏
        if (routes.length > 0) {
          // 同步更新 localStorage，保持与顶部菜单行为一致
          localStorage.setItem('leftRoutesData', JSON.stringify(routes));
          this.$store.commit("SET_SIDEBAR_ROUTERS", routes);
        } else {
          // 如果没有找到对应的子菜单，尝试从 localStorage 恢复
          const cachedRoutes = JSON.parse(localStorage.getItem('leftRoutesData'));
          if (cachedRoutes) {
            this.$store.commit("SET_SIDEBAR_ROUTERS", cachedRoutes);
          }
        }
      },

      ishttp(url) {
        return url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1
      }
    }
  };
</script>
<style lang="scss" scoped>
  .max-box{
    display: flex;
    flex-direction: column;
    margin:5px 10px 0 0;
    border-bottom-right-radius: 10px;
    border-top-right-radius: 10px;
    position: relative;
    .router-button-box{
      flex:1;
    }
    .user-box {
      width:230px;
      height:40px;
      margin:28px 0;
      margin-right: 30px;
      .avatar-wrapper {
        display: flex;
        position: relative;
        img{
          height:40px;
          width:40px;
          border-radius:50%;
        }
        p{
          flex:1;
          line-height:40px;
          margin:0 15px;
          font-size:14px;
        }
        i{
          -webkit-transform: rotateZ(-90deg);
          -ms-transform: rotate(-90deg);
          transform: rotateZ(-90deg);
        }
      }
    }
    .sidebar-position-p{
      position: absolute;
      left:250px;
      bottom:20px;
      width:34px;
      height:34px;
      color:#0183FA;
      font-size:34px;
      cursor: pointer;
    }
    .sidebar-position-p-2{
      position: fixed!important;
      left:-5px!important;
      bottom:20px;
      background-color: #fff;
      box-shadow: 0 0 8px 1px rgba(0, 0, 0, 0.1);
      -webkit-border-radius: 6px;
      -moz-border-radius: 6px;
      border-radius: 6px;
    }
  }
  .el-dropdown-menu--medium{
    /*backAnimation: red!important;*/
    /*top:810px!important;*/
  }
  .flexibleTypeFalse{
    margin-left: -300px!important;
  }
</style>
