<script setup lang="ts">
import { computed } from 'vue';
import * as AntdIcons from '@ant-design/icons-vue';

defineOptions({
  name: 'SvgIcon'
});

interface Props {
  /** 图标名称 */
  name: string;
  /** 图标类型: 'svg' | 'antd' */
  type?: 'svg' | 'antd';
  /** 图标尺寸 (支持CSS单位) */
  size?: string | number;
  /** 图标颜色 */
  color?: string;
  /** 旋转动画 */
  spin?: boolean;
  /** 自定义类名 */
  className?: string;
}

// 设置默认属性值
const props = withDefaults(defineProps<Props>(), {
  type: 'svg',
  size: '1em',
  color: 'currentColor',
  spin: false,
  className: ''
});

// 动态解析Ant Design图标
const antdIcon = computed(() => {
  if (props.type !== 'antd') return null;
  
  const iconComponent = AntdIcons[props.name as keyof typeof AntdIcons] as any;
  
  if (!iconComponent) {
    console.warn(`Ant Design图标未找到: ${props.name}`);
  }
  
  return iconComponent || null;
});

// 处理尺寸值，确保有单位
const formattedSize = computed(() => {
  if (typeof props.size === 'number') return `${props.size}px`;
  return props.size;
});

// 自定义样式
const style = computed(() => ({
  width: formattedSize.value,
  height: formattedSize.value,
  color: props.color,
  animation: props.spin ? 'icon-spin 1s infinite linear' : 'none'
}));
</script>

<template>
  <!-- SVG图标 -->
  <svg 
    v-if="type === 'svg'"
    :class="['svg-icon', className]"
    :style="style"
    aria-hidden="true"
  >
    <use :xlink:href="`#icon-${name}`" />
  </svg>
  
  <!-- Ant Design图标 -->
  <component 
    v-else-if="type === 'antd' && antdIcon"
    :is="antdIcon"
    v-bind="{ 
      spin, 
      style: { 
        color, 
        fontSize: formattedSize
      } 
    }"
  />
  
  <!-- 图标未找到时的回退 -->
  <span 
    v-else
    class="icon-fallback"
    :style="{ fontSize: formattedSize }"
  >
    ?
  </span>
</template>

<style scoped>
.svg-icon {
  display: inline-block;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
  transition: transform 0.3s ease;
}

.icon-fallback {
  display: inline-block;
  width: 1em;
  height: 1em;
  line-height: 1;
  text-align: center;
  background-color: #f0f0f0;
  border-radius: 2px;
  font-weight: bold;
  color: #999;
}

@keyframes icon-spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>