import { Component, Input, signal, computed } from '@angular/core';
import { CommonModule } from '@angular/common';
import { PanoramicSynthesis, PanoramicSpace, SpaceImage } from '../../../models/project.model';

export interface SynthesisTask {
  id: string;
  projectId: string;
  spaceId: string;
  spaceName: string;
  spaceType: string;
  status: 'pending' | 'processing' | 'completed' | 'failed';
  progress: number;
  startTime?: Date;
  completionTime?: Date;
  outputUrl?: string;
  errorMessage?: string;
  quality?: 'standard' | 'high' | 'ultra';
  renderTime?: number; // 渲染时间（分钟）
  fileSize?: number; // 文件大小（字节）
}

export interface SynthesisStats {
  totalTasks: number;
  completedTasks: number;
  processingTasks: number;
  failedTasks: number;
  averageRenderTime: number;
  totalFileSize: number;
}

@Component({
  selector: 'app-panoramic-synthesis-card',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './panoramic-synthesis-card.html',
  styleUrls: ['./panoramic-synthesis-card.scss']
})
export class PanoramicSynthesisCardComponent {
  @Input() synthesis!: PanoramicSynthesis;
  @Input() showActions: boolean = true;
  @Input() synthesisTasks: SynthesisTask[] = [];
  
  // 状态管理
  isProcessing = signal<boolean>(false);
  selectedQuality = signal<'standard' | 'high' | 'ultra'>('high');
  batchMode = signal<boolean>(false);
  selectedSpaces = signal<string[]>([]);
  
  // 计算统计数据
  stats = computed<SynthesisStats>(() => {
    const tasks = this.synthesisTasks || [];
    const completedTasks = tasks.filter(t => t.status === 'completed');
    const processingTasks = tasks.filter(t => t.status === 'processing');
    const failedTasks = tasks.filter(t => t.status === 'failed');
    
    const renderTimes = completedTasks
      .filter(t => t.startTime && t.completionTime)
      .map(t => (t.completionTime!.getTime() - t.startTime!.getTime()) / 1000);
    
    const averageRenderTime = renderTimes.length > 0 
      ? renderTimes.reduce((sum, time) => sum + time, 0) / renderTimes.length 
      : 0;
    
    return {
      totalTasks: tasks.length,
      completedTasks: completedTasks.length,
      processingTasks: processingTasks.length,
      failedTasks: failedTasks.length,
      averageRenderTime,
      totalFileSize: 0 // 这里可以根据实际需要计算
    };
  });

  getStatusLabel(status: string): string {
    const statusMap: { [key: string]: string } = {
      'draft': '草稿',
      'processing': '处理中',
      'completed': '已完成',
      'published': '已发布'
    };
    return statusMap[status] || status;
  }

  getSpaceTypeLabel(type: string): string {
    const typeMap: { [key: string]: string } = {
      'living_room': '客厅',
      'bedroom': '卧室',
      'kitchen': '厨房',
      'bathroom': '卫生间',
      'dining_room': '餐厅',
      'study': '书房',
      'balcony': '阳台'
    };
    return typeMap[type] || type;
  }

  getQualityLabel(quality: string): string {
    const qualityMap: { [key: string]: string } = {
      'standard': '标准',
      'high': '高清',
      'ultra': '超清'
    };
    return qualityMap[quality] || quality;
  }

  getProgressPercentage(space: PanoramicSpace): number {
    return space.progress || 0;
  }

  getProgressColor(progress: number): string {
    if (progress >= 100) return '#52c41a';
    if (progress >= 70) return '#1890ff';
    if (progress >= 30) return '#faad14';
    return '#f5222d';
  }

  onPreview(synthesis: PanoramicSynthesis): void {
    if (synthesis.previewUrl) {
      window.open(synthesis.previewUrl, '_blank');
    } else {
      console.warn('预览链接不可用');
    }
  }

  onDownload(synthesis: PanoramicSynthesis): void {
    if (synthesis.downloadUrl) {
      window.open(synthesis.downloadUrl, '_blank');
    } else {
      console.warn('下载链接不可用');
    }
  }

  onEdit(synthesis: PanoramicSynthesis): void {
    console.log('编辑全景合成:', synthesis);
    // 实际实现中会导航到编辑页面
  }

  onDelete(synthesis: PanoramicSynthesis): void {
    if (confirm('确定要删除这个全景合成吗？')) {
      console.log('删除全景合成:', synthesis);
      // 实际实现中会调用删除API
    }
  }

  formatFileSize(bytes: number | undefined): string {
    if (!bytes) return '未知';
    
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
  }

  // 开始合成任务
  startSynthesis(spaceIds: string[] = []): void {
    if (this.isProcessing()) return;
    
    this.isProcessing.set(true);
    const spacesToProcess = spaceIds.length > 0 ? spaceIds : this.selectedSpaces();
    
    console.log('开始全景图合成:', {
      spaces: spacesToProcess,
      quality: this.selectedQuality(),
      batchMode: this.batchMode()
    });
    
    // 模拟合成过程
    setTimeout(() => {
      this.isProcessing.set(false);
      console.log('全景图合成完成');
    }, 3000);
  }

  // 批量合成
  startBatchSynthesis(): void {
    if (this.synthesis?.spaces) {
      const allSpaceIds = this.synthesis.spaces.map(space => space.id);
      this.startSynthesis(allSpaceIds);
    }
  }

  // 切换空间选择
  toggleSpaceSelection(spaceId: string): void {
    const current = this.selectedSpaces();
    if (current.includes(spaceId)) {
      this.selectedSpaces.set(current.filter(id => id !== spaceId));
    } else {
      this.selectedSpaces.set([...current, spaceId]);
    }
  }

  // 设置合成质量
  setQuality(quality: 'standard' | 'high' | 'ultra'): void {
    this.selectedQuality.set(quality);
  }

  // 切换批量模式
  toggleBatchMode(): void {
    this.batchMode.set(!this.batchMode());
    if (this.batchMode()) {
      // 批量模式下选择所有空间
      if (this.synthesis?.spaces) {
        this.selectedSpaces.set(this.synthesis.spaces.map(space => space.id));
      }
    } else {
      this.selectedSpaces.set([]);
    }
  }

  // 预览合成结果
  previewSynthesis(spaceId: string): void {
    const task = this.synthesisTasks.find(t => t.spaceId === spaceId);
    if (task?.outputUrl) {
      window.open(task.outputUrl, '_blank');
    } else {
      console.warn('预览不可用');
    }
  }

  // 下载合成结果
  downloadSynthesis(spaceId: string): void {
    const task = this.synthesisTasks.find(t => t.spaceId === spaceId);
    if (task?.outputUrl) {
      const link = document.createElement('a');
      link.href = task.outputUrl;
      link.download = `panoramic_${task.spaceName}.jpg`;
      link.click();
    } else {
      console.warn('下载不可用');
    }
  }

  // 重试失败的任务
  retryFailedTask(taskId: string): void {
    console.log('重试合成任务:', taskId);
    // 这里可以实现重试逻辑
  }

  // 取消处理中的任务
  cancelTask(taskId: string): void {
    console.log('取消合成任务:', taskId);
    // 这里可以实现取消逻辑
  }
}