<template>
	<div v-show="showTags" class="tags-view">
		<div class="tags-wrapper" @contextmenu.prevent>
			<a-space :size="4">
				<a-tag
					v-for="tag in visitedViews"
					:key="tag.fullPath"
					:closable="!tag.meta?.affix"
					class="tag-item"
					:class="{
						active: isActive(tag),
						'tag-affix': tag.meta?.affix,
					}"
					@click="clickTag(tag)"
					@close="closeSelectedTag(tag)"
					@contextmenu.prevent="handleContextMenu($event, tag)"
				>
					<template #icon v-if="tag.meta?.affix">
						<PushpinFilled />
					</template>
					{{ tag.meta?.title || tag.name }}
				</a-tag>
			</a-space>
		</div>

		<div class="tags-actions">
			<a-dropdown v-model:open="actionMenuVisible" trigger="click" placement="bottomRight">
				<a-button size="small" type="text">
					<MoreOutlined />
				</a-button>
				<template #overlay>
					<a-menu @click="handleActionMenuClick">
						<a-menu-item key="refresh">
							<ReloadOutlined />
							<span>刷新当前页</span>
						</a-menu-item>
						<a-menu-item key="closeOthers">
							<ColumnWidthOutlined />
							<span>关闭其他</span>
						</a-menu-item>
						<a-menu-item key="closeLeft">
							<LeftOutlined />
							<span>关闭左侧</span>
						</a-menu-item>
						<a-menu-item key="closeRight">
							<RightOutlined />
							<span>关闭右侧</span>
						</a-menu-item>
						<a-menu-item key="closeAll">
							<CloseCircleOutlined />
							<span>关闭所有</span>
						</a-menu-item>
					</a-menu>
				</template>
			</a-dropdown>
		</div>

		<!-- 右键菜单 -->
		<teleport to="body">
			<div
				v-if="contextMenu.visible"
				:style="{
					position: 'fixed',
					left: contextMenu.x + 'px',
					top: contextMenu.y + 'px',
					zIndex: 9999,
				}"
				class="context-menu"
				@click="closeContextMenu"
			>
				<a-menu @click="handleMenuClick">
					<a-menu-item key="refresh">
						<ReloadOutlined />
						<span>刷新</span>
					</a-menu-item>
					<a-menu-item v-if="selectedTag && !selectedTag.meta?.affix" key="close">
						<CloseOutlined />
						<span>关闭</span>
					</a-menu-item>
					<a-menu-item key="closeOthers">
						<ColumnWidthOutlined />
						<span>关闭其他</span>
					</a-menu-item>
					<a-menu-item key="closeAll">
						<CloseCircleOutlined />
						<span>关闭所有</span>
					</a-menu-item>
				</a-menu>
			</div>
		</teleport>
	</div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useLayoutStore } from '@/stores/modules/layout'
import config from '@/config'

defineOptions({
	name: 'TagsView',
})

const route = useRoute()
const router = useRouter()
const layoutStore = useLayoutStore()

const showTags = ref(true)
const selectedTag = ref(null)
const visitedViews = computed(() => layoutStore.viewTags)
console.log(layoutStore.viewTags)
// 右键菜单状态
const contextMenu = ref({
	visible: false,
	x: 0,
	y: 0,
})
// 顶部操作菜单状态
const actionMenuVisible = ref(false)

// 判断是否是当前激活的标签
const isActive = (tag) => {
	return tag.fullPath === route.fullPath
}

// 添加标签
const addTags = () => {
	const { name } = route
	if (name && !route.meta?.noCache) {
		layoutStore.updateViewTags({
			fullPath: route.fullPath,
			path: route.path,
			name: name,
			query: route.query,
			params: route.params,
			meta: route.meta,
		})
	}
}

// 移除标签
const closeSelectedTag = (view) => {
	// 如果是固定标签，不允许关闭
	if (view.meta?.affix) {
		return
	}

	layoutStore.removeViewTags(view.fullPath)

	// 如果关闭的是当前激活的标签，需要跳转
	if (isActive(view)) {
		const nextTag = visitedViews.value.find((tag) => tag.fullPath !== view.fullPath)
		if (nextTag) {
			router.push(nextTag.fullPath)
		} else {
			// 如果没有其他标签，跳转到首页
			router.push(config.DASHBOARD_URL)
		}
	}
}

// 关闭其他标签
const closeOthersTags = () => {
	if (!selectedTag.value || !selectedTag.value.fullPath) {
		return
	}

	// 保留固定标签和当前选中的标签
	const tagsToKeep = visitedViews.value.filter((tag) => tag.meta?.affix || tag.fullPath === selectedTag.value.fullPath)

	// 更新标签列表
	layoutStore.viewTags = tagsToKeep

	// 如果当前不在选中的标签页，跳转到选中的标签
	if (!isActive(selectedTag.value)) {
		router.push(selectedTag.value.fullPath)
	}
}

// 关闭所有标签
const closeAllTags = () => {
	// 只保留固定标签
	const affixTags = visitedViews.value.filter((tag) => tag.meta?.affix)
	layoutStore.viewTags = affixTags

	// 如果还有固定标签，跳转到第一个固定标签
	if (affixTags.length > 0) {
		router.push(affixTags[0].fullPath)
	} else {
		// 如果没有固定标签，跳转到首页
		router.push(config.DASHBOARD_URL)
	}
}

// 关闭左侧标签
const closeLeftTags = () => {
	const currentTag = selectedTag.value || visitedViews.value.find((tag) => isActive(tag))
	if (!currentTag) return

	const currentIndex = visitedViews.value.findIndex((tag) => tag.fullPath === currentTag.fullPath)
	if (currentIndex === -1) return

	// 保留当前标签及其右侧的标签，以及所有固定标签
	const tagsToKeep = visitedViews.value.filter((tag, index) => {
		return tag.meta?.affix || index >= currentIndex
	})

	layoutStore.viewTags = tagsToKeep
}

// 关闭右侧标签
const closeRightTags = () => {
	const currentTag = selectedTag.value || visitedViews.value.find((tag) => isActive(tag))
	if (!currentTag) return

	const currentIndex = visitedViews.value.findIndex((tag) => tag.fullPath === currentTag.fullPath)
	if (currentIndex === -1) return

	// 保留当前标签及其左侧的标签，以及所有固定标签
	const tagsToKeep = visitedViews.value.filter((tag, index) => {
		return tag.meta?.affix || index <= currentIndex
	})

	layoutStore.viewTags = tagsToKeep
}

// 点击标签
const clickTag = (tag) => {
	if (!isActive(tag)) {
		router.push(tag.fullPath)
	}
}

// 刷新指定标签
const refreshTag = (tag) => {
	// 如果刷新的是当前激活的标签
	if (isActive(tag)) {
		// 调用 store 的刷新方法，触发组件重新渲染
		layoutStore.refreshTag()
	} else {
		// 如果刷新的是其他标签，先跳转到该标签
		router.push(tag.fullPath)
	}
}

// 刷新当前选中的标签（用于顶部操作按钮）
const refreshSelectedTag = () => {
	// 找到当前激活的标签
	const currentTag = visitedViews.value.find((tag) => isActive(tag))
	if (currentTag) {
		refreshTag(currentTag)
	}
}

// 右键菜单处理
const handleContextMenu = (event, tag) => {
	event.preventDefault()
	event.stopPropagation()

	selectedTag.value = tag
	contextMenu.value = {
		visible: true,
		x: event.clientX,
		y: event.clientY,
	}
}

// 关闭右键菜单
const closeContextMenu = () => {
	contextMenu.value.visible = false
}

// 菜单点击处理
const handleMenuClick = ({ key }) => {
	switch (key) {
		case 'refresh':
			if (selectedTag.value) {
				refreshTag(selectedTag.value)
			}
			break
		case 'close':
			if (selectedTag.value && !selectedTag.value.meta?.affix) {
				closeSelectedTag(selectedTag.value)
			}
			break
		case 'closeOthers':
			closeOthersTags()
			break
		case 'closeAll':
			closeAllTags()
			break
	}
	closeContextMenu()
}

// 顶部操作菜单点击处理
const handleActionMenuClick = ({ key }) => {
	switch (key) {
		case 'refresh':
			refreshSelectedTag()
			break
		case 'closeOthers':
			closeOthersTags()
			break
		case 'closeLeft':
			closeLeftTags()
			break
		case 'closeRight':
			closeRightTags()
			break
		case 'closeAll':
			closeAllTags()
			break
	}
	actionMenuVisible.value = false
}

// 点击其他地方关闭右键菜单
const handleClickOutside = (event) => {
	if (contextMenu.value.visible) {
		const menuElement = document.querySelector('.context-menu')
		if (menuElement && !menuElement.contains(event.target)) {
			closeContextMenu()
		}
	}
}

// 监听路由变化，自动添加标签
watch(
	() => route.fullPath,
	() => {
		addTags()
		// 更新当前选中的标签
		selectedTag.value = visitedViews.value.find((tag) => isActive(tag)) || null
	},
	{ immediate: true },
)

onMounted(() => {
	addTags()
	// 初始化选中的标签
	selectedTag.value = visitedViews.value.find((tag) => isActive(tag)) || null
	// 添加点击事件监听器
	document.addEventListener('click', handleClickOutside)
})

onBeforeUnmount(() => {
	// 移除点击事件监听器
	document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped lang="scss">
.tags-view {
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 40px;
	background-color: #ffffff;
	border-bottom: 1px solid #f0f0f0;
	padding: 0 16px;
	box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);

	.tags-wrapper {
		flex: 1;
		overflow-x: auto;
		overflow-y: hidden;
		white-space: nowrap;

		&::-webkit-scrollbar {
			height: 0;
		}

		&::-webkit-scrollbar-thumb {
			background: rgba(0, 0, 0, 0.2);
			border-radius: 0;
		}

		&::-webkit-scrollbar-track {
			background: transparent;
		}

		.tag-item {
			display: inline-flex;
			align-items: center;
			gap: 4px;
			height: 28px;
			line-height: 28px;
			padding: 0 12px;
			margin: 0 4px;
			border: 1px solid #d9d9d9;
			background-color: #fafafa;
			border-radius: 2px;
			cursor: pointer;
			transition: all 0.3s;
			user-select: none;

			&:hover {
				color: #1890ff;
				border-color: #1890ff;
			}

			&.active {
				background-color: #1890ff;
				border-color: #1890ff;
				color: #ffffff;

				&:hover {
					background-color: #40a9ff;
					border-color: #40a9ff;
				}
			}

			&.tag-affix {
				background-color: #fff7e6;
				border-color: #ffd591;
				color: #fa8c16;

				&.active {
					background-color: #fa8c16;
					border-color: #fa8c16;
					color: #ffffff;
				}

				&:hover {
					background-color: #ffe7ba;
					border-color: #ffa940;
				}

				&.active:hover {
					background-color: #d46b08;
					border-color: #d46b08;
				}
			}

			:deep(.ant-tag-close-icon) {
				color: inherit;

				&:hover {
					background-color: rgba(255, 255, 255, 0.3);
				}
			}
		}
	}

	.tags-actions {
		display: flex;
		align-items: center;
		gap: 4px;
		margin-left: 12px;
		flex-shrink: 0;

		:deep(.ant-btn) {
			font-size: 14px;
			padding: 2px 6px;

			&:hover {
				color: #1890ff;
			}
		}
	}
}

.context-menu {
	background: #ffffff;
	border-radius: 2px;
	box-shadow:
		0 3px 6px -4px rgba(0, 0, 0, 0.12),
		0 6px 16px 0 rgba(0, 0, 0, 0.08),
		0 9px 28px 8px rgba(0, 0, 0, 0.05);
	border: 1px solid #f0f0f0;
	padding: 4px 0;
	min-width: 160px;

	:deep(.ant-menu) {
		background: transparent;
		border: none;
		box-shadow: none;
		padding: 0;

		.ant-menu-item {
			margin: 0;
			padding: 8px 12px;
			height: auto;
			line-height: normal;

			&:hover {
				background-color: #f5f5f5;
			}
		}
	}
}
</style>
