import { defineStore } from 'pinia'
import { ref } from 'vue'
import { customStorage } from '../persist'

export const useLayoutStore = defineStore(
	'layout',
	() => {
		// 布局模式：'default', 'menu', 'top'
		const layoutMode = ref('default')

		// 侧边栏折叠状态
		const sidebarCollapsed = ref(false)

		// 主题颜色
		const themeColor = ref('#1890ff')

		// 显示标签栏
		const showTags = ref(true)

		// 显示面包屑
		const showBreadcrumb = ref(true)

		// 当前选中的父菜单（用于双栏布局）
		const selectedParentMenu = ref(null)

		// 视图标签页（用于记录页面滚动位置）
		const viewTags = ref([])

		// 刷新标签的 key，用于触发组件刷新
		const refreshKey = ref(0)

		// 切换侧边栏折叠
		const toggleSidebar = () => {
			sidebarCollapsed.value = !sidebarCollapsed.value
		}

		// 设置选中的父菜单
		const setSelectedParentMenu = (menu) => {
			selectedParentMenu.value = menu
		}

		// 设置布局模式
		const setLayoutMode = (mode) => {
			layoutMode.value = mode
		}

		// 更新视图标签
		const updateViewTags = (tag) => {
			const index = viewTags.value.findIndex((item) => item.fullPath === tag.fullPath)
			if (index !== -1) {
				viewTags.value[index] = tag
			} else {
				viewTags.value.push(tag)
			}
		}

		// 移除视图标签
		const removeViewTags = (fullPath) => {
			const index = viewTags.value.findIndex((item) => item.fullPath === fullPath)
			if (index !== -1) {
				viewTags.value.splice(index, 1)
			}
		}

		// 清空视图标签
		const clearViewTags = () => {
			viewTags.value = []
		}

		// 设置主题颜色
		const setThemeColor = (color) => {
			themeColor.value = color
			document.documentElement.style.setProperty('--primary-color', color)
		}

		// 设置标签栏显示
		const setShowTags = (show) => {
			showTags.value = show
			document.documentElement.style.setProperty('--show-tags', show ? 'block' : 'none')
		}

		// 设置面包屑显示
		const setShowBreadcrumb = (show) => {
			showBreadcrumb.value = show
		}

		// 刷新标签
		const refreshTag = () => {
			refreshKey.value++
		}

		// 重置主题设置
		const resetTheme = () => {
			themeColor.value = '#1890ff'
			showTags.value = true
			showBreadcrumb.value = true
			document.documentElement.style.setProperty('--primary-color', '#1890ff')
			document.documentElement.style.setProperty('--show-tags', 'block')
		}

		return {
			layoutMode,
			sidebarCollapsed,
			selectedParentMenu,
			viewTags,
			themeColor,
			showTags,
			showBreadcrumb,
			refreshKey,
			toggleSidebar,
			setLayoutMode,
			setSelectedParentMenu,
			updateViewTags,
			removeViewTags,
			clearViewTags,
			setThemeColor,
			setShowTags,
			setShowBreadcrumb,
			resetTheme,
			refreshTag,
		}
	},
	{
		persist: {
			key: 'layout-store',
			storage: customStorage,
			pick: ['layoutMode', 'sidebarCollapsed', 'themeColor', 'showTags', 'showBreadcrumb', 'viewTags'],
		},
	},
)
