import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { FmodeObject, FmodeQuery, FmodeParse } from 'fmode-ng/parse';
import { NovaStorage, NovaFile } from 'fmode-ng/core';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { ColorGetDialogComponent } from '../color-get/color-get-dialog.component';

const Parse = FmodeParse.with('nova');

export interface ProjectFile {
  id: string;
  name: string;
  originalName: string;
  url: string;
  key: string;
  type: string;
  size: number;
  uploadedBy: {
    id: string;
    name: string;
    avatar?: string;
  };
  uploadedAt: Date;
  source: string;
  md5?: string;
  metadata?: any;
  description?: string;
}

@Component({
  selector: 'app-project-files-modal',
  standalone: true,
  imports: [CommonModule, FormsModule, MatDialogModule],
  templateUrl: './project-files-modal.component.html',
  styleUrls: ['./project-files-modal.component.scss']
})
export class ProjectFilesModalComponent implements OnInit {
  @Input() project: FmodeObject | null = null;
  @Input() currentUser: FmodeObject | null = null;
  @Input() isVisible: boolean = false;
  @Output() close = new EventEmitter<void>();

  files: ProjectFile[] = [];
  loading: boolean = false;
  selectedFile: ProjectFile | null = null;
  previewMode: 'grid' | 'list' = 'grid';
  searchQuery: string = '';
  filterType: string = 'all';

  // 统计信息
  totalFiles: number = 0;
  totalSize: number = 0;
  imageCount: number = 0;
  documentCount: number = 0;

  constructor(private dialog: MatDialog) {}

  ngOnInit(): void {
    if (this.isVisible && this.project) {
      this.loadFiles();
    }
  }

  ngOnChanges(): void {
    if (this.isVisible && this.project) {
      this.loadFiles();
    }
  }

  async loadFiles(): Promise<void> {
    if (!this.project) return;

    try {
      this.loading = true;

      const query = new FmodeQuery('ProjectFile');
      query.equalTo('project', this.project.toPointer());
      query.include('uploadedBy','attach');
      query.descending('uploadedAt');
      query.limit(100);

      const results = await query.find();

      this.files = results.map((file: FmodeObject) => {
        let attach = file?.get("attach")
        return {
        id: file.id || '',
        name: attach.get('name') || attach.get('originalName') || '',
        originalName: attach.get('originalName') || '',
        url: attach.get('url') || '',
        key: file.get('key') || '',
        type: attach.get('mime') || '',
        mime: attach.get('mime') || '',
        size: attach.get('size') || 0,
        uploadedBy: file.get('uploadedBy')?.toJSON(),
        uploadedAt: file.get('uploadedAt') || file.createdAt,
        source: attach.get('source') || 'unknown',
        md5: attach.get('md5'),
        metadata: attach.get('metadata'),
        description: attach.get('description') || ''
      }
      
    });

      this.calculateStats();
      console.log(`✅ 加载了 ${this.files.length} 个项目文件`);
    } catch (error) {
      console.error('❌ 加载项目文件失败:', error);
    } finally {
      this.loading = false;
    }
  }

  calculateStats(): void {
    this.totalFiles = this.files.length;
    this.totalSize = this.files.reduce((sum, file) => sum + (file.size || 0), 0);
    this.imageCount = this.files.filter(file => file.type.startsWith('image/')).length;
    this.documentCount = this.files.filter(file => !file.type.startsWith('image/')).length;
  }

  onClose(): void {
    this.close.emit();
  }

  onBackdropClick(event: MouseEvent): void {
    if (event.target === event.currentTarget) {
      this.onClose();
    }
  }

  selectFile(file: ProjectFile): void {
    this.selectedFile = file;
  }

  closePreview(): void {
    this.selectedFile = null;
  }

  downloadFile(file: ProjectFile): void {
    const link = document.createElement('a');
    link.href = file.url;
    link.download = file.originalName;
    link.target = '_blank';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  openColorAnalysis(file: ProjectFile): void {
    if (!this.isImageFile(file)) return;
    this.dialog.open(ColorGetDialogComponent, {
      data: {
        file: {
          id: file.id,
          name: file.name,
          originalName: file.originalName,
          url: file.url,
          type: file.type,
          size: file.size
        }
      },
      width: '90vw',
      maxWidth: '1200px'
    });
  }

  formatFileSize(bytes: number): string {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }

  getFileIcon(type: string): string {
    if (type.startsWith('image/')) return '🖼️';
    if (type.startsWith('video/')) return '🎬';
    if (type.startsWith('audio/')) return '🎵';
    if (type.includes('pdf')) return '📄';
    if (type.includes('word') || type.includes('document')) return '📝';
    if (type.includes('excel') || type.includes('spreadsheet')) return '📊';
    if (type.includes('powerpoint') || type.includes('presentation')) return '📑';
    if (type.includes('zip') || type.includes('rar') || type.includes('7z')) return '📦';
    if (type.includes('text') || type.includes('plain')) return '📄';
    return '📎';
  }

  getFileExtension(name: string): string {
    return name.split('.')?.pop()?.toUpperCase() || '';
  }

  isImageFile(file: ProjectFile): boolean {
    return file.type.startsWith('image/');
  }

  isVideoFile(file: ProjectFile): boolean {
    return file.type.startsWith('video/');
  }

  getFilteredFiles(): ProjectFile[] {
    let filtered = this.files;

    // 搜索过滤
    if (this.searchQuery) {
      const query = this.searchQuery.toLowerCase();
      filtered = filtered.filter(file =>
        file.name.toLowerCase().includes(query) ||
        file.originalName.toLowerCase().includes(query) ||
        file.uploadedBy.name.toLowerCase().includes(query)
      );
    }

    // 类型过滤
    if (this.filterType !== 'all') {
      switch (this.filterType) {
        case 'images':
          filtered = filtered.filter(file => this.isImageFile(file));
          break;
        case 'documents':
          filtered = filtered.filter(file => !this.isImageFile(file));
          break;
        case 'videos':
          filtered = filtered.filter(file => this.isVideoFile(file));
          break;
      }
    }

    return filtered;
  }

  async updateFileDescription(file: ProjectFile, description: string): Promise<void> {
    try {
      const query = new FmodeQuery('ProjectFile');
      const fileObject = await query.get(file.id);

      if (fileObject) {
        fileObject.set('description', description);
        await fileObject.save();

        // 更新本地数据
        const localFile = this.files.find(f => f.id === file.id);
        if (localFile) {
          localFile.description = description;
        }

        console.log('✅ 文件说明更新成功');
      }
    } catch (error) {
      console.error('❌ 更新文件说明失败:', error);
    }
  }

  getSourceBadgeClass(source: string): string {
    switch (source) {
      case '企业微信拖拽':
        return 'source-wxwork';
      case '手动选择':
        return 'source-manual';
      default:
        return 'source-default';
    }
  }

  getSourceLabel(source: string): string {
    switch (source) {
      case '企业微信拖拽':
        return '企微拖拽';
      case '手动选择':
        return '手动上传';
      default:
        return '其他';
    }
  }
}