import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';

export interface FurnitureFormOption {
  id: string;
  name: string;
  description: string;
  icon: string; // SVG path或图标名
  textures: Array<'smooth' | 'rough' | 'soft' | 'hard' | 'glossy' | 'matte'>;
  examples: string[]; // 示例描述
}

export interface FormAnalysisResult {
  selectedForms: FurnitureFormOption[];
  dominantTexture: string;
  formComplexity: 'simple' | 'moderate' | 'complex';
  styleDirection: string;
}

@Component({
  selector: 'app-furniture-form-selector',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './furniture-form-selector.html',
  styleUrls: ['./furniture-form-selector.scss']
})
export class FurnitureFormSelectorComponent implements OnInit {
  @Input() preselectedForms: string[] = []; // 预选的形体ID
  @Input() maxSelections: number = 3; // 最多选择数量
  @Input() showExamples: boolean = true; // 是否显示示例
  
  @Output() selectionChanged = new EventEmitter<FormAnalysisResult>();

  // 可用的形体选项
  formOptions: FurnitureFormOption[] = [
    {
      id: 'curved-soft',
      name: '曲线柔和',
      description: '圆润流畅的线条，柔软舒适的质感',
      icon: 'M3 12 Q12 3, 21 12 T39 12',
      textures: ['soft', 'smooth'],
      examples: ['布艺沙发', '圆角茶几', '弧形书架']
    },
    {
      id: 'straight-hard',
      name: '直线硬朗',
      description: '笔直清晰的线条，坚硬稳固的质感',
      icon: 'M3 3 L21 3 L21 21 L3 21 Z',
      textures: ['hard', 'smooth'],
      examples: ['方形餐桌', '直角书柜', '金属椅']
    },
    {
      id: 'organic-rough',
      name: '有机粗糙',
      description: '自然不规则的形态，粗糙质朴的质感',
      icon: 'M3 12 Q6 8, 9 12 T15 12 Q18 16, 21 12',
      textures: ['rough', 'soft'],
      examples: ['实木家具', '藤编椅', '石材台面']
    },
    {
      id: 'geometric-glossy',
      name: '几何光泽',
      description: '规则几何图形，光滑反光的质感',
      icon: 'M12 3 L21 12 L12 21 L3 12 Z',
      textures: ['glossy', 'hard', 'smooth'],
      examples: ['玻璃茶几', '镜面柜', '金属灯具']
    },
    {
      id: 'layered-matte',
      name: '分层哑光',
      description: '多层次堆叠，柔和哑光的质感',
      icon: 'M3 6 L21 6 M3 12 L21 12 M3 18 L21 18',
      textures: ['matte', 'soft'],
      examples: ['布艺窗帘', '亚麻沙发', '木饰面墙']
    },
    {
      id: 'mixed-texture',
      name: '混合质感',
      description: '多种材质组合，对比鲜明',
      icon: 'M3 3 L12 3 Q21 3, 21 12 L21 21 L3 21 Z',
      textures: ['smooth', 'rough', 'glossy', 'matte'],
      examples: ['皮木结合椅', '金属玻璃桌', '布艺金属灯']
    }
  ];

  selectedForms: FurnitureFormOption[] = [];

  ngOnInit(): void {
    // 根据预选ID初始化选择
    if (this.preselectedForms.length > 0) {
      this.selectedForms = this.formOptions.filter(opt => 
        this.preselectedForms.includes(opt.id)
      );
      this.emitSelection();
    }
  }

  /**
   * 切换形体选择
   */
  toggleFormSelection(form: FurnitureFormOption): void {
    const index = this.selectedForms.findIndex(f => f.id === form.id);
    
    if (index > -1) {
      // 取消选择
      this.selectedForms.splice(index, 1);
    } else {
      // 添加选择（检查最大数量）
      if (this.selectedForms.length < this.maxSelections) {
        this.selectedForms.push(form);
      } else {
        // 替换第一个选择
        this.selectedForms.shift();
        this.selectedForms.push(form);
      }
    }
    
    this.emitSelection();
  }

  /**
   * 检查是否已选择
   */
  isSelected(formId: string): boolean {
    return this.selectedForms.some(f => f.id === formId);
  }

  /**
   * 发射选择变更事件
   */
  private emitSelection(): void {
    const result: FormAnalysisResult = {
      selectedForms: this.selectedForms,
      dominantTexture: this.calculateDominantTexture(),
      formComplexity: this.calculateFormComplexity(),
      styleDirection: this.determineStyleDirection()
    };
    
    this.selectionChanged.emit(result);
  }

  /**
   * 计算主导质感
   */
  calculateDominantTexture(): string {
    const textureCount: { [key: string]: number } = {};
    
    this.selectedForms.forEach(form => {
      form.textures.forEach(texture => {
        textureCount[texture] = (textureCount[texture] || 0) + 1;
      });
    });
    
    let maxCount = 0;
    let dominant = 'smooth';
    
    Object.entries(textureCount).forEach(([texture, count]) => {
      if (count > maxCount) {
        maxCount = count;
        dominant = texture;
      }
    });
    
    return this.getTextureName(dominant);
  }

  /**
   * 计算形体复杂度
   */
  calculateFormComplexity(): 'simple' | 'moderate' | 'complex' {
    if (this.selectedForms.length === 0) return 'simple';
    if (this.selectedForms.length === 1) return 'simple';
    
    const hasOrganic = this.selectedForms.some(f => f.id === 'organic-rough');
    const hasMixed = this.selectedForms.some(f => f.id === 'mixed-texture');
    const hasGeometric = this.selectedForms.some(f => f.id === 'geometric-glossy');
    
    if (hasMixed || (hasOrganic && hasGeometric)) return 'complex';
    if (this.selectedForms.length >= 2) return 'moderate';
    
    return 'simple';
  }

  /**
   * 确定风格方向
   */
  determineStyleDirection(): string {
    if (this.selectedForms.length === 0) return '未定义';
    
    const formIds = this.selectedForms.map(f => f.id);
    
    if (formIds.includes('curved-soft') && formIds.includes('layered-matte')) {
      return '温馨舒适';
    }
    if (formIds.includes('straight-hard') && formIds.includes('geometric-glossy')) {
      return '现代简约';
    }
    if (formIds.includes('organic-rough')) {
      return '自然质朴';
    }
    if (formIds.includes('mixed-texture')) {
      return '混搭创新';
    }
    if (formIds.includes('geometric-glossy')) {
      return '时尚现代';
    }
    
    return '综合风格';
  }

  /**
   * 获取质感中文名称
   */
  getTextureName(texture: string): string {
    const nameMap: { [key: string]: string } = {
      'smooth': '光滑',
      'rough': '粗糙',
      'soft': '柔软',
      'hard': '坚硬',
      'glossy': '光泽',
      'matte': '哑光'
    };
    return nameMap[texture] || texture;
  }

  /**
   * 获取复杂度中文名称
   */
  getComplexityName(complexity: 'simple' | 'moderate' | 'complex'): string {
    const nameMap = {
      'simple': '简单',
      'moderate': '中等',
      'complex': '复杂'
    };
    return nameMap[complexity];
  }

  /**
   * 清除所有选择
   */
  clearSelections(): void {
    this.selectedForms = [];
    this.emitSelection();
  }
}

