import { Component } from '@angular/core';

interface Photo {
  id: number;
  url: string;
  tags: string[];
}

@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss'],
})
export class Tab1Page {
  photos: Photo[] = [
    { id: 1, url: 'assets/photos/photo1.jpg', tags: ['赛马娘', '东商改革'] },
    { id: 2, url: 'assets/photos/photo2.jpg', tags: ['赛马娘', '东海帝皇', '目白麦昆'] },
    { id: 3, url: 'assets/photos/photo3.jpg', tags: ['赛马娘', '东海帝皇'] },
    { id: 4, url: 'assets/photos/photo4.jpg', tags: ['赛马娘', '目白麦昆'] },
    { id: 5, url: 'assets/photos/photo5.jpg', tags: ['赛马娘', '草上飞'] },
    { id: 6, url: 'assets/photos/photo6.jpg', tags: ['赛马娘', '北部玄驹'] },
    // 添加更多照片
  ];

  displayedPhotos: Photo[] = [];
  newPhotoTags: string = '';

  constructor() {
    this.displayedPhotos = [...this.photos]; // 初始显示所有照片
  }

  onSearch(event: CustomEvent) {
    const searchTerm = (event.target as HTMLInputElement).value.toLowerCase().trim();
    if (searchTerm === '') {
      this.displayedPhotos = [...this.photos]; // 重置显示所有照片
    } else {
      this.displayedPhotos = this.photos.filter(photo =>
        photo.tags.some(tag => tag.toLowerCase().includes(searchTerm))
      );
    }
  }

  openFullscreen(imageUrl: string) {
    window.open(imageUrl, '_blank');
  }

  // 打开文件选择器
  openFilePicker() {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    input.onchange = (event: Event) => this.handleFileSelect(event);
    input.click();
  }

  // 处理文件选择和标签输入
  handleFileSelect(event: Event) {
    const input = event.target as HTMLInputElement;
    if (input.files && input.files.length > 0) {
      const file = input.files[0];
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        const imageUrl = reader.result as string;
        const newTags = this.newPhotoTags.split(',').map(tag => tag.trim());
        const newPhoto: Photo = {
          id: this.photos.length + 1,
          url: imageUrl,
          tags: newTags,
        };
        this.photos.push(newPhoto);
        this.displayedPhotos = [...this.photos]; // 更新显示的照片列表
        this.newPhotoTags = ''; // 清空标签输入框
      };
      reader.onerror = error => {
        console.error('FileReader error:', error);
      };
    }
  }
}
