import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ProjectService } from '../../../services/project.service';

// 临时定义MaterialItem接口，因为它在project.model.ts中不存在
interface MaterialItem {
  id: string;
  name: string;
  type: string;
  style: string;
  price: number;
  thumbnailUrl: string;
  downloadCount: number;
  tags: string[];
  costSaved: number;
  isNew: boolean;
  uploadTime: Date;
}

@Component({
  selector: 'app-material-share',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './material-share.html',
  styleUrl: './material-share.scss'
})
export class MaterialShare implements OnInit {
  materials: MaterialItem[] = [];
  searchQuery: string = '';
  filterType: string = '';
  filterStyle: string = '';
  filterPrice: string = '';
  showAdvancedSearch: boolean = false;
  isLoading: boolean = false;
  selectedImageUrl: string | null = null;
  currentPage: number = 1;
  itemsPerPage: number = 12;
  totalMaterials: number = 0;
  totalPages: number = 0;
  visiblePages: number[] = [];
  monthlyAdded: number = 0;
  totalCostSaved: number = 0;
  personalDownloads: number = 0;
  favoriteMaterials: Set<string> = new Set();

  constructor(private projectService: ProjectService) {}

  ngOnInit(): void {
    this.loadMaterials();
    this.loadFavoriteMaterials();
    this.loadMaterialStatistics();
  }

  loadMaterials(): void {
    this.isLoading = true;
    
    // 模拟API加载素材列表
    setTimeout(() => {
      this.projectService.getMaterials(
        this.searchQuery, 
        this.filterType, 
        this.filterStyle, 
        this.filterPrice,
        this.currentPage,
        this.itemsPerPage
      ).subscribe(data => {
        this.materials = data.materials;
        this.totalMaterials = data.total;
        this.totalPages = Math.ceil(this.totalMaterials / this.itemsPerPage);
        this.updateVisiblePages();
        this.isLoading = false;
      });
    }, 800);
  }

  searchMaterials(): void {
    this.currentPage = 1;
    this.loadMaterials();
  }

  resetFilters(): void {
    this.searchQuery = '';
    this.filterType = '';
    this.filterStyle = '';
    this.filterPrice = '';
    this.selectedImageUrl = null;
    this.currentPage = 1;
    this.loadMaterials();
  }

  toggleAdvancedSearch(): void {
    this.showAdvancedSearch = !this.showAdvancedSearch;
  }

  searchByImage(event: Event): void {
    const input = event.target as HTMLInputElement;
    if (input.files && input.files[0]) {
      const file = input.files[0];
      const reader = new FileReader();
      
      reader.onload = (e: ProgressEvent<FileReader>) => {
        if (e.target?.result) {
          this.selectedImageUrl = e.target.result as string;
          // 模拟以图搜图功能
          this.simulateImageSearch();
        }
      };
      
      reader.readAsDataURL(file);
    }
  }

  simulateImageSearch(): void {
    this.isLoading = true;
    // 模拟以图搜图的延迟
    setTimeout(() => {
      // 在实际应用中，这里应该调用真正的以图搜图API
      // 这里只是简单地筛选与图片风格可能相关的素材
      if (this.filterStyle === '') {
        this.filterStyle = '现代'; // 假设上传的图片是现代风格
      }
      this.loadMaterials();
    }, 1500);
  }

  clearSelectedImage(): void {
    this.selectedImageUrl = null;
    // 重新加载所有素材
    this.loadMaterials();
  }

  uploadMaterial(event: Event): void {
    const input = event.target as HTMLInputElement;
    if (input.files && input.files[0]) {
      const file = input.files[0];
      // 模拟上传过程
      this.isLoading = true;
      setTimeout(() => {
        // 实际应用中应调用上传API
        console.log('上传素材:', file.name);
        alert('素材上传成功！等待审核后即可在共享盘中看到');
        this.isLoading = false;
        // 重置输入，允许重新选择同一文件
        input.value = '';
      }, 1000);
    }
  }

  downloadMaterial(materialId: string): void {
    // 模拟下载过程
    this.isLoading = true;
    setTimeout(() => {
      // 实际应用中应调用下载API
      this.projectService.recordMaterialDownload(materialId).subscribe(() => {
        console.log('下载素材:', materialId);
        alert('素材下载成功！');
        this.isLoading = false;
        // 刷新统计数据
        this.loadMaterialStatistics();
      });
    }, 800);
  }

  viewMaterialDetail(materialId: string): void {
    // 在实际应用中，这里应该导航到素材详情页
    console.log('查看素材详情:', materialId);
    alert('素材ID: ' + materialId);
  }

  addToFavorites(materialId: string): void {
    if (this.isFavorited(materialId)) {
      this.favoriteMaterials.delete(materialId);
    } else {
      this.favoriteMaterials.add(materialId);
    }
    // 实际应用中应调用API保存收藏状态
    this.projectService.updateFavoriteMaterial(materialId, this.isFavorited(materialId)).subscribe();
  }

  isFavorited(materialId: string): boolean {
    return this.favoriteMaterials.has(materialId);
  }

  loadFavoriteMaterials(): void {
    // 实际应用中应从服务获取收藏列表
    this.projectService.getFavoriteMaterials().subscribe(favorites => {
      favorites.forEach(id => this.favoriteMaterials.add(id));
    });
  }

  loadMaterialStatistics(): void {
    // 模拟加载统计数据
    this.projectService.getMaterialStatistics().subscribe(stats => {
      this.monthlyAdded = stats.monthlyAdded;
      this.totalCostSaved = stats.totalCostSaved;
      this.personalDownloads = stats.personalDownloads;
    });
  }

  // 分页相关方法
  goToPage(page: number): void {
    if (page >= 1 && page <= this.totalPages) {
      this.currentPage = page;
      this.loadMaterials();
    }
  }

  updateVisiblePages(): void {
    // 计算当前可见的页码
    const maxVisiblePages = 5;
    let startPage = Math.max(1, this.currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(this.totalPages, startPage + maxVisiblePages - 1);
    
    if (endPage - startPage + 1 < maxVisiblePages) {
      startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }
    
    this.visiblePages = [];
    for (let i = startPage; i <= endPage; i++) {
      this.visiblePages.push(i);
    }
  }

  // 辅助方法
  formatDate(date: Date): string {
    return new Date(date).toLocaleDateString('zh-CN');
  }
}