import { h, ref, onMounted, reactive, watch, toRaw, nextTick, onUnmounted } from "vue";
import { request } from "@/utils/request";
import { Search } from "@element-plus/icons-vue";
import { useRoute, useRouter } from 'vue-router'

const menuList = ref([])

// 获取菜单列表
const getMenuList = async () => {
    try {
        const res = await request({
            url: '/snow-ops-platform/menu/getMenus',
            method: 'GET'
        })
        if (res.code === '00000') {
            menuList.value = res.data
        } else {
            throw new Error(res.message)
        }
    } catch (error) {
        ElMessage.error(error.message);
        console.log(error);
    }
}




export default () => {

    // 点击菜单处理
    const handleMenuClick = (menu) => {
        console.log('menu', menu)
        if (menu.path) {
            router.push({
                path: menu.path,
            });
        }
    };

    const router = useRouter();
    const tokenRef = ref(localStorage.getItem('token'));
    watch(tokenRef, async (newVal) => {
        if (newVal) {
            await getMenuList();
            const firstMenuItem = menuList.value[0]?.children?.[0];
            if (firstMenuItem) {
                // 注释掉进入页面点击第一项的逻辑 后续记得打开
                handleMenuClick(firstMenuItem);
            }
        }
    }, { immediate: true });
    const handleStorageChange = (e) => {
        if (e.key === 'token') {
            tokenRef.value = e.newValue;
        }
    };
    onMounted(() => {
        window.addEventListener('storage', handleStorageChange);
    });
    onUnmounted(() => {
        window.removeEventListener('storage', handleStorageChange);
    });

    return {
        menuList,
        handleMenuClick,
    }
};