<script setup>

import TMenu from "@/components/ui/TMenu.vue";
import TDivider from "@/components/ui/TDivider.vue";
import {onMounted, onUnmounted, ref} from "vue";
const props = defineProps(["ctx", "hasMenu", "hasTab"])

let items = props.ctx.leftMenuItems
if (props.ctx.tinyLeftMenuItems instanceof Array && props.ctx.tinyLeftMenuItems.length > 0) {
	items = [
		{
			label: "当前路由规则",
			items: props.ctx.tinyLeftMenuItems
		}
	]
}

const leftBoxRef = ref()
const scrollHeightListener = () => {
	const scrollTop = document.querySelector(".main").scrollTop
	if (props.hasMenu) {
		leftBoxRef.value.style.top = "max(calc(10.8em - " + scrollTop + "px), 5em)"
	}
}

onMounted(() => {
	document.querySelector(".main").addEventListener("scroll", scrollHeightListener)

	// focus on item
	const activeItem = leftBoxRef.value.querySelector(".p-menu-item-link.t-active-item")
	if (activeItem) {
		if (activeItem.scrollIntoViewIfNeeded) {
			activeItem.scrollIntoViewIfNeeded()
		} else {
			activeItem.scrollIntoView()
		}
	}
})

onUnmounted(() => {
	document.querySelector(".main").removeEventListener("scroll", scrollHeightListener)
})

</script>

<template>
	<div class="relative">
		<div ref="leftBoxRef" class="left-box" :class="{disabled:ctx.leftMenuItemIsDisabled, 'has-menu': hasMenu, 'has-tab': hasTab}">
			<TMenu :items="items" class="mb-14">
				<template #item="{ item, props }">
					<a v-ripple class="p-menu-item-link" :href="item.url" :class="{'t-active-item':item.isActive, on:item.isOn, off:item.isOff||item.isImportant}" v-if="item.name != '-'">
						<span v-if="item.name != '-'">{{ item.name }}<var v-if="item.isOff" class="not-italic">关</var><var v-if="item.isImportant" class="not-italic">开</var></span>
					</a>
					<span v-else><TDivider></TDivider></span>
				</template>
			</TMenu>
		</div>
		<div class="right-box" :class="{'has-menu': hasMenu}">
			<slot></slot>
		</div>
	</div>
</template>

<style scoped lang="postcss">
.left-box {
	position: fixed;
	top: 5em;
	bottom: 1em;
	overflow-y: auto;
}

.left-box.has-menu {
	/* top: 10.8em;
	top: 88px!important; */
	top: 30px!important;
	position: absolute;
	border: 1px solid rgba(229, 232, 242, 1);
}

:deep(.p-menu) {
	border: none;
}

:deep(.wrapper) {
	padding-bottom: 30px!important;
}

.left-box.has-tab {
	top: 7.4em;
}

:deep(.p-menu) {
	min-width: auto;
	width: 10em;
}

.right-box {
	/* padding-left: 11.4em; */
	padding-left: 170px;
}

.t-active-item {
	color: var(--p-primary-color);
}

a.on {
	@apply decoration-dotted underline underline-offset-4;
}

var {
	@apply inline-block ml-1 text-red-500 text-sm;
}

</style>