<template>
	<div class="quick-actions-component">
		<a-card :bordered="false" class="quick-actions-card">
			<template #title>
				<div class="card-title">
					<ThunderboltOutlined class="title-icon" />
					<span>快速操作</span>
				</div>
			</template>
			<template #extra>
				<a-button type="primary" size="small" @click="showCustomizeModal = true">
					<SettingOutlined />
					自定义
				</a-button>
			</template>

			<div class="actions-container">
				<transition-group name="list" tag="div" class="actions-grid">
					<div v-for="action in displayActions" :key="action.path" class="action-item" :class="{ 'no-actions': displayActions.length === 0 }" @click="handleActionClick(action)">
						<div
							class="action-icon-wrapper"
							:style="{
								background: action.gradient || getGradient(action.color),
							}"
						>
							<component :is="action.icon || 'AppstoreOutlined'" class="action-icon" />
						</div>
						<div class="action-content">
							<div class="action-title">{{ action.title }}</div>
						</div>
					</div>
				</transition-group>

				<div v-if="displayActions.length === 0" class="empty-state">
					<a-empty description="暂无快速操作" />
					<a-button type="link" @click="showCustomizeModal = true">
						<PlusOutlined />
						添加操作
					</a-button>
				</div>
			</div>
		</a-card>

		<!-- 自定义快速操作弹窗 -->
		<a-modal v-model:open="showCustomizeModal" title="自定义快速操作" :width="700" :footer="null" class="customize-modal">
			<div class="customize-content">
				<!-- 已添加的操作 -->
				<div class="section">
					<div class="section-header">
						<h3 class="section-title">已添加的操作</h3>
						<a-tag :color="tempCustomActions.length >= 8 ? 'error' : 'blue'"> {{ tempCustomActions.length }}/8 </a-tag>
					</div>
					<div class="selected-actions">
						<div class="drag-container">
							<div v-for="(action, index) in tempCustomActions" :key="action.path" class="action-tag" :style="{ borderColor: action.color }">
								<div
									class="tag-icon"
									:style="{
										background: getGradient(action.color),
									}"
								>
									<component :is="action.icon || 'AppstoreOutlined'" />
								</div>
								<span class="tag-title">{{ action.title }}</span>
								<CloseOutlined class="tag-close" @click="handleRemoveAction(action)" />
							</div>
						</div>
						<a-empty v-if="tempCustomActions.length === 0" description="从下方列表选择添加" />
					</div>
				</div>

				<!-- 可选操作 -->
				<div class="section">
					<div class="section-header">
						<h3 class="section-title">可选操作</h3>
						<a-tag color="cyan">{{ availableMenus.length }}个可用</a-tag>
					</div>
					<a-input-search v-model:value="searchKeyword" placeholder="搜索菜单名称或路径..." allow-clear size="large" class="search-input">
						<template #prefix>
							<SearchOutlined />
						</template>
					</a-input-search>
					<div class="available-actions">
						<div v-for="menu in filteredMenus" :key="menu.path" class="menu-item" :class="{ disabled: isAdded(menu) }" @click="handleAddAction(menu)">
							<div
								class="menu-icon"
								:style="{
									background: getGradient(menu.meta?.iconColor),
								}"
							>
								<component :is="menu.meta?.icon || 'AppstoreOutlined'" />
							</div>
							<div class="menu-info">
								<div class="menu-title">
									{{ menu.meta?.title || menu.title || menu.name }}
								</div>
								<div class="menu-path">{{ menu.path }}</div>
							</div>
							<div class="menu-action">
								<a-button v-if="!isAdded(menu)" type="primary" size="small" ghost>
									<PlusOutlined />
									添加
								</a-button>
								<a-tag v-else color="success">
									<CheckOutlined />
									已添加
								</a-tag>
							</div>
						</div>
						<a-empty v-if="filteredMenus.length === 0" description="未找到匹配的操作" />
					</div>
				</div>
			</div>

			<!-- 底部操作按钮 -->
			<div class="modal-footer">
				<a-space>
					<a-button @click="handleCancelCustomize">取消</a-button>
					<a-button type="primary" @click="handleSaveCustomActions" :loading="saving">
						<SaveOutlined />
						保存配置
					</a-button>
				</a-space>
			</div>
		</a-modal>
	</div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/modules/user'
import { SettingOutlined, PlusOutlined, CheckOutlined, AppstoreOutlined, ThunderboltOutlined, CloseOutlined, SearchOutlined, SaveOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'

defineOptions({
	name: 'QuickActions',
})

const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const showCustomizeModal = ref(false)
const searchKeyword = ref('')
const saving = ref(false)
const customActions = ref([])
const tempCustomActions = ref([])

// 默认快速操作
const defaultActions = ref([])

// 渐变色映射
const gradientColors = {
	'#1890ff': 'linear-gradient(135deg, #1890ff 0%, #36cfc9 100%)',
	'#52c41a': 'linear-gradient(135deg, #52c41a 0%, #95de64 100%)',
	'#faad14': 'linear-gradient(135deg, #faad14 0%, #ffc53d 100%)',
	'#f5222d': 'linear-gradient(135deg, #f5222d 0%, #ff4d4f 100%)',
	'#722ed1': 'linear-gradient(135deg, #722ed1 0%, #9254de 100%)',
	'#eb2f96': 'linear-gradient(135deg, #eb2f96 0%, #f759ab 100%)',
	'#13c2c2': 'linear-gradient(135deg, #13c2c2 0%, #36cfc9 100%)',
	'#fa8c16': 'linear-gradient(135deg, #fa8c16 0%, #ffa940 100%)',
}

// 获取渐变色
const getGradient = (color) => {
	if (!color) return gradientColors['#1890ff']
	return gradientColors[color] || gradientColors['#1890ff']
}

// 可用的菜单列表（扁平化所有菜单项）
const availableMenus = computed(() => {
	const menus = userStore.menu || []
	const flattenMenus = []

	const traverse = (menuList) => {
		menuList.forEach((menu) => {
			// 兼容不同的菜单数据结构
			const menuType = menu.type || (menu.path ? 'menu' : '')
			if (menuType === 'menu' && menu.path && !menu.meta?.hidden) {
				flattenMenus.push({
					...menu,
					title: menu.meta?.title || menu.title || menu.name,
					icon: menu.meta?.icon || 'AppstoreOutlined',
				})
			}
			if (menu.children && menu.children.length > 0) {
				traverse(menu.children)
			}
		})
	}

	traverse(menus)
	return flattenMenus
})

// 显示的快速操作
const displayActions = computed(() => {
	if (customActions.value.length > 0) {
		return customActions.value
	}
	return defaultActions.value
})

// 过滤后的菜单
const filteredMenus = computed(() => {
	if (!searchKeyword.value) {
		return availableMenus.value.slice(0, 50)
	}
	const keyword = searchKeyword.value.toLowerCase()
	return availableMenus.value.filter((menu) => {
		const title = (menu.meta?.title || menu.title || menu.name || '').toLowerCase()
		const path = (menu.path || '').toLowerCase()
		return title.includes(keyword) || path.includes(keyword)
	})
})

// 检查是否已添加
const isAdded = (menu) => {
	return tempCustomActions.value.some((action) => action.path === menu.path)
}

// 加载自定义操作
const loadCustomActions = () => {
	try {
		const saved = localStorage.getItem('quick-actions')
		if (saved) {
			customActions.value = JSON.parse(saved)
		} else {
			setDefaultActions()
		}
	} catch (error) {
		console.error('加载自定义操作失败:', error)
		setDefaultActions()
	}
}

// 设置默认快速操作
const setDefaultActions = () => {
	const menus = availableMenus.value
	const commonPaths = ['/system/users', '/system/roles', '/system/permissions', '/system/config']
	defaultActions.value = menus
		.filter((menu) => commonPaths.includes(menu.path))
		.map((menu) => ({
			...menu,
			color: getRandomColor(),
		}))
		.slice(0, 8)
}

// 获取随机颜色
const getRandomColor = () => {
	const colors = ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1', '#eb2f96', '#13c2c2', '#fa8c16']
	return colors[Math.floor(Math.random() * colors.length)]
}

// 添加操作
const handleAddAction = (menu) => {
	if (tempCustomActions.value.length >= 8) {
		message.warning('最多添加8个快速操作')
		return
	}
	if (isAdded(menu)) {
		message.info('该操作已添加')
		return
	}
	tempCustomActions.value.push({
		path: menu.path,
		title: menu.title,
		icon: menu.icon,
		color: getRandomColor(),
	})
	message.success(`已添加: ${menu.title}`)
}

// 移除操作
const handleRemoveAction = (action) => {
	const index = tempCustomActions.value.findIndex((item) => item.path === action.path)
	if (index > -1) {
		tempCustomActions.value.splice(index, 1)
		message.success(`已移除: ${action.title}`)
	}
}

// 保存自定义操作
const handleSaveCustomActions = () => {
	if (tempCustomActions.value.length === 0) {
		message.warning('请至少添加一个快速操作')
		return
	}
	saving.value = true
	try {
		customActions.value = [...tempCustomActions.value]
		localStorage.setItem('quick-actions', JSON.stringify(customActions.value))
		setTimeout(() => {
			saving.value = false
			showCustomizeModal.value = false
			message.success('保存成功，快速操作已更新')
		}, 500)
	} catch (error) {
		saving.value = false
		message.error('保存失败，请重试')
	}
}

// 取消自定义
const handleCancelCustomize = () => {
	showCustomizeModal.value = false
}

// 点击操作项
const handleActionClick = (action) => {
	if (action.path) {
		router.push(action.path)
	}
}

// 监听弹窗打开
watch(showCustomizeModal, (newVal) => {
	if (newVal) {
		tempCustomActions.value = [...customActions.value]
		searchKeyword.value = ''
	}
})

// 监听菜单变化
watch(
	() => userStore.menu,
	(newMenu) => {
		if (newMenu && newMenu.length > 0 && customActions.value.length === 0) {
			setDefaultActions()
		}
	},
	{ immediate: true },
)

onMounted(() => {
	loading.value = true
	loadCustomActions()
	loading.value = false
})
</script>

<style scoped lang="scss">
.quick-actions-component {
	.quick-actions-card {
		background: #fff;
		border-radius: 12px;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);

		:deep(.ant-card-head) {
			border-bottom: 1px solid #f0f0f0;
			padding: 16px 24px;
		}

		:deep(.ant-card-body) {
			padding: 20px;
		}

		.card-title {
			display: flex;
			align-items: center;
			gap: 8px;
			font-size: 16px;
			font-weight: 600;
			color: rgba(0, 0, 0, 0.85);

			.title-icon {
				color: #1890ff;
				font-size: 18px;
			}
		}
	}

	.actions-container {
		min-height: 200px;

		.actions-grid {
			display: grid;
			grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
			gap: 16px;
		}

		.action-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 20px 16px;
			background: #fafafa;
			border-radius: 12px;
			cursor: pointer;
			transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
			border: 2px solid transparent;

			&:hover {
				background: #fff;
				box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
				transform: translateY(-4px);

				.action-icon-wrapper {
					transform: scale(1.1) rotate(5deg);
				}
			}

			&:active {
				transform: translateY(-2px);
			}

			.action-icon-wrapper {
				width: 64px;
				height: 64px;
				display: flex;
				align-items: center;
				justify-content: center;
				border-radius: 16px;
				margin-bottom: 12px;
				transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
				box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);

				.action-icon {
					font-size: 28px;
					color: #fff;
				}
			}

			.action-content {
				text-align: center;

				.action-title {
					font-size: 14px;
					font-weight: 500;
					color: rgba(0, 0, 0, 0.85);
					line-height: 1.4;
					display: -webkit-box;
					-webkit-line-clamp: 2;
					-webkit-box-orient: vertical;
					overflow: hidden;
				}
			}
		}

		.empty-state {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			min-height: 200px;
			padding: 40px;

			:deep(.ant-empty) {
				margin-bottom: 16px;
			}
		}
	}

	.list-enter-active,
	.list-leave-active {
		transition: all 0.3s ease;
	}

	.list-enter-from {
		opacity: 0;
		transform: translateY(20px);
	}

	.list-leave-to {
		opacity: 0;
		transform: scale(0.8);
	}
}

// 自定义弹窗样式
:deep(.customize-modal) {
	.ant-modal-content {
		border-radius: 12px;
		overflow: hidden;
	}

	.ant-modal-header {
		border-bottom: 1px solid #f0f0f0;
		padding: 20px 24px;
	}

	.ant-modal-body {
		padding: 24px;
		max-height: 70vh;
		overflow-y: auto;
	}
}

.customize-content {
	.section {
		margin-bottom: 24px;

		&:last-child {
			margin-bottom: 0;
		}

		.section-header {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 16px;

			.section-title {
				margin: 0;
				font-size: 16px;
				font-weight: 600;
				color: rgba(0, 0, 0, 0.85);
			}
		}

		.selected-actions {
			min-height: 80px;
			padding: 16px;
			background: #fafafa;
			border-radius: 8px;
			border: 2px dashed #d9d9d9;
			transition: all 0.3s ease;

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

			.drag-container {
				display: flex;
				flex-wrap: wrap;
				gap: 12px;
			}

			.action-tag {
				display: flex;
				align-items: center;
				gap: 8px;
				padding: 8px 16px;
				background: #fff;
				border: 2px solid #e8e8e8;
				border-radius: 8px;
				cursor: move;
				transition: all 0.3s ease;

				&:hover {
					box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

					.tag-close {
						opacity: 1;
					}
				}

				.tag-icon {
					width: 32px;
					height: 32px;
					display: flex;
					align-items: center;
					justify-content: center;
					border-radius: 6px;

					:deep(.anticon) {
						font-size: 16px;
						color: #fff;
					}
				}

				.tag-title {
					font-size: 14px;
					font-weight: 500;
					color: rgba(0, 0, 0, 0.85);
				}

				.tag-close {
					opacity: 0;
					transition: opacity 0.3s ease;
					cursor: pointer;
					color: rgba(0, 0, 0, 0.45);

					&:hover {
						color: #f5222d;
					}
				}
			}

			:deep(.ant-empty) {
				margin: 20px 0;
			}
		}

		.search-input {
			margin-bottom: 16px;

			:deep(.ant-input) {
				border-radius: 8px;
			}
		}

		.available-actions {
			max-height: 400px;
			overflow-y: auto;
			border: 1px solid #f0f0f0;
			border-radius: 8px;

			.menu-item {
				display: flex;
				align-items: center;
				padding: 16px;
				cursor: pointer;
				transition: all 0.3s ease;
				border-bottom: 1px solid #f0f0f0;

				&:hover {
					background: #fafafa;
				}

				&:last-child {
					border-bottom: none;
				}

				&.disabled {
					opacity: 0.5;
					cursor: not-allowed;

					&:hover {
						background: transparent;
					}
				}

				.menu-icon {
					width: 48px;
					height: 48px;
					display: flex;
					align-items: center;
					justify-content: center;
					border-radius: 10px;
					margin-right: 16px;
					flex-shrink: 0;

					:deep(.anticon) {
						font-size: 24px;
						color: #fff;
					}
				}

				.menu-info {
					flex: 1;
					min-width: 0;

					.menu-title {
						font-size: 15px;
						font-weight: 500;
						color: rgba(0, 0, 0, 0.85);
						margin-bottom: 4px;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}

					.menu-path {
						font-size: 13px;
						color: rgba(0, 0, 0, 0.45);
						font-family: 'Courier New', monospace;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}
				}

				.menu-action {
					flex-shrink: 0;
				}

				&::-webkit-scrollbar {
					width: 6px;
				}

				&::-webkit-scrollbar-thumb {
					background: #d9d9d9;
					border-radius: 3px;

					&:hover {
						background: #bfbfbf;
					}
				}
			}

			:deep(.ant-empty) {
				margin: 40px 0;
			}
		}
	}

	.modal-footer {
		display: flex;
		justify-content: flex-end;
		padding-top: 24px;
		border-top: 1px solid #f0f0f0;
	}
}

// 响应式设计
@media (max-width: 768px) {
	.quick-actions-component {
		.actions-container {
			.actions-grid {
				grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
				gap: 12px;
			}

			.action-item {
				padding: 16px 12px;

				.action-icon-wrapper {
					width: 56px;
					height: 56px;

					.action-icon {
						font-size: 24px;
					}
				}

				.action-title {
					font-size: 13px;
				}
			}
		}

		:deep(.customize-modal) {
			.ant-modal {
				max-width: 95vw;
			}

			.ant-modal-body {
				max-height: 60vh;
				padding: 16px;
			}
		}

		.customize-content {
			.selected-actions {
				.action-tag {
					padding: 6px 12px;

					.tag-icon {
						width: 28px;
						height: 28px;

						:deep(.anticon) {
							font-size: 14px;
						}
					}

					.tag-title {
						font-size: 13px;
					}
				}
			}

			.available-actions {
				.menu-item {
					padding: 12px;

					.menu-icon {
						width: 40px;
						height: 40px;
						margin-right: 12px;

						:deep(.anticon) {
							font-size: 20px;
						}
					}

					.menu-info {
						.menu-title {
							font-size: 14px;
						}

						.menu-path {
							font-size: 12px;
						}
					}
				}
			}
		}
	}
}
</style>
