import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { UploadComponent, UploadResult } from '../upload-component/upload.component';
import { NovaFile } from 'fmode-ng/core';

@Component({
  selector: 'app-upload-example',
  standalone: true,
  imports: [CommonModule, UploadComponent],
  templateUrl: './upload-example.component.html',
  styleUrls: ['./upload-example.component.scss']
})
export class UploadExampleComponent {
  uploadResults: UploadResult[] = [];
  isUploading: boolean = false;

  // 计算属性
  get successfulUploads(): number {
    return this.uploadResults.filter(r => r.success).length;
  }

  get failedUploads(): number {
    return this.uploadResults.filter(r => !r.success).length;
  }

  // 示例配置
  exampleConfigs = [
    {
      title: '基础图片上传',
      accept: 'image/*',
      multiple: false,
      maxSize: 5,
      showPreview: true,
      prefixKey: 'demo/images/'
    },
    {
      title: '文档批量上传',
      accept: '.pdf,.doc,.docx,.xls,.xlsx',
      multiple: true,
      maxSize: 10,
      showPreview: false,
      prefixKey: 'demo/documents/'
    },
    {
      title: '项目文件上传',
      accept: '*/*',
      multiple: true,
      maxSize: 20,
      showPreview: true,
      prefixKey: 'demo/projects/'
    }
  ];

  selectedConfig = this.exampleConfigs[0];

  onFileSelected(files: File[]): void {
    console.log('文件选择:', files);
  }

  onUploadStart(files: File[]): void {
    this.isUploading = true;
    console.log('开始上传:', files);
  }

  onUploadProgress(progress: { completed: number; total: number; currentFile: string }): void {
    console.log('上传进度:', progress);
  }

  onUploadComplete(results: UploadResult[]): void {
    this.isUploading = false;
    this.uploadResults = results;

    console.log('上传完成:', results);

    // 处理上传结果
    const successCount = results.filter(r => r.success).length;
    const failCount = results.filter(r => !r.success).length;

    console.log(`✅ 成功: ${successCount}, ❌ 失败: ${failCount}`);

    // 保存成功的文件信息
    results.forEach(result => {
      if (result.success && result.file) {
        this.saveFileInfo(result.file as NovaFile);
      }
    });
  }

  onUploadError(error: string): void {
    this.isUploading = false;
    console.error('上传错误:', error);
    alert(`上传失败: ${error}`);
  }

  /**
   * 保存文件信息到数据库（示例）
   */
  private async saveFileInfo(file: NovaFile): Promise<void> {
    try {
      // 这里可以将文件信息保存到数据库
      console.log('保存文件信息:', {
        key: file.key,
        url: file.url,
        name: file.name,
        type: file.type,
        size: file.size,
        metadata: file.metadata,
        md5: file.md5
      });

      // 示例：保存到 Attachment 表
      // const attachment = new FmodeObject('Attachment');
      // attachment.set('key', file.key);
      // attachment.set('url', file.url);
      // attachment.set('name', file.name);
      // attachment.set('type', file.type);
      // attachment.set('size', file.size);
      // attachment.set('md5', file.md5);
      // await attachment.save();

    } catch (error) {
      console.error('保存文件信息失败:', error);
    }
  }

  /**
   * 选择不同的配置
   */
  selectConfig(config: any): void {
    this.selectedConfig = config;
    this.uploadResults = [];
  }

  /**
   * 清空结果
   */
  clearResults(): void {
    this.uploadResults = [];
  }

  /**
   * 格式化文件大小
   */
  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];
  }

  /**
   * 获取文件状态样式
   */
  getStatusClass(result: UploadResult): string {
    return result.success ? 'success' : 'error';
  }

  /**
   * 复制URL到剪贴板
   */
  async copyUrl(url: string): Promise<void> {
    try {
      await navigator.clipboard.writeText(url);
      alert('URL已复制到剪贴板');
    } catch (error) {
      console.error('复制失败:', error);
      // 降级方案
      const textArea = document.createElement('textarea');
      textArea.value = url;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand('copy');
      document.body.removeChild(textArea);
      alert('URL已复制到剪贴板');
    }
  }
}