<template>
	<div class="sc-icon-picker">
		<a-input :value="selectedIcon || ''" :placeholder="placeholder" readonly @click="handleOpenPicker">
			<template #prefix v-if="selectedIcon">
				<component :is="selectedIcon" />
			</template>
			<template #suffix>
				<SearchOutlined v-if="!selectedIcon" />
				<CloseCircleFilled v-else @click.stop="handleClear" />
			</template>
		</a-input>

		<a-modal v-model:open="visible" title="选择图标" :width="900" :footer="null" @cancel="handleCancel">
			<div class="icon-picker-content">
				<!-- 搜索框 -->
				<div class="icon-search">
					<a-input v-model:value="searchValue" placeholder="搜索图标名称..." allow-clear @change="handleSearchChange">
						<template #prefix>
							<SearchOutlined />
						</template>
					</a-input>
				</div>

				<!-- 分类标签 -->
				<div class="icon-categories" v-if="!searchValue">
					<a-tag v-for="category in iconCategories" :key="category.key" :class="['category-tag', { active: activeCategory === category.key }]" @click="handleCategoryChange(category.key)">
						{{ category.label }}
					</a-tag>
				</div>

				<!-- 最近使用 -->
				<div v-if="!searchValue && activeCategory === 'recent' && recentIcons.length > 0" class="recent-section">
					<div class="section-title">最近使用</div>
					<div class="icon-list">
						<div v-for="icon in recentIcons" :key="icon" :class="['icon-item', { active: tempIcon === icon }]" @click="handleSelectIcon(icon)">
							<component :is="icon" />
							<div class="icon-name">{{ icon }}</div>
							<CloseCircleFilled class="recent-remove" @click.stop="handleRemoveRecent(icon)" />
						</div>
					</div>
				</div>

				<!-- 图标列表 -->
				<div class="icon-list" v-show="activeCategory !== 'recent' || searchValue || (activeCategory === 'recent' && recentIcons.length === 0)">
					<div v-for="icon in filteredIcons" :key="icon" :class="['icon-item', { active: tempIcon === icon }]" @click="handleSelectIcon(icon)">
						<component :is="icon" />
						<div class="icon-name">{{ icon }}</div>
					</div>
					<a-empty v-if="filteredIcons.length === 0" description="暂无图标" :image="Empty.PRESENTED_IMAGE_SIMPLE" />
				</div>
			</div>
		</a-modal>
	</div>
</template>

<script setup>
/**
 * @component scIconPicker
 * @description 图标选择器组件，支持 Ant Design Vue 图标库
 */
import { ref, computed, watch, onMounted } from 'vue'
import { Empty } from 'ant-design-vue'
import { SearchOutlined, CloseCircleFilled } from '@ant-design/icons-vue'

const props = defineProps({
	modelValue: {
		type: String,
		default: '',
	},
	placeholder: {
		type: String,
		default: '请选择图标',
	},
})

const emit = defineEmits(['update:modelValue', 'change'])

const visible = ref(false)
const activeCategory = ref('all')
const searchValue = ref('')
const tempIcon = ref('')
const recentIcons = ref([])
const RECENT_ICONS_KEY = 'sc-icon-picker-recent'
const MAX_RECENT_ICONS = 12

// 图标分类
const iconCategories = [
	{ key: 'recent', label: '最近使用' },
	{ key: 'all', label: '全部' },
	{ key: 'direction', label: '方向' },
	{ key: 'edit', label: '编辑' },
	{ key: 'data', label: '数据' },
	{ key: 'media', label: '媒体' },
	{ key: 'user', label: '用户' },
	{ key: 'system', label: '系统' },
	{ key: 'commerce', label: '商务' },
]

// Ant Design 图标分类列表（经过验证存在的图标）
const iconCategoriesMap = {
	direction: [
		'ArrowLeftOutlined',
		'ArrowRightOutlined',
		'ArrowUpOutlined',
		'ArrowDownOutlined',
		'LeftOutlined',
		'RightOutlined',
		'UpOutlined',
		'DownOutlined',
		'CaretLeftOutlined',
		'CaretRightOutlined',
		'CaretUpOutlined',
		'CaretDownOutlined',
		'RollbackOutlined',
		'EnterOutlined',
		'RetweetOutlined',
		'SwapOutlined',
		'SwapLeftOutlined',
		'SwapRightOutlined',
		'UpCircleOutlined',
		'DownCircleOutlined',
		'LeftCircleOutlined',
		'RightCircleOutlined',
		'DoubleRightOutlined',
		'DoubleLeftOutlined',
		'VerticalAlignTopOutlined',
		'VerticalAlignBottomOutlined',
		'VerticalAlignMiddleOutlined',
		'FullscreenOutlined',
		'FullscreenExitOutlined',
		'CompressOutlined',
		'ExpandOutlined',
	],
	edit: [
		'EditOutlined',
		'DeleteOutlined',
		'PlusOutlined',
		'MinusOutlined',
		'CheckOutlined',
		'CloseOutlined',
		'FormOutlined',
		'CopyOutlined',
		'ScissorOutlined',
		'SnippetsOutlined',
		'DiffOutlined',
		'HighlightOutlined',
		'AlignLeftOutlined',
		'AlignCenterOutlined',
		'AlignRightOutlined',
		'BoldOutlined',
		'ItalicOutlined',
		'UnderlineOutlined',
		'RedoOutlined',
		'UndoOutlined',
		'FileSyncOutlined',
		'ExportOutlined',
		'ImportOutlined',
		'FileAddOutlined',
		'FolderAddOutlined',
	],
	data: [
		'DatabaseOutlined',
		'CloudOutlined',
		'CloudUploadOutlined',
		'CloudDownloadOutlined',
		'HddOutlined',
		'ServerOutlined',
		'ReconciliationOutlined',
		'AccountBookOutlined',
		'AuditOutlined',
		'BarChartOutlined',
		'AreaChartOutlined',
		'DotChartOutlined',
		'LineChartOutlined',
		'PieChartOutlined',
		'FundOutlined',
		'SlidersOutlined',
		'ControlOutlined',
		'ExperimentOutlined',
		'ProjectOutlined',
		'PartitionOutlined',
		'ApartmentOutlined',
		'BlockOutlined',
		'FunctionOutlined',
	],
	media: [
		'PictureOutlined',
		'VideoCameraOutlined',
		'AudioOutlined',
		'FileImageOutlined',
		'FilePdfOutlined',
		'FileWordOutlined',
		'FileExcelOutlined',
		'FileZipOutlined',
		'FilePptOutlined',
		'FolderOutlined',
		'FolderOpenOutlined',
		'FileTextOutlined',
		'FileOutlined',
		'FileMarkdownOutlined',
		'FileUnknownOutlined',
		'CameraOutlined',
		'QrcodeOutlined',
		'BarcodeOutlined',
		'SoundOutlined',
		'CustomerServiceOutlined',
	],
	user: [
		'UserOutlined',
		'UsergroupAddOutlined',
		'UsergroupDeleteOutlined',
		'TeamOutlined',
		'SolutionOutlined',
		'ContactsOutlined',
		'IdcardOutlined',
		'ProfileOutlined',
		'SmileOutlined',
		'MehOutlined',
		'FrownOutlined',
		'HeartOutlined',
		'StarOutlined',
		'LikeOutlined',
		'DislikeOutlined',
		'ThumbUpOutlined',
		'MessageOutlined',
		'MailOutlined',
		'PhoneOutlined',
	],
	system: [
		'SettingOutlined',
		'HomeOutlined',
		'DashboardOutlined',
		'AppstoreOutlined',
		'MenuFoldOutlined',
		'MenuUnfoldOutlined',
		'BarsOutlined',
		'MoreOutlined',
		'BellOutlined',
		'AlertOutlined',
		'WarningOutlined',
		'CheckCircleOutlined',
		'CloseCircleOutlined',
		'ExclamationCircleOutlined',
		'InfoCircleOutlined',
		'QuestionCircleOutlined',
		'StopOutlined',
		'SafetyOutlined',
		'LockOutlined',
		'UnlockOutlined',
		'KeyOutlined',
		'EyeOutlined',
		'EyeInvisibleOutlined',
		'LogoutOutlined',
		'LoginOutlined',
		'MobileOutlined',
		'ThunderboltOutlined',
		'WifiOutlined',
		'ApiOutlined',
		'BugOutlined',
		'BuildOutlined',
		'CodeOutlined',
		'PoweroffOutlined',
		'HourglassOutlined',
		'SyncOutlined',
	],
	commerce: [
		'ShoppingCartOutlined',
		'ShoppingOutlined',
		'GiftOutlined',
		'GoldOutlined',
		'CrownOutlined',
		'MedalOutlined',
		'TrophyOutlined',
		'DiamondOutlined',
		'BankOutlined',
		'CreditCardOutlined',
		'PayCircleOutlined',
		'WalletOutlined',
		'MoneyCollectOutlined',
		'DollarOutlined',
		'EuroOutlined',
		'PoundOutlined',
		'YenOutlined',
		'GiftFilledOutlined',
		'RocketOutlined',
		'FireOutlined',
		'BulbOutlined',
		'SafetyCertificateOutlined',
		'ShopOutlined',
		'ShoppingBagOutlined',
		'InsuranceOutlined',
	],
	all: [
		// 导航和布局
		'HomeOutlined',
		'DashboardOutlined',
		'AppstoreOutlined',
		'BarsOutlined',
		'MenuFoldOutlined',
		'MenuUnfoldOutlined',
		'MoreOutlined',
		'EllipsisOutlined',
		// 用户
		'UserOutlined',
		'TeamOutlined',
		'UsergroupAddOutlined',
		'UsergroupDeleteOutlined',
		'SolutionOutlined',
		'ContactsOutlined',
		'IdcardOutlined',
		'ProfileOutlined',
		// 设置
		'SettingOutlined',
		'ControlOutlined',
		'BuildOutlined',
		'ToolOutlined',
		// 搜索和过滤
		'SearchOutlined',
		'FilterOutlined',
		'SortAscendingOutlined',
		'SortDescendingOutlined',
		'ReloadOutlined',
		'SyncOutlined',
		'RedoOutlined',
		'UndoOutlined',
		// 编辑
		'EditOutlined',
		'DeleteOutlined',
		'PlusOutlined',
		'MinusOutlined',
		'CheckOutlined',
		'CloseOutlined',
		'CheckCircleOutlined',
		'CloseCircleOutlined',
		'FormOutlined',
		'CopyOutlined',
		'ScissorOutlined',
		// 方向
		'ArrowLeftOutlined',
		'ArrowRightOutlined',
		'ArrowUpOutlined',
		'ArrowDownOutlined',
		'LeftOutlined',
		'RightOutlined',
		'UpOutlined',
		'DownOutlined',
		'CaretLeftOutlined',
		'CaretRightOutlined',
		'CaretUpOutlined',
		'CaretDownOutlined',
		'RollbackOutlined',
		'EnterOutlined',
		'SwapOutlined',
		'UpCircleOutlined',
		'DownCircleOutlined',
		'LeftCircleOutlined',
		'RightCircleOutlined',
		// 文件
		'FileTextOutlined',
		'FileOutlined',
		'FileAddOutlined',
		'FileExcelOutlined',
		'FilePdfOutlined',
		'FileWordOutlined',
		'FilePptOutlined',
		'FileImageOutlined',
		'FileUnknownOutlined',
		'FileMarkdownOutlined',
		'FileZipOutlined',
		'FolderOutlined',
		'FolderAddOutlined',
		'FolderOpenOutlined',
		// 媒体
		'PictureOutlined',
		'VideoCameraOutlined',
		'AudioOutlined',
		'CameraOutlined',
		'SoundOutlined',
		'QrcodeOutlined',
		'BarcodeOutlined',
		// 时间
		'CalendarOutlined',
		'ClockCircleOutlined',
		'HistoryOutlined',
		'FieldTimeOutlined',
		'HourglassOutlined',
		'CarryOutOutlined',
		// 社交
		'HeartOutlined',
		'StarOutlined',
		'LikeOutlined',
		'DislikeOutlined',
		'ThumbUpOutlined',
		'MessageOutlined',
		'MailOutlined',
		'PhoneOutlined',
		'SmileOutlined',
		'MehOutlined',
		'FrownOutlined',
		// 位置
		'EnvironmentOutlined',
		'GlobalOutlined',
		'CompassOutlined',
		'MapOutlined',
		// 安全
		'LockOutlined',
		'UnlockOutlined',
		'KeyOutlined',
		'SafetyOutlined',
		'EyeOutlined',
		'EyeInvisibleOutlined',
		'SafetyCertificateOutlined',
		// 通知
		'BellOutlined',
		'AlertOutlined',
		'WarningOutlined',
		'InfoCircleOutlined',
		'QuestionCircleOutlined',
		'ExclamationCircleOutlined',
		'StopOutlined',
		// 云和数据
		'DatabaseOutlined',
		'CloudOutlined',
		'HddOutlined',
		'ServerOutlined',
		'CloudUploadOutlined',
		'CloudDownloadOutlined',
		// 设备
		'WifiOutlined',
		'ApiOutlined',
		'CodeOutlined',
		'LaptopOutlined',
		'MobileOutlined',
		'TabletOutlined',
		'DesktopOutlined',
		// 状态
		'ThunderboltOutlined',
		'BulbOutlined',
		'FireOutlined',
		'ExperimentOutlined',
		'CheckSquareOutlined',
		'MinusSquareOutlined',
		'CloseSquareOutlined',
		// 商务
		'ShoppingCartOutlined',
		'ShoppingOutlined',
		'ShoppingBagOutlined',
		'ShopOutlined',
		'GiftOutlined',
		'GiftFilledOutlined',
		'WalletOutlined',
		'CreditCardOutlined',
		'BankOutlined',
		'PayCircleOutlined',
		'MoneyCollectOutlined',
		'DollarOutlined',
		'EuroOutlined',
		'PoundOutlined',
		'YenOutlined',
		// 奖项
		'MedalOutlined',
		'TrophyOutlined',
		'CrownOutlined',
		'GoldOutlined',
		'DiamondOutlined',
		// 其他
		'RocketOutlined',
		'FundOutlined',
		'PieChartOutlined',
		'BarChartOutlined',
		'AreaChartOutlined',
		'LineChartOutlined',
		'DotChartOutlined',
		'UploadOutlined',
		'DownloadOutlined',
		'ImportOutlined',
		'ExportOutlined',
		'ScanOutlined',
		'PrinterOutlined',
		'RetweetOutlined',
		'SwapOutlined',
		'ShareAltOutlined',
		'PoweroffOutlined',
		'LoginOutlined',
		'LogoutOutlined',
		'BugOutlined',
		'HourglassOutlined',
	],
}

// 加载最近使用的图标
const loadRecentIcons = () => {
	try {
		const stored = localStorage.getItem(RECENT_ICONS_KEY)
		if (stored) {
			recentIcons.value = JSON.parse(stored)
		}
	} catch (error) {
		console.error('加载最近使用图标失败:', error)
	}
}

// 保存最近使用的图标
const saveRecentIcons = (icon) => {
	if (!icon) return

	// 移除已存在的相同图标
	const index = recentIcons.value.indexOf(icon)
	if (index > -1) {
		recentIcons.value.splice(index, 1)
	}

	// 添加到开头
	recentIcons.value.unshift(icon)

	// 限制数量
	if (recentIcons.value.length > MAX_RECENT_ICONS) {
		recentIcons.value = recentIcons.value.slice(0, MAX_RECENT_ICONS)
	}

	// 保存到本地存储
	try {
		localStorage.setItem(RECENT_ICONS_KEY, JSON.stringify(recentIcons.value))
	} catch (error) {
		console.error('保存最近使用图标失败:', error)
	}
}

// 移除最近使用的图标
const handleRemoveRecent = (icon) => {
	const index = recentIcons.value.indexOf(icon)
	if (index > -1) {
		recentIcons.value.splice(index, 1)
		try {
			localStorage.setItem(RECENT_ICONS_KEY, JSON.stringify(recentIcons.value))
		} catch (error) {
			console.error('保存最近使用图标失败:', error)
		}
	}
}

// 当前选中的图标
const selectedIcon = ref(props.modelValue)

// 获取当前分类的图标
const currentCategoryIcons = computed(() => {
	if (activeCategory.value === 'all') {
		return iconCategoriesMap.all
	}
	return iconCategoriesMap[activeCategory.value] || []
})

// 过滤后的图标
const filteredIcons = computed(() => {
	let icons = []

	if (searchValue.value) {
		// 搜索时从所有图标中筛选
		const allIcons = iconCategoriesMap.all
		icons = allIcons.filter((icon) => icon.toLowerCase().includes(searchValue.value.toLowerCase()))
	} else if (activeCategory.value === 'recent') {
		// 最近使用时不显示其他图标
		icons = []
	} else {
		// 根据分类显示
		icons = currentCategoryIcons.value
	}

	return icons
})

// 打开选择器
const handleOpenPicker = () => {
	tempIcon.value = props.modelValue
	visible.value = true
}

// 清除选择
const handleClear = () => {
	emit('update:modelValue', '')
	emit('change', '')
}

// 切换分类
const handleCategoryChange = (key) => {
	activeCategory.value = key
}

// 搜索变化
const handleSearchChange = () => {
	// 搜索时重置分类
	if (searchValue.value) {
		activeCategory.value = 'all'
	}
}

// 选择图标（直接确认并关闭）
const handleSelectIcon = (icon) => {
	emit('update:modelValue', icon)
	emit('change', icon)
	selectedIcon.value = icon

	// 添加到最近使用
	saveRecentIcons(icon)

	visible.value = false
}

// 取消选择
const handleCancel = () => {
	visible.value = false
}

// 监听 props 变化，更新本地状态
watch(
	() => props.modelValue,
	(newVal) => {
		selectedIcon.value = newVal
	},
)

// 组件挂载时加载最近使用的图标
onMounted(() => {
	loadRecentIcons()
})
</script>

<style scoped lang="scss">
.sc-icon-picker {
	:deep(.ant-input) {
		cursor: pointer;
	}
}

.icon-picker-content {
	.icon-search {
		margin-bottom: 16px;
	}

	.icon-categories {
		display: flex;
		flex-wrap: wrap;
		gap: 8px;
		margin-bottom: 16px;
		padding: 12px;
		background: #fafafa;
		border-radius: 6px;

		.category-tag {
			cursor: pointer;
			transition: all 0.3s;
			user-select: none;
			margin: 0;

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

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

	.recent-section {
		margin-bottom: 16px;

		.section-title {
			font-size: 14px;
			font-weight: 500;
			color: #333;
			margin-bottom: 12px;
			padding-left: 4px;
		}
	}

	.icon-list {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
		gap: 12px;
		max-height: 400px;
		overflow-y: auto;
		padding: 4px;

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

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

			&:hover {
				background: #bfbfbf;
			}
		}

		.icon-item {
			position: relative;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 12px 8px;
			border: 1px solid #d9d9d9;
			border-radius: 6px;
			cursor: pointer;
			transition: all 0.3s;
			background: #fff;

			&:hover {
				border-color: #1890ff;
				color: #1890ff;
				transform: translateY(-2px);
				box-shadow: 0 2px 8px rgba(24, 144, 255, 0.15);

				.recent-remove {
					opacity: 1;
				}
			}

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

			:deep(svg) {
				font-size: 28px;
				margin-bottom: 8px;
			}

			.icon-name {
				font-size: 12px;
				color: #666;
				text-align: center;
				word-break: break-all;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				width: 100%;
				line-height: 1.2;
			}

			.recent-remove {
				position: absolute;
				top: 4px;
				right: 4px;
				font-size: 14px;
				color: #ff4d4f;
				opacity: 0;
				transition: opacity 0.3s;
				padding: 2px;
				border-radius: 50%;

				&:hover {
					background-color: rgba(255, 77, 95, 0.1);
				}
			}
		}
	}
}

:deep(.ant-modal-body) {
	padding: 16px 24px;
}
</style>
