<template>
  <div class="icon-gallery" :style="containerStyle">
    <!-- 搜索框 -->
    <a-input
      v-if="showSearch"
      v-model:value="keyword"
      placeholder="搜索图标名称..."
      allow-clear
      class="search-input"
      :size="searchSize"
    />

    <!-- 图标网格 -->
    <div class="icons-grid" :style="gridStyle">
      <div
        v-for="item in filteredIcons"
        :key="item.name"
        class="icon-item"
        :style="itemStyle"
        @mouseenter="handleMouseEnter(item.name)"
        @mouseleave="handleMouseLeave"
      >
        <component :is="item.component" class="icon" :style="iconStyle" />
        <span class="icon-name">{{ item.name }}</span>
        
        <!-- 复制按钮 - 仅在hover时显示 -->
        <div v-if="hoveredIcon === item.name" class="copy-buttons">
          <a-button 
            type="primary" 
            size="small" 
            @click.stop="copyWithTags(item.name)"
            class="copy-btn"
          >
            <CopyOutlined class="mr-1" />标签
          </a-button>
          <a-button 
            type="default" 
            size="small" 
            @click.stop="copyName(item.name)"
            class="copy-btn"
          >
            <CopyOutlined class="mr-1" />名称
          </a-button>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="filteredIcons.length === 0" class="empty-state">
      <a-empty description="没有找到匹配的图标" />
    </div>

    <!-- 复制提示 -->
    <a-message
      v-if="showMessage"
      :content="messageContent"
      :type="messageType"
      :duration="messageDuration"
      class="copy-message"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, ref, PropType, onMounted } from 'vue'
import * as Icons from '@ant-design/icons-vue'
import { Input, Button, Empty, Message } from 'ant-design-vue'
import { CopyOutlined } from '@ant-design/icons-vue'

// 定义组件属性
const props = defineProps({
  // 是否显示搜索框
  showSearch: {
    type: Boolean,
    default: true
  },
  // 搜索框尺寸
  searchSize: {
    type: String as PropType<'small' | 'middle' | 'large'>,
    default: 'middle'
  },
  // 网格列数
  columns: {
    type: Number,
    default: 6
  },
  // 图标大小
  iconSize: {
    type: Number,
    default: 24
  },
  // 每个图标项的内边距
  itemPadding: {
    type: String,
    default: '16px'
  },
  // 复制提示消息持续时间(毫秒)
  messageDuration: {
    type: Number,
    default: 2000
  }
})

// 过滤掉非图标成员
const exclude = [
  'createFromIconfontCN',
  'getTwoToneColor',
  'setTwoToneColor',
  'default',
  'CopyOutlined' // 排除我们在按钮中使用的复制图标
]

// 生成图标列表
const iconList = Object.entries(Icons)
  .filter(([name]) => !exclude.includes(name))
  .map(([name, component]) => ({ name, component }))

// 搜索相关
const keyword = ref('')
const filteredIcons = computed(() => {
  if (!keyword.value) return iconList
  
  return iconList.filter(({ name }) =>
    name.toLowerCase().includes(keyword.value.toLowerCase())
  )
})

// 交互状态
const hoveredIcon = ref('')
const showMessage = ref(false)
const messageContent = ref('')
const messageType = ref<'success' | 'error'>('success')

// 处理鼠标悬停
function handleMouseEnter(iconName: string) {
  hoveredIcon.value = iconName
}

function handleMouseLeave() {
  hoveredIcon.value = ''
}

// 复制功能
function copyWithTags(name: string) {
  const code = `<${name} />`
  copyToClipboard(code)
    .then(() => {
      showMessageToast(`已复制: ${code}`, 'success')
    })
    .catch(() => {
      showMessageToast('复制失败，请手动复制', 'error')
    })
}

function copyName(name: string) {
  copyToClipboard(name)
    .then(() => {
      showMessageToast(`已复制: ${name}`, 'success')
    })
    .catch(() => {
      showMessageToast('复制失败，请手动复制', 'error')
    })
}

// 复制到剪贴板
async function copyToClipboard(text: string): Promise<boolean> {
  try {
    await navigator.clipboard.writeText(text)
    return true
  } catch (err) {
    console.error('无法复制文本: ', err)
    return false
  }
}

// 显示消息提示
function showMessageToast(content: string, type: 'success' | 'error') {
  messageContent.value = content
  messageType.value = type
  showMessage.value = true
  
  setTimeout(() => {
    showMessage.value = false
  }, props.messageDuration)
}

// 计算样式
const containerStyle = computed(() => ({
  padding: '16px',
  backgroundColor: '#f5f5f5',
  borderRadius: '4px'
}))

const gridStyle = computed(() => ({
  display: 'grid',
  gridTemplateColumns: `repeat(${props.columns}, 1fr)`,
  gap: '12px',
  marginTop: props.showSearch ? '16px' : 0
}))

const itemStyle = computed(() => ({
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'center',
  backgroundColor: '#fff',
  border: '1px solid #e8e8e8',
  borderRadius: '6px',
  padding: props.itemPadding,
  cursor: 'pointer',
  transition: 'all 0.2s'
}))

const iconStyle = computed(() => ({
  fontSize: `${props.iconSize}px`,
  color: '#262626',
  marginBottom: '8px'
}))
</script>

<style scoped>
.icon-gallery {
  width: 100%;
  box-sizing: border-box;
}

.search-input {
  max-width: 400px;
}

.icons-grid {
  width: 100%;
  box-sizing: border-box;
}

.icon-item:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.icon-name {
  font-size: 12px;
  color: #595959;
  text-align: center;
  word-break: break-all;
  max-width: 100%;
}

.copy-buttons {
  display: flex;
  gap: 8px;
  margin-top: 8px;
  width: 100%;
  justify-content: center;
}

.copy-btn {
  padding: 2px 8px !important;
  font-size: 12px !important;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

.copy-message {
  position: fixed;
  bottom: 24px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1000;
}
</style>
