import { Component, OnInit, signal, computed } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule, FormBuilder, FormGroup } from '@angular/forms';
import { RouterModule } from '@angular/router';

// 定义案例接口
interface CaseItem {
  id: string;
  name: string;
  category: string;
  style: string[];
  houseType: string;
  property: string;
  designer: string;
  area: number;
  createdAt: Date;
  coverImage: string;
  detailImages: string[];
  isFavorite: boolean;
  tags: string[];
  views: number;
  description: string;
}

@Component({
  selector: 'app-case-library',
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule, RouterModule],
  templateUrl: './case-library.html',
  styleUrls: ['./case-library.scss', '../customer-service-styles.scss']
})
export class CaseLibrary implements OnInit {
  // 当前日期
  currentDate = new Date();
  
  // 搜索关键词
  searchTerm = signal('');
  
  // 筛选表单
  filterForm: FormGroup;
  
  // 案例列表
  cases = signal<CaseItem[]>([]);
  
  // 筛选后的案例
  filteredCases = computed(() => {
    let result = [...this.cases()];
    
    // 应用搜索筛选
    if (this.searchTerm()) {
      const searchLower = this.searchTerm().toLowerCase();
      result = result.filter(caseItem => 
        caseItem.name.toLowerCase().includes(searchLower) ||
        caseItem.designer.toLowerCase().includes(searchLower) ||
        caseItem.description.toLowerCase().includes(searchLower) ||
        caseItem.tags.some(tag => tag.toLowerCase().includes(searchLower))
      );
    }
    
    // 应用表单筛选
    const filters = this.filterForm.value;
    
    if (filters.style && filters.style.length > 0) {
      result = result.filter(caseItem => 
        caseItem.style.some(style => filters.style.includes(style))
      );
    }
    
    if (filters.houseType) {
      result = result.filter(caseItem => caseItem.houseType === filters.houseType);
    }
    
    if (filters.property) {
      result = result.filter(caseItem => caseItem.property === filters.property);
    }
    
    if (filters.minArea) {
      result = result.filter(caseItem => caseItem.area >= filters.minArea);
    }
    
    if (filters.maxArea) {
      result = result.filter(caseItem => caseItem.area <= filters.maxArea);
    }
    
    if (filters.favorite) {
      result = result.filter(caseItem => caseItem.isFavorite);
    }
    
    return result;
  });
  
  // 显示筛选面板
  showFilterPanel = signal(false);
  
  // 当前查看的案例详情
  selectedCase = signal<CaseItem | null>(null);
  
  // 分页信息
  currentPage = signal(1);
  itemsPerPage = signal(12);
  
  // 分页后的案例
  paginatedCases = computed(() => {
    const startIndex = (this.currentPage() - 1) * this.itemsPerPage();
    return this.filteredCases().slice(startIndex, startIndex + this.itemsPerPage());
  });
  
  // 总页数
  totalPages = computed(() => {
    return Math.ceil(this.filteredCases().length / this.itemsPerPage());
  });
  
  // 筛选选项
  styleOptions = ['现代简约', '北欧风', '工业风', '新中式', '法式轻奢', '日式', '美式', '混搭'];
  houseTypeOptions = ['一室一厅', '两室一厅', '两室两厅', '三室一厅', '三室两厅', '四室两厅', '复式', '别墅', '其他'];
  propertyOptions = ['万科', '绿城', '保利', '龙湖', '融创', '中海', '碧桂园', '其他'];
  
  constructor(private fb: FormBuilder) {
    // 初始化筛选表单
    this.filterForm = this.fb.group({
      style: [[]],
      houseType: [''],
      property: [''],
      minArea: [''],
      maxArea: [''],
      favorite: [false]
    });
  }
  
  ngOnInit(): void {
    // 加载模拟案例数据
    this.loadCases();
  }
  
  // 加载案例数据
  loadCases(): void {
    // 模拟API请求获取案例数据
    const mockCases: CaseItem[] = Array.from({ length: 24 }, (_, i) => ({
      id: `case-${i + 1}`,
      name: `${this.styleOptions[Math.floor(Math.random() * this.styleOptions.length)]}风格 ${this.houseTypeOptions[Math.floor(Math.random() * this.houseTypeOptions.length)]}设计`,
      category: ['客厅', '卧室', '厨房', '浴室', '书房', '餐厅'][Math.floor(Math.random() * 6)],
      style: [this.styleOptions[Math.floor(Math.random() * this.styleOptions.length)]],
      houseType: this.houseTypeOptions[Math.floor(Math.random() * this.houseTypeOptions.length)],
      property: this.propertyOptions[Math.floor(Math.random() * this.propertyOptions.length)],
      designer: ['张设计', '李设计', '王设计', '赵设计', '陈设计'][Math.floor(Math.random() * 5)],
      area: Math.floor(Math.random() * 100) + 50, // 50-150㎡
      createdAt: new Date(Date.now() - Math.floor(Math.random() * 365) * 24 * 60 * 60 * 1000),
      coverImage: `https://picsum.photos/id/${100 + i}/600/400`,
      detailImages: Array.from({ length: 4 }, (_, j) => `https://picsum.photos/id/${130 + i + j}/800/600`),
      isFavorite: Math.random() > 0.7,
      tags: ['热门', '精选', '新上传', '高性价比', '业主好评'].filter(() => Math.random() > 0.5),
      views: Math.floor(Math.random() * 1000) + 100,
      description: '这是一个精美的' + ['现代简约', '北欧风', '新中式'][Math.floor(Math.random() * 3)] + '风格设计案例，融合了功能性与美学，为客户打造了舒适宜人的居住环境。'
    }));
    
    this.cases.set(mockCases);
  }
  
  // 切换收藏状态
  toggleFavorite(caseId: string): void {
    this.cases.set(
      this.cases().map(caseItem => 
        caseItem.id === caseId 
          ? { ...caseItem, isFavorite: !caseItem.isFavorite }
          : caseItem
      )
    );
  }
  
  // 查看案例详情
  viewCaseDetails(caseItem: CaseItem): void {
    this.selectedCase.set(caseItem);
    // 增加浏览量
    this.cases.set(
      this.cases().map(item => 
        item.id === caseItem.id 
          ? { ...item, views: item.views + 1 }
          : item
      )
    );
  }
  
  // 关闭案例详情
  closeCaseDetails(): void {
    this.selectedCase.set(null);
  }
  
  // 分享案例
  shareCase(caseId: string): void {
    console.log('分享案例:', caseId);
    // 模拟复制到剪贴板
    alert('案例链接已复制到剪贴板！');
  }
  
  // 重置筛选条件
  resetFilters(): void {
    this.filterForm.reset({
      style: [],
      houseType: '',
      property: '',
      minArea: '',
      maxArea: '',
      favorite: false
    });
    this.searchTerm.set('');
    this.currentPage.set(1);
  }
  
  // 切换筛选面板
  toggleFilterPanel(): void {
    this.showFilterPanel.set(!this.showFilterPanel());
  }
  
  // 分页导航
  goToPage(page: number): void {
    if (page >= 1 && page <= this.totalPages()) {
      this.currentPage.set(page);
    }
  }
  
  // 上一页
  prevPage(): void {
    this.goToPage(this.currentPage() - 1);
  }
  
  // 下一页
  nextPage(): void {
    this.goToPage(this.currentPage() + 1);
  }
  
  // 格式化日期
  formatDate(date: Date): string {
    return new Date(date).toLocaleDateString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
      year: 'numeric'
    });
  }
  // 智能页码生成
pageNumbers = computed(() => {
  const pages = [];
  const total = this.totalPages();
  const current = this.currentPage();
  
  // 显示当前页及前后2页，加上第一页和最后一页
  const start = Math.max(1, current - 2);
  const end = Math.min(total, current + 2);
  
  if (start > 1) {
    pages.push(1);
    if (start > 2) {
      pages.push(-1); // 用-1表示省略号
    }
  }
  
  for (let i = start; i <= end; i++) {
    pages.push(i);
  }
  
  if (end < total) {
    if (end < total - 1) {
      pages.push(-1); // 用-1表示省略号
    }
    pages.push(total);
  }
  
  return pages;
});
  // 格式化样式显示的辅助方法
  getStyleDisplay(caseItem: CaseItem | null | undefined): string {
    if (!caseItem || !caseItem.style) {
      return '';
    }
    return Array.isArray(caseItem.style) ? caseItem.style.join('、') : String(caseItem.style);
  }

  // 如果需要直接获取当前选中案例的样式显示
  getSelectedCaseStyle(): string {
    return this.getStyleDisplay(this.selectedCase());
  }

  // 删除重复的简单分页逻辑
  // 保留智能分页逻辑（第251-270行）
  // 移除下面这段代码：
  //  // 在组件类中添加这个计算属性
  //  pageNumbers = computed(() => {
  //    const pages = [];
  //    for (let i = 1; i <= this.totalPages(); i++) {
  //      pages.push(i);
  //    }
  //    return pages;
  //  });
  
  // 修复 onStyleChange 方法中的类型安全问题
  onStyleChange(style: string, isChecked: boolean): void {
    const currentStyles = (this.filterForm.get('style')?.value || []) as string[];
    let updatedStyles: string[];
    
    if (isChecked) {
      // 如果勾选，则添加风格（避免重复）
      updatedStyles = [...new Set([...currentStyles, style])];
    } else {
      // 如果取消勾选，则移除风格
      updatedStyles = currentStyles.filter(s => s !== style);
    }
    
    this.filterForm.patchValue({ style: updatedStyles });
  }
}