<template>
  <div class="app-container icon-manager">
    <!-- 搜索区域 -->
    <div class="search-header">
      <el-input
        v-model="searchQuery"
        placeholder="搜索图标名称..."
        prefix-icon="Search"
        clearable
        class="search-input"
      />
      <div class="header-right">
        <div class="icon-stats">
          共 <span class="count">{{ filteredIcons.length }}</span> 个图标
        </div>
        <el-button v-if="isDev" type="primary" icon="Plus" @click="showUploadDialog = true" v-hasPermi="['tool:icon:add']">
          上传图标
        </el-button>
      </div>
    </div>

    <!-- 图标网格 -->
    <div class="icon-grid">
      <div
        v-for="icon in filteredIcons"
        :key="icon"
        class="icon-item"
        @click="handleCopy(icon)"
      >
        <div class="icon-wrapper">
          <svg-icon :icon-class="icon" class="icon-preview" />
        </div>
        <div class="icon-name">{{ icon }}</div>
        <div class="icon-actions">
          <el-tooltip content="复制名称" placement="top">
            <el-button type="primary" link size="small" @click.stop="handleCopy(icon)">
              <el-icon><DocumentCopy /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="复制组件代码" placement="top">
            <el-button type="primary" link size="small" @click.stop="handleCopyComponent(icon)">
              <el-icon><CopyDocument /></el-icon>
            </el-button>
          </el-tooltip>
        </div>
      </div>
    </div>

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

    <!-- 上传对话框 -->
    <el-dialog v-model="showUploadDialog" title="上传图标" width="500px">
      <el-upload
        ref="uploadRef"
        drag
        :auto-upload="false"
        :limit="10"
        accept=".svg"
        :on-change="handleFileChange"
      >
        <el-icon class="el-icon--upload"><Upload /></el-icon>
        <div class="el-upload__text">将SVG文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">只能上传 SVG 格式，上传后刷新页面即可使用</div>
        </template>
      </el-upload>
      <template #footer>
        <el-button @click="showUploadDialog = false">取消</el-button>
        <el-button type="primary" @click="handleUpload" :loading="uploading">确认上传</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { DocumentCopy, CopyDocument, Upload } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { uploadIcon } from '@/api/system/icon'

const searchQuery = ref('')
const showUploadDialog = ref(false)
const uploading = ref(false)
const uploadRef = ref(null)
const uploadFiles = ref([])

// 判断是否开发环境
const isDev = import.meta.env.DEV

// 获取所有图标
const iconModules = import.meta.glob('@/assets/icons/svg/*.svg', { eager: true })
const allIcons = Object.keys(iconModules).map(path => {
  const fileName = path.split('/').pop()
  return fileName.replace('.svg', '')
})

// 过滤图标
const filteredIcons = computed(() => {
  if (!searchQuery.value) return allIcons
  const query = searchQuery.value.toLowerCase()
  return allIcons.filter(icon => icon.toLowerCase().includes(query))
})

// 复制图标名称
function handleCopy(iconName) {
  navigator.clipboard.writeText(iconName).then(() => {
    ElMessage.success(`已复制: ${iconName}`)
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

// 复制组件代码
function handleCopyComponent(iconName) {
  const code = `<svg-icon icon-class="${iconName}" />`
  navigator.clipboard.writeText(code).then(() => {
    ElMessage.success('已复制组件代码')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

// 处理文件变化
function handleFileChange(file, fileList) {
  uploadFiles.value = fileList
}

// 上传图标
async function handleUpload() {
  if (uploadFiles.value.length === 0) {
    ElMessage.warning('请选择要上传的图标')
    return
  }
  
  uploading.value = true
  let successCount = 0
  
  for (const file of uploadFiles.value) {
    try {
      const formData = new FormData()
      formData.append('file', file.raw)
      const res = await uploadIcon(formData)
      if (res.code === 200) {
        successCount++
      } else {
        ElMessage.error(res.msg || '上传失败')
      }
    } catch (e) {
      ElMessage.error('上传失败')
    }
  }
  
  uploading.value = false
  
  if (successCount > 0) {
    ElMessage.success(`成功上传 ${successCount} 个图标，即将刷新页面`)
    showUploadDialog.value = false
    uploadRef.value?.clearFiles()
    uploadFiles.value = []
    setTimeout(() => window.location.reload(), 1000)
  }
}
</script>

<style lang="scss" scoped>
.icon-manager {
  padding: 20px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 16px 20px;
  background: var(--el-bg-color);
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);

  .search-input {
    width: 320px;
  }

  .header-right {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  .icon-stats {
    color: var(--el-text-color-secondary);
    font-size: 14px;

    .count {
      color: var(--el-color-primary);
      font-weight: 600;
      font-size: 18px;
      margin: 0 4px;
    }
  }
}

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

.icon-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 12px 12px;
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    border-color: var(--el-color-primary);
    box-shadow: 0 4px 16px rgba(var(--el-color-primary-rgb), 0.15);
    transform: translateY(-2px);

    .icon-wrapper {
      background: var(--el-color-primary-light-9);
    }

    .icon-preview {
      color: var(--el-color-primary);
      transform: scale(1.1);
    }

    .icon-actions {
      opacity: 1;
    }
  }
}

.icon-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  border-radius: 8px;
  background: var(--el-fill-color-lighter);
  transition: all 0.3s;
}

.icon-preview {
  font-size: 28px;
  color: var(--el-text-color-primary);
  transition: all 0.3s;
}

.icon-name {
  margin-top: 12px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  text-align: center;
  word-break: break-all;
  line-height: 1.4;
  max-width: 100%;
}

.icon-actions {
  display: flex;
  gap: 8px;
  margin-top: 8px;
  opacity: 0;
  transition: opacity 0.3s;
}
</style>
