<template>
  <div class="model-3d-container">
    <!-- 顶部操作栏 -->
    <div class="header-toolbar">
      <a-space>
        <a-button 
          type="primary" 
          @click="handleUploadModel"
          :loading="uploading"
        >
          <template #icon><icon-plus /></template>
          上传模型
        </a-button>
        
        <a-button @click="refreshModels">
          <template #icon><icon-refresh /></template>
          刷新
        </a-button>
        
        <a-button @click="exportModels">
          <template #icon><icon-download /></template>
          导出模型
        </a-button>
      </a-space>
    </div>

    <!-- 模型卡片展示区域 -->
    <div class="models-grid">
      <div 
        v-for="model in models" 
        :key="model.id"
        class="model-card"
      >
        <div class="model-preview">
          <div class="model-thumbnail">
            <img 
              v-if="model.thumbnail" 
              :src="model.thumbnail" 
              :alt="model.name"
              @error="handleImageError"
            />
            <div v-else class="no-image">
              <icon-image />
              <span>暂无预览图</span>
            </div>
          </div>
          
          <div class="model-type-tag">
            <a-tag :color="getModelTypeColor(model.type)">
              {{ model.type }}
            </a-tag>
          </div>
        </div>
        
        <div class="model-info">
          <h3 class="model-name">{{ model.name }}</h3>
          <p class="model-description">{{ model.description }}</p>
          
          <div class="model-meta">
            <div class="meta-item">
              <span class="meta-label">文件大小:</span>
              <span class="meta-value">{{ model.fileSize }}</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">创建时间:</span>
              <span class="meta-value">{{ model.createTime }}</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">创建者:</span>
              <span class="meta-value">{{ model.creator }}</span>
            </div>
          </div>
        </div>
        
        <div class="model-actions">
          <a-space>
            <a-button size="small" @click="viewModel(model)">
              查看
            </a-button>
            <a-button size="small" @click="editModel(model)">
              编辑
            </a-button>
            <a-button size="small" status="danger" @click="deleteModel(model)">
              删除
            </a-button>
          </a-space>
        </div>
      </div>
    </div>

    <!-- 上传模型模态框 -->
    <a-modal
      v-model:visible="uploadModalVisible"
      title="上传三维模型"
      width="600px"
      @ok="handleUploadOk"
      @cancel="handleUploadCancel"
    >
      <a-form ref="uploadFormRef" :model="uploadForm" layout="vertical">
        <a-form-item label="模型名称" field="name" required>
          <a-input v-model="uploadForm.name" placeholder="请输入模型名称" />
        </a-form-item>
        
        <a-form-item label="模型类型" field="type" required>
          <a-select v-model="uploadForm.type" placeholder="请选择模型类型">
            <a-option value="叶片">叶片</a-option>
            <a-option value="机组">机组</a-option>
            <a-option value="地形">地形</a-option>
            <a-option value="塔筒">塔筒</a-option>
            <a-option value="其他">其他</a-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="模型描述" field="description">
          <a-textarea v-model="uploadForm.description" placeholder="请输入模型描述" />
        </a-form-item>
        
        <a-form-item label="模型文件" field="file" required>
          <a-upload
            :file-list="fileList"
            :limit="1"
            :auto-upload="false"
            accept=".obj,.fbx,.3ds,.dae,.ply,.stl"
            @change="handleFileChange"
          >
            <template #upload-button>
              <div class="upload-area">
                <icon-cloud-upload />
                <div class="upload-text">
                  <p>点击或拖拽文件到此处上传</p>
                  <p class="upload-hint">支持 .obj .fbx .3ds .dae .ply .stl 格式</p>
                </div>
              </div>
            </template>
          </a-upload>
        </a-form-item>
        
        <a-form-item label="预览图" field="thumbnail">
          <a-upload
            :file-list="thumbnailList"
            :limit="1"
            :auto-upload="false"
            accept=".jpg,.jpeg,.png,.gif"
            @change="handleThumbnailChange"
          >
            <template #upload-button>
              <a-button>
                <template #icon><icon-image /></template>
                上传预览图
              </a-button>
            </template>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 模型详情模态框 -->
    <a-modal
      v-model:visible="detailModalVisible"
      :title="selectedModel?.name"
      width="800px"
      :footer="false"
    >
      <div v-if="selectedModel" class="model-detail">
        <div class="detail-preview">
          <img 
            v-if="selectedModel.thumbnail" 
            :src="selectedModel.thumbnail" 
            :alt="selectedModel.name"
            class="detail-image"
          />
          <div v-else class="no-preview">
            <icon-image />
            <span>暂无预览图</span>
          </div>
        </div>
        
        <div class="detail-info">
          <a-descriptions :data="modelDetailData" title="模型信息" :column="2" />
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'

defineOptions({ name: 'Model3D' })

// 接口定义
interface Model3D {
  id: string
  name: string
  type: string
  description: string
  fileSize: string
  createTime: string
  creator: string
  thumbnail?: string
  filePath: string
}

// 响应式数据
const uploading = ref(false)
const uploadModalVisible = ref(false)
const detailModalVisible = ref(false)
const selectedModel = ref<Model3D | null>(null)
const uploadFormRef = ref()
const fileList = ref<any[]>([])
const thumbnailList = ref<any[]>([])

// 表单数据
const uploadForm = reactive({
  name: '',
  type: '',
  description: '',
  file: null,
  thumbnail: null
})

// 模型数据
const models = ref<Model3D[]>([
  {
    id: '1',
    name: 'A型叶片模型',
    type: '叶片',
    description: '用于风力发电机A型叶片的三维模型，包含详细的结构和材质信息',
    fileSize: '15.2MB',
    createTime: '2023-10-15',
    creator: '张工程师',
    thumbnail: '/model-thumbnails/blade-a.jpg',
    filePath: '/models/blade-a.obj'
  },
  {
    id: '2',
    name: '2.5MW机组模型',
    type: '机组',
    description: '2.5MW风力发电机组的完整三维模型，包含所有主要组件',
    fileSize: '42.8MB',
    createTime: '2023-10-12',
    creator: '李工程师',
    thumbnail: '/model-thumbnails/turbine-2.5mw.jpg',
    filePath: '/models/turbine-2.5mw.fbx'
  },
  {
    id: '3',
    name: 'B风场地形模型',
    type: '地形',
    description: 'B风场的地形三维模型，用于风场规划和分析',
    fileSize: '28.7MB',
    createTime: '2023-10-10',
    creator: '王工程师',
    thumbnail: '/model-thumbnails/terrain-b.jpg',
    filePath: '/models/terrain-b.dae'
  }
])

// 计算属性
const modelDetailData = computed(() => {
  if (!selectedModel.value) return []
  
  return [
    { label: '模型名称', value: selectedModel.value.name },
    { label: '模型类型', value: selectedModel.value.type },
    { label: '文件大小', value: selectedModel.value.fileSize },
    { label: '创建时间', value: selectedModel.value.createTime },
    { label: '创建者', value: selectedModel.value.creator },
    { label: '文件路径', value: selectedModel.value.filePath },
    { label: '模型描述', value: selectedModel.value.description }
  ]
})

// 方法
const getModelTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    '叶片': 'blue',
    '机组': 'green',
    '地形': 'orange',
    '塔筒': 'purple',
    '其他': 'gray'
  }
  return colorMap[type] || 'gray'
}

const handleUploadModel = () => {
  resetUploadForm()
  uploadModalVisible.value = true
}

const handleUploadOk = async () => {
  try {
    uploading.value = true
    
    // 模拟上传过程
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 创建新模型
    const newModel: Model3D = {
      id: Date.now().toString(),
      name: uploadForm.name,
      type: uploadForm.type,
      description: uploadForm.description,
      fileSize: '0MB', // 实际应该从文件获取
      createTime: new Date().toLocaleDateString(),
      creator: '当前用户',
      thumbnail: thumbnailList.value[0]?.url || undefined,
      filePath: `/models/${uploadForm.name.toLowerCase().replace(/\s+/g, '-')}.obj`
    }
    
    models.value.push(newModel)
    uploadModalVisible.value = false
    Message.success('模型上传成功')
  } catch (error) {
    Message.error('模型上传失败')
  } finally {
    uploading.value = false
  }
}

const handleUploadCancel = () => {
  uploadModalVisible.value = false
  resetUploadForm()
}

const resetUploadForm = () => {
  Object.assign(uploadForm, {
    name: '',
    type: '',
    description: '',
    file: null,
    thumbnail: null
  })
  fileList.value = []
  thumbnailList.value = []
}

const handleFileChange = (files: any) => {
  fileList.value = files
  uploadForm.file = files[0]?.file || null
}

const handleThumbnailChange = (files: any) => {
  thumbnailList.value = files
  uploadForm.thumbnail = files[0]?.file || null
}

const viewModel = (model: Model3D) => {
  selectedModel.value = model
  detailModalVisible.value = true
}

const editModel = (model: Model3D) => {
  // 编辑模型逻辑
  Object.assign(uploadForm, {
    name: model.name,
    type: model.type,
    description: model.description
  })
  uploadModalVisible.value = true
  Message.info('编辑模型功能')
}

const deleteModel = (model: Model3D) => {
  const index = models.value.findIndex(m => m.id === model.id)
  if (index > -1) {
    models.value.splice(index, 1)
    Message.success('模型删除成功')
  }
}

const refreshModels = () => {
  Message.success('模型列表已刷新')
}

const exportModels = () => {
  Message.success('模型导出成功')
}

const handleImageError = (e: Event) => {
  const target = e.target as HTMLImageElement
  target.style.display = 'none'
  target.parentElement?.classList.add('error')
}
</script>

<style scoped lang="scss">
.model-3d-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
  
  .header-toolbar {
    margin-bottom: 20px;
    padding: 16px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  .models-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(360px, 1fr));
    gap: 20px;
    
    .model-card {
      background: white;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      transition: transform 0.2s, box-shadow 0.2s;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
      }
      
      .model-preview {
        position: relative;
        height: 200px;
        background: #f8f9fa;
        
        .model-thumbnail {
          width: 100%;
          height: 100%;
          
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
          
          .no-image {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            color: #9ca3af;
            
            .arco-icon {
              font-size: 48px;
              margin-bottom: 8px;
            }
          }
        }
        
        .model-type-tag {
          position: absolute;
          top: 12px;
          right: 12px;
        }
      }
      
      .model-info {
        padding: 16px;
        
        .model-name {
          font-size: 16px;
          font-weight: 600;
          margin: 0 0 8px 0;
          color: #1f2937;
        }
        
        .model-description {
          color: #6b7280;
          font-size: 14px;
          margin: 0 0 12px 0;
          line-height: 1.4;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
        
        .model-meta {
          .meta-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 4px;
            font-size: 12px;
            
            .meta-label {
              color: #6b7280;
            }
            
            .meta-value {
              color: #1f2937;
            }
          }
        }
      }
      
      .model-actions {
        padding: 16px;
        border-top: 1px solid #e5e7eb;
        display: flex;
        justify-content: center;
      }
    }
  }
  
  .upload-area {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 40px;
    border: 2px dashed #d1d5db;
    border-radius: 8px;
    text-align: center;
    
    .arco-icon {
      font-size: 48px;
      color: #9ca3af;
      margin-bottom: 16px;
    }
    
    .upload-text {
      p {
        margin: 4px 0;
        
        &.upload-hint {
          font-size: 12px;
          color: #9ca3af;
        }
      }
    }
  }
  
  .model-detail {
    .detail-preview {
      margin-bottom: 24px;
      text-align: center;
      
      .detail-image {
        max-width: 100%;
        max-height: 300px;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
      
      .no-preview {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 200px;
        color: #9ca3af;
        border: 2px dashed #d1d5db;
        border-radius: 8px;
        
        .arco-icon {
          font-size: 48px;
          margin-bottom: 8px;
        }
      }
    }
  }
}

:deep(.arco-upload-list-item) {
  margin-top: 8px;
}

:deep(.arco-descriptions-item-label) {
  font-weight: 600;
}
</style> 