import { Component, OnInit, Input, ChangeDetectionStrategy, ChangeDetectorRef, ViewChild, ElementRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { IonIcon } from '@ionic/angular/standalone';
import { ProductSpaceService, Project } from '../../../services/product-space.service';
import { completionJSON } from 'fmode-ng';

/**
 * 确认需求阶段组件 - Product表统一空间管理
 */
@Component({
  selector: 'app-stage-requirements',
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule, IonIcon],
  templateUrl: './stage-requirements.component.html',
  styleUrls: ['./stage-requirements.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class StageRequirementsComponent implements OnInit {
  @Input() project: any = null;
  @Input() customer: any = null;
  @Input() currentUser: any = null;
  @Input() canEdit: boolean = false;

  // 路由参数
  cid: string = '';
  projectId: string = '';

  // Product-based 空间管理
  projectProducts: Project[] = [];
  isMultiProductProject: boolean = false;
  activeProductId: string = '';
  selectedProductIds: string[] = [];

  // 需求分段管理
  requirementsSegment: string = 'global'; // global | spaces | cross-space

  // 全局需求
  globalRequirements = {
    stylePreference: '',
    colorScheme: {
      primary: '',
      secondary: '',
      accent: '',
      atmosphere: ''
    },
    overallBudget: {
      min: 0,
      max: 0
    },
    timeline: '',
    qualityLevel: 'standard', // standard | premium | luxury
    specialRequirements: '',
    environmentRequirements: {
      lighting: '',
      ventilation: '',
      noise: '',
      temperature: ''
    }
  };

  // 空间需求数据
  spaceRequirements: any[] = [];

  // 跨空间需求
  crossSpaceRequirements: any[] = [];

  // 参考图片（支持按空间分类）
  referenceImages: Array<{
    id: string;
    url: string;
    name: string;
    type: string; // style | space | material
    uploadTime: Date;
    description?: string;
    spaceId?: string;
    tags: string[];
  }> = [];

  // CAD文件
  cadFiles: Array<{
    id: string;
    url: string;
    name: string;
    uploadTime: Date;
    size: number;
    spaceId?: string;
  }> = [];

  // AI生成的方案
  aiSolution: {
    generated: boolean;
    content: string;
    spaces: Array<{
      id: string;
      name: string;
      type: string;
      styleDescription: string;
      colorPalette: string[];
      materials: string[];
      furnitureRecommendations: string[];
      estimatedCost?: number;
      timeline?: string;
    }>;
    estimatedCost: number;
    timeline: string;
    crossSpaceCoordination?: {
      styleConsistency: {
        description: string;
        keyElements: string[];
      };
      functionalFlow: {
        description: string;
        considerations: string[];
      };
      timelineCoordination: {
        description: string;
        strategy: string;
      };
    };
  } | null = null;

  // AI分析相关数据
  aiAnalysisResults: {
    imageAnalysis?: Array<{
      imageId: string;
      styleElements: string[];
      colorPalette: string[];
      materialAnalysis: string[];
      layoutFeatures: string[];
      mood: string;
      confidence: number;
    }>;
    cadAnalysis?: Array<{
      fileId: string;
      spaceStructure: any;
      dimensions: any;
      constraints: string[];
      opportunities: string[];
    }>;
    comprehensiveAnalysis?: {
      overallStyle: string;
      colorScheme: any;
      materialRecommendations: string[];
      layoutOptimization: string[];
      budgetAssessment: any;
      timeline: string;
      riskFactors: string[];
    };
  } = {};

  // AI聊天相关
  aiChatMessages: Array<{
    id: string;
    role: 'user' | 'assistant';
    content: string;
    timestamp: Date;
    analysisType?: string;
  }> = [];

  // AI分析状态
  aiAnalyzing: boolean = false;
  aiAnalyzingImages: boolean = false;
  aiAnalyzingCAD: boolean = false;
  aiGeneratingComprehensive: boolean = false;
  showAIChat: boolean = false;
  aiChatInput: string = '';

  // AI分析配置
  private readonly AI_MODEL = 'fmode-1.6-cn';

  // 加载状态
  loading: boolean = true;
  uploading: boolean = false;
  generating: boolean = false;
  saving: boolean = false;

  // 模板引用变量
  @ViewChild('chatMessages') chatMessagesContainer!: ElementRef;

  constructor(
    private route: ActivatedRoute,
    private cdr: ChangeDetectorRef,
    private productSpaceService: ProductSpaceService
  ) {}

  async ngOnInit() {
    // 尝试从父组件获取数据（如果通过@Input传入）
    // 否则从路由参数加载
    if (!this.project || !this.customer || !this.currentUser) {
      this.cid = this.route.parent?.snapshot.paramMap.get('cid') || '';
      this.projectId = this.route.parent?.snapshot.paramMap.get('projectId') || '';
    }

    await this.loadData();
  }

  /**
   * 加载数据
   */
  async loadData() {
    try {
      this.loading = true;

      // 从项目ID加载Product数据
      if (this.projectId) {
        this.projectProducts = await this.productSpaceService.getProjectProductSpaces(this.projectId);
      } else if (this.project) {
        // 如果有project对象，使用其ID
        this.projectProducts = await this.productSpaceService.getProjectProductSpaces(this.project.id);
      }

      this.isMultiProductProject = this.projectProducts.length > 1;

      // 如果有产品，默认选中第一个
      if (this.projectProducts.length > 0 && !this.activeProductId) {
        this.activeProductId = this.projectProducts[0].id;
      }

      // 模拟加载需求数据
      this.globalRequirements = {
        stylePreference: '现代简约',
        colorScheme: {
          primary: '#ffffff',
          secondary: '#f5f5f5',
          accent: '#3880ff',
          atmosphere: '温馨'
        },
        overallBudget: { min: 15, max: 25 },
        timeline: '45天',
        qualityLevel: 'premium',
        specialRequirements: '需要充足的储物空间',
        environmentRequirements: {
          lighting: '明亮自然',
          ventilation: '良好通风',
          noise: '隔音处理',
          temperature: '恒温控制'
        }
      };

      // 模拟加载参考图片
      this.referenceImages = [
        { id: '1', url: 'https://via.placeholder.com/300x300/3880ff/ffffff?text=客厅', name: '客厅风格参考', type: 'style', uploadTime: new Date(), spaceId: '1', tags: ['现代', '简约'] },
        { id: '2', url: 'https://via.placeholder.com/300x300/2dd36f/ffffff?text=主卧', name: '主卧风格参考', type: 'style', uploadTime: new Date(), spaceId: '2', tags: ['温馨', '舒适'] }
      ];

      this.cdr.markForCheck();

    } catch (err) {
      console.error('加载失败:', err);
    } finally {
      this.loading = false;
    }
  }

  // ===== 多空间需求管理方法 =====

  /**
   * 切换需求分段
   */
  onRequirementsSegmentChange(event: any): void {
    this.requirementsSegment = event.detail.value;
    this.cdr.markForCheck();
  }

  /**
   * 选择需求分段
   */
  selectRequirementsSegment(segment: string): void {
    this.requirementsSegment = segment;
    this.cdr.markForCheck();
  }

  /**
   * 选择产品空间
   */
  selectProduct(productId: string): void {
    this.activeProductId = productId;
    this.cdr.markForCheck();
  }

  /**
   * 切换产品选择状态
   */
  toggleProductSelection(productId: string): void {
    const index = this.selectedProductIds.indexOf(productId);
    if (index > -1) {
      this.selectedProductIds.splice(index, 1);
    } else {
      this.selectedProductIds.push(productId);
    }
    this.cdr.markForCheck();
  }

  /**
   * 上传参考图片
   */
  async uploadReferenceImage(event: any, productId?: string): Promise<void> {
    const files = event.target.files;
    if (!files || files.length === 0) return;

    try {
      this.uploading = true;

      for (let i = 0; i < files.length; i++) {
        const file = files[i];

        // 简单的文件类型验证
        if (!file.type.startsWith('image/')) {
          console.warn(`文件 ${file.name} 不是图片格式，跳过`);
          continue;
        }

        // 验证文件大小 (10MB)
        if (file.size > 10 * 1024 * 1024) {
          console.warn(`文件 ${file.name} 超过10MB限制，跳过`);
          continue;
        }

        // 模拟文件上传
        const uploadedFile = {
          id: `img_${Date.now()}_${i}`,
          url: URL.createObjectURL(file),
          name: file.name,
          type: 'style',
          uploadTime: new Date(),
          spaceId: productId || this.activeProductId, // 保持兼容性，后续可改为productId
          tags: []
        };

        // 添加到参考图片列表
        this.analysisImageMap[uploadedFile?.id] = uploadedFile
        this.referenceImages.push(uploadedFile);
      }

      this.cdr.markForCheck();

    } catch (error) {
      console.error('上传失败:', error);
    } finally {
      this.uploading = false;
    }
  }

  analysisImageMap:any = {}
  /**
   * 删除参考图片
   */
  async deleteReferenceImage(imageId: string): Promise<void> {
    try {
      // 从列表中移除
      this.referenceImages = this.referenceImages.filter(img => img.id !== imageId);
      this.cdr.markForCheck();

    } catch (error) {
      console.error('删除参考图片失败:', error);
    }
  }

  /**
   * 上传CAD文件
   */
  async uploadCAD(event: any, productId?: string): Promise<void> {
    const files = event.target.files;
    if (!files || files.length === 0) return;

    try {
      this.uploading = true;

      for (let i = 0; i < files.length; i++) {
        const file = files[i];

        // 验证文件类型
        const allowedExtensions = ['.dwg', '.dxf', '.pdf'];
        const fileExtension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
        if (!allowedExtensions.includes(fileExtension)) {
          console.warn(`文件 ${file.name} 不是支持的CAD格式，跳过`);
          continue;
        }

        // 验证文件大小 (50MB)
        if (file.size > 50 * 1024 * 1024) {
          console.warn(`文件 ${file.name} 超过50MB限制，跳过`);
          continue;
        }

        // 模拟文件上传
        const uploadedFile = {
          id: `cad_${Date.now()}_${i}`,
          url: URL.createObjectURL(file),
          name: file.name,
          uploadTime: new Date(),
          size: file.size,
          spaceId: productId || this.activeProductId // 保持兼容性，后续可改为productId
        };

        // 添加到CAD文件列表
        this.cadFiles.push(uploadedFile);
      }

      this.cdr.markForCheck();

    } catch (error) {
      console.error('上传失败:', error);
    } finally {
      this.uploading = false;
    }
  }

  /**
   * 删除CAD文件
   */
  async deleteCAD(fileId: string): Promise<void> {
    try {
      // 从列表中移除
      this.cadFiles = this.cadFiles.filter(file => file.id !== fileId);
      this.cdr.markForCheck();

    } catch (error) {
      console.error('删除CAD文件失败:', error);
    }
  }

  /**
   * 生成AI方案
   */
  async generateAISolution(): Promise<void> {
    if (!this.project || !this.canEdit) return;

    try {
      this.generating = true;

      // 先进行AI分析，再生成方案
      await this.performComprehensiveAIAnalysis();

      // 基于AI分析结果生成方案
      this.aiSolution = {
        generated: true,
        content: this.generateSolutionContent(),
        spaces: this.generateSpaceSolutions(),
        estimatedCost: this.calculateAIEnhancedEstimatedCost(),
        timeline: this.calculateAIEnhancedTimeline(),
        crossSpaceCoordination: this.generateAICrossSpaceCoordination()
      };

      this.cdr.markForCheck();

    } catch (error) {
      console.error('生成失败:', error);
    } finally {
      this.generating = false;
    }
  }

  /**
   * AI分析参考图片
   */
  async analyzeReferenceImages(): Promise<void> {
    if (this.referenceImages.length === 0) return;

    try {
      this.aiAnalyzingImages = true;
      this.aiAnalysisResults.imageAnalysis = [];

      for (const image of this.referenceImages) {
        const analysisResult = await this.analyzeImage(image);
        this.aiAnalysisResults.imageAnalysis.push(analysisResult);
      }

      this.cdr.markForCheck();
    } catch (error) {
      console.error('图片分析失败:', error);
    } finally {
      this.aiAnalyzingImages = false;
    }
  }

  /**
   * 分析单张图片
   */
  private async analyzeImage(image: any): Promise<any> {
    try {
      const prompt = `分析这张家装参考图片，提取以下设计信息：
{
  "styleElements": ["风格元素1", "风格元素2"],
  "colorPalette": ["#主色调", "#副色调", "#点缀色"],
  "materialAnalysis": ["材质1", "材质2"],
  "layoutFeatures": ["布局特征1", "布局特征2"],
  "mood": "空间氛围描述",
  "confidence": 0.95
}

要求：
1. 准确识别图片中的设计风格（如现代简约、北欧、轻奢等）
2. 提取主要色彩搭配（HEX格式）
3. 识别使用的材质（如实木、大理石、布艺等）
4. 分析空间布局特点
5. 描述整体氛围感受`;

      const output = `{
  "styleElements": ["现代简约", "线条流畅", "留白设计"],
  "colorPalette": ["#FFFFFF", "#F5F5F5", "#3880FF"],
  "materialAnalysis": ["实木地板", "布艺沙发", "金属装饰"],
  "layoutFeatures": ["开放式布局", "功能分区明确", "采光良好"],
  "mood": "简洁明亮，温馨舒适",
  "confidence": 0.92
}`;

      // 转换图片为Base64（实际项目中应该使用已上传的Base64数据）
      const imageBase64 = await this.convertImageToBase64(image.url);

      const result = await completionJSON(
        prompt,
        output,
        (_content) => {
          // 进度回调
        },
        2,
        {
          model: this.AI_MODEL,
          vision: true,
          images: [imageBase64]
        }
      );

      return {
        imageId: image.id,
        ...result
      };

    } catch (error) {
      console.error('图片分析失败:', error);
      return {
        imageId: image.id,
        styleElements: [],
        colorPalette: [],
        materialAnalysis: [],
        layoutFeatures: [],
        mood: '',
        confidence: 0
      };
    }
  }

  /**
   * AI分析CAD文件
   */
  async analyzeCADFiles(): Promise<void> {
    if (this.cadFiles.length === 0) return;

    try {
      this.aiAnalyzingCAD = true;
      this.aiAnalysisResults.cadAnalysis = [];

      for (const cadFile of this.cadFiles) {
        const analysisResult = await this.analyzeCADFile(cadFile);
        this.analysisFileMap[analysisResult?.fileId] = analysisResult;
        this.aiAnalysisResults.cadAnalysis.push(analysisResult);
      }

      this.cdr.markForCheck();
    } catch (error) {
      console.error('CAD分析失败:', error);
    } finally {
      this.aiAnalyzingCAD = false;
    }
  }
  analysisFileMap:any = {}

  /**
   * 分析单个CAD文件
   */
  private async analyzeCADFile(cadFile: any): Promise<any> {
    try {
      const prompt = `分析这个CAD户型文件，提取空间结构信息：
{
  "spaceStructure": {
    "totalArea": "总面积",
    "roomCount": "房间数量",
    "layoutType": "布局类型"
  },
  "dimensions": {
    "length": "长度",
    "width": "宽度",
    "height": "层高"
  },
  "constraints": ["限制因素1", "限制因素2"],
  "opportunities": ["优化机会1", "优化机会2"]
}

要求：
1. 识别空间结构和尺寸
2. 分析承重墙、管道等限制因素
3. 提供布局优化建议`;

      const output = `{
  "spaceStructure": {
    "totalArea": "120㎡",
    "roomCount": "3室2厅",
    "layoutType": "南北通透"
  },
  "dimensions": {
    "length": "12m",
    "width": "10m",
    "height": "2.8m"
  },
  "constraints": ["承重墙不可拆改", "主管道位置固定"],
  "opportunities": ["客厅阳台可打通", "厨房可做开放式设计"]
}`;

      // 模拟CAD分析（实际需要CAD解析库）
      const result = await completionJSON(
        prompt,
        output,
        (_content) => {
          // 进度回调
        },
        2,
        {
          model: this.AI_MODEL
        }
      );

      return {
        fileId: cadFile.id,
        ...result
      };

    } catch (error) {
      console.error('CAD文件分析失败:', error);
      return {
        fileId: cadFile.id,
        spaceStructure: {},
        dimensions: {},
        constraints: [],
        opportunities: []
      };
    }
  }

  /**
   * 执行综合AI分析
   */
  async performComprehensiveAIAnalysis(): Promise<void> {
    try {
      this.aiGeneratingComprehensive = true;

      // 并行执行图片和CAD分析
      await Promise.all([
        this.analyzeReferenceImages(),
        this.analyzeCADFiles()
      ]);

      // 生成综合分析
      await this.generateComprehensiveAnalysis();

      this.cdr.markForCheck();
    } catch (error) {
      console.error('综合分析失败:', error);
    } finally {
      this.aiGeneratingComprehensive = false;
    }
  }

  /**
   * 生成综合分析
   */
  private async generateComprehensiveAnalysis(): Promise<void> {
    try {
      const prompt = `基于以下信息，生成综合设计方案分析：

参考图片分析：${JSON.stringify(this.aiAnalysisResults.imageAnalysis, null, 2)}
CAD文件分析：${JSON.stringify(this.aiAnalysisResults.cadAnalysis, null, 2)}
用户需求：${JSON.stringify(this.globalRequirements, null, 2)}
产品信息：${JSON.stringify(this.projectProducts.map(p => ({
  name: p.name,
  type: p.type,
  area: p.area
    })), null, 2)}

请生成以下格式的综合分析：
{
  "overallStyle": "整体风格定位",
  "colorScheme": {
    "primary": "主色调",
    "secondary": "副色调",
    "accent": "点缀色"
  },
  "materialRecommendations": ["材质1", "材质2"],
  "layoutOptimization": ["布局优化建议1", "布局优化建议2"],
  "budgetAssessment": {
    "estimatedMin": 最低预算,
    "estimatedMax": 最高预算,
    "riskLevel": "风险等级"
  },
  "timeline": "预计工期",
  "riskFactors": ["风险因素1", "风险因素2"]
}`;

      const output = `{
  "overallStyle": "现代简约风格，注重功能性和舒适性",
  "colorScheme": {
    "primary": "#FFFFFF",
    "secondary": "#F5F5F5",
    "accent": "#3880FF"
  },
  "materialRecommendations": ["实木复合地板", "环保乳胶漆", "布艺沙发"],
  "layoutOptimization": ["打通客厅阳台，增加空间感", "厨房做开放式设计，提升互动性"],
  "budgetAssessment": {
    "estimatedMin": 150000,
    "estimatedMax": 250000,
    "riskLevel": "中等"
  },
  "timeline": "60-75个工作日",
  "riskFactors": ["工期可能受天气影响", "材料价格波动风险"]
}`;

      const result = await completionJSON(
        prompt,
        output,
        (_content) => {
          // 进度回调
        },
        2,
        {
          model: this.AI_MODEL
        }
      );

      this.aiAnalysisResults.comprehensiveAnalysis = result;

    } catch (error) {
      console.error('综合分析生成失败:', error);
    }
  }

  /**
   * AI聊天助手
   */
  async sendAIChatMessage(): Promise<void> {
    if (!this.aiChatInput.trim()) return;

    try {
      const userMessage = {
        id: `msg_${Date.now()}`,
        role: 'user' as const,
        content: this.aiChatInput,
        timestamp: new Date()
      };

      this.aiChatMessages.push(userMessage);
      this.aiChatInput = '';
      this.cdr.markForCheck();

      // 生成AI回复
      const aiResponse = await this.generateAIChatResponse(userMessage.content);

      this.aiChatMessages.push({
        id: `msg_${Date.now() + 1}`,
        role: 'assistant',
        content: aiResponse,
        timestamp: new Date()
      });

      this.cdr.markForCheck();

    } catch (error) {
      console.error('AI聊天失败:', error);
    }
  }

  /**
   * 生成AI聊天回复
   */
  private async generateAIChatResponse(userMessage: string): Promise<string> {
    try {
      const context = `
项目背景：${JSON.stringify(this.globalRequirements, null, 2)}
AI分析结果：${JSON.stringify(this.aiAnalysisResults, null, 2)}
产品信息：${JSON.stringify(this.projectProducts.map(p => ({
    name: p.name,
    type: p.type,
    area: p.area
  })), null, 2)}`;

      const prompt = `作为专业的家装设计AI助手，基于以下项目信息回答用户问题：

${context}

用户问题：${userMessage}

请提供专业、实用的建议，回答要简洁明了，字数控制在200字以内。`;

      const result = await completionJSON(
        prompt,
        '{"response": "专业的家装设计建议"}',
        (content) => {
          // 流式输出回调
        },
        2,
        {
          model: this.AI_MODEL
        }
      );

      return result.response || '抱歉，我暂时无法回答这个问题。';

    } catch (error) {
      console.error('AI回复生成失败:', error);
      return '抱歉，服务暂时不可用，请稍后再试。';
    }
  }

  /**
   * 转换图片为Base64
   */
  private async convertImageToBase64(_imageUrl: string): Promise<string> {
    // 实际项目中，图片上传时应该已经保存了Base64格式
    // 这里返回一个模拟的Base64字符串
    return 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAABAAEDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAv/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFQEBAQAAAAAAAAAAAAAAAAAAAAX/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwA/wA==';
  }

  /**
   * 生成方案内容
   */
  private generateSolutionContent(): string {
    const analysis = this.aiAnalysisResults.comprehensiveAnalysis;
    if (analysis) {
      return `基于AI分析结果，我们为您推荐${analysis.overallStyle}，通过${analysis.colorScheme.primary}、${analysis.colorScheme.secondary}、${analysis.colorScheme.accent}的色彩搭配，营造${this.globalRequirements.colorScheme.atmosphere}的居住氛围。`;
    }
    return `基于您的${this.globalRequirements.stylePreference}风格需求，我们为您设计了以下方案...`;
  }

  /**
   * 生成空间方案
   */
  private generateSpaceSolutions(): any[] {
    return this.projectProducts.map(product => {
      const analysis = this.aiAnalysisResults.comprehensiveAnalysis;
      return {
        id: product.id,
        name: product.name,
        type: product.type,
        styleDescription: `${analysis?.overallStyle || this.globalRequirements.stylePreference}风格${product.name}设计`,
        colorPalette: analysis ? [analysis.colorScheme.primary, analysis.colorScheme.secondary, analysis.colorScheme.accent] : [this.globalRequirements.colorScheme.primary, this.globalRequirements.colorScheme.secondary, this.globalRequirements.colorScheme.accent],
        materials: analysis?.materialRecommendations || ['实木', '大理石', '布艺'],
        furnitureRecommendations: this.getFurnitureRecommendations(product.type),
        estimatedCost: this.calculateProductEstimatedCost(product),
        timeline: this.calculateProductTimeline(product)
      };
    });
  }

  /**
   * 计算AI增强的估算成本
   */
  private calculateAIEnhancedEstimatedCost(): number {
    const analysis = this.aiAnalysisResults.comprehensiveAnalysis;
    if (analysis?.budgetAssessment) {
      return analysis.budgetAssessment.estimatedMax || this.calculateTotalEstimatedCost();
    }
    return this.globalRequirements.overallBudget.max || this.calculateTotalEstimatedCost();
  }

  /**
   * 计算AI增强的工期
   */
  private calculateAIEnhancedTimeline(): string {
    const analysis = this.aiAnalysisResults.comprehensiveAnalysis;
    return analysis?.timeline || this.calculateTotalTimeline();
  }

  /**
   * 生成AI跨空间协调方案
   */
  private generateAICrossSpaceCoordination(): any {
    const analysis = this.aiAnalysisResults.comprehensiveAnalysis;
    return {
      styleConsistency: {
        description: analysis ? `确保${analysis.overallStyle}风格在各空间的统一体现` : '确保各空间风格统一协调',
        keyElements: ['色彩搭配', '材质选择', '设计元素']
      },
      functionalFlow: {
        description: analysis ? `基于${analysis.layoutOptimization?.join('、') || '空间规划'}优化功能流线` : '优化空间之间的功能流线',
        considerations: ['动线规划', '采光通风', '噪音控制']
      },
      timelineCoordination: {
        description: '协调各空间施工时间',
        strategy: '并行施工，关键节点协调'
      }
    };
  }

  /**
   * 切换AI聊天显示
   */
  toggleAIChat(): void {
    this.showAIChat = !this.showAIChat;
    this.cdr.markForCheck();
  }

  /**
   * 获取家具推荐
   */
  private getFurnitureRecommendations(spaceType: string): string[] {
    const recommendations: Record<string, string[]> = {
      'living_room': ['沙发', '茶几', '电视柜', '书架', '装饰柜'],
      'bedroom': ['床', '衣柜', '床头柜', '梳妆台', '椅子'],
      'kitchen': ['橱柜', '冰箱', '灶具', '抽油烟机', '洗碗机'],
      'bathroom': ['浴室柜', '马桶', '淋浴房', '花洒', '镜子'],
      'dining_room': ['餐桌', '餐椅', '餐边柜', '酒柜', '装饰品'],
      'study': ['书桌', '书椅', '书架', '台灯', '电脑桌']
    };
    return recommendations[spaceType] || ['基础家具'];
  }

  /**
   * 计算产品估算成本
   */
  private calculateProductEstimatedCost(product: Project): number {
    const baseCostPerSqm: Record<string, number> = {
      'living_room': 1500,
      'bedroom': 1200,
      'kitchen': 2000,
      'bathroom': 1800,
      'dining_room': 1300,
      'study': 1100
    };
    const baseCost = (baseCostPerSqm[product.type] || 1000) * (product.area || 10);
    const qualityMultiplier: Record<string, number> = {
      'standard': 1.0,
      'premium': 1.5,
      'luxury': 2.0
    };
    return baseCost * (qualityMultiplier[this.globalRequirements.qualityLevel] || 1.0);
  }

  /**
   * 计算总估算成本
   */
  private calculateTotalEstimatedCost(): number {
    return this.projectProducts.reduce((total, product) => {
      return total + this.calculateProductEstimatedCost(product);
    }, 0);
  }

  /**
   * 计算产品工期
   */
  private calculateProductTimeline(product: Project): string {
    const baseDays: Record<string, number> = {
      'living_room': 15,
      'bedroom': 12,
      'kitchen': 20,
      'bathroom': 18,
      'dining_room': 10,
      'study': 8
    };
    return `${baseDays[product.type] || 10}-15个工作日`;
  }

  /**
   * 计算总工期
   */
  private calculateTotalTimeline(): string {
    const totalDays = this.projectProducts.reduce((total, product) => {
      const baseDays: Record<string, number> = {
        'living_room': 15,
        'bedroom': 12,
        'kitchen': 20,
        'bathroom': 18,
        'dining_room': 10,
        'study': 8
      };
      return total + (baseDays[product.type] || 10);
    }, 0);
    return `预计${Math.ceil(totalDays * 0.7)}-${totalDays}个工作日（考虑并行施工）`;
  }

  
  /**
   * 保存草稿
   */
  async saveDraft(): Promise<void> {
    if (!this.project || !this.canEdit) return;

    try {
      this.saving = true;

      // 模拟保存逻辑
      console.log('保存草稿');

    } catch (err) {
      console.error('保存失败:', err);
    } finally {
      this.saving = false;
      this.cdr.markForCheck();
    }
  }

  /**
   * 提交确认
   */
  async submitRequirements(): Promise<void> {
    if (!this.project || !this.canEdit) return;

    try {
      this.saving = true;

      // 模拟提交逻辑
      console.log('提交需求确认');

    } catch (err) {
      console.error('提交失败:', err);
    } finally {
      this.saving = false;
      this.cdr.markForCheck();
    }
  }

  // ===== 工具方法 =====

  /**
   * 获取空间图标
   */
  getSpaceIcon(spaceType: string): string {
    const iconMap: Record<string, string> = {
      'living_room': 'home',
      'bedroom': 'bed',
      'kitchen': 'restaurant',
      'bathroom': 'water',
      'dining_room': 'restaurant',
      'study': 'book',
      'balcony': 'sunny',
      'corridor': 'walk',
      'storage': 'archive',
      'entrance': 'log-in',
      'other': 'grid'
    };
    return iconMap[spaceType] || 'grid';
  }

  /**
   * 获取空间类型名称
   */
  getSpaceTypeName(spaceType: string): string {
    const nameMap: Record<string, string> = {
      'living_room': '客厅',
      'bedroom': '卧室',
      'kitchen': '厨房',
      'bathroom': '卫生间',
      'dining_room': '餐厅',
      'study': '书房',
      'balcony': '阳台',
      'corridor': '走廊',
      'storage': '储物间',
      'entrance': '玄关',
      'other': '其他'
    };
    return nameMap[spaceType] || '其他';
  }

  /**
   * 获取空间显示名称
   */
  getSpaceDisplayName(space: any): string {
    return space.name || this.getSpaceTypeName(space.type);
  }

  /**
   * 获取当前产品的需求
   */
  getCurrentProductRequirement(): any {
    if (!this.activeProductId) return null;
    return this.spaceRequirements.find(req => req.productId === this.activeProductId) || {
      productId: this.activeProductId,
      colorRequirement: {},
      spaceStructureRequirement: {},
      materialRequirement: {},
      lightingRequirement: {},
      specificRequirements: ''
    };
  }

  /**
   * 获取当前产品特殊需求的 getter/setter
   */
  get currentProductSpecificRequirements(): string {
    const requirement = this.getCurrentProductRequirement();
    return requirement?.specificRequirements || '';
  }

  set currentProductSpecificRequirements(value: string) {
    const requirement = this.getCurrentProductRequirement();
    if (requirement) {
      requirement.specificRequirements = value;
    }
  }

  /**
   * 获取当前产品的评价
   */
  getCurrentProductFeedback(): any {
    return null;
  }

  /**
   * 过滤参考图片
   */
  getFilteredReferenceImages(): typeof this.referenceImages {
    if (!this.isMultiProductProject || !this.activeProductId) {
      return this.referenceImages;
    }
    return this.referenceImages.filter(img => !img.spaceId || img.spaceId === this.activeProductId);
  }

  /**
   * 过滤CAD文件
   */
  getFilteredCADFiles(): typeof this.cadFiles {
    if (!this.isMultiProductProject || !this.activeProductId) {
      return this.cadFiles;
    }
    return this.cadFiles.filter(file => !file.spaceId || file.spaceId === this.activeProductId);
  }

  /**
   * 获取图片类型标签
   */
  getImageTypeLabel(type: string): string {
    const map: Record<string, string> = {
      'style': '风格参考',
      'space': '空间布局',
      'material': '材质参考',
      'color': '色彩参考',
      'layout': '布局参考'
    };
    return map[type] || '其他';
  }

  /**
   * 获取图片类型颜色
   */
  getImageTypeColor(type: string): string {
    const map: Record<string, string> = {
      'style': 'primary',
      'space': 'secondary',
      'material': 'tertiary',
      'color': 'success',
      'layout': 'warning'
    };
    return map[type] || 'medium';
  }

  /**
   * 获取空间的参考图片
   */
  getSpaceReferenceImages(spaceId?: string): any[] {
    if (!spaceId) return this.referenceImages;
    return this.referenceImages.filter(img => img.spaceId === spaceId);
  }

  /**
   * 格式化文件大小
   */
  formatFileSize(bytes: number): string {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }

  /**
   * 获取质量等级名称
   */
  getQualityLevelName(level: string): string {
    const levelMap: Record<string, string> = {
      'standard': '标准',
      'premium': '高级',
      'luxury': '豪华'
    };
    return levelMap[level] || '标准';
  }

  /**
   * 获取氛围名称
   */
  getAtmosphereName(atmosphere: string): string {
    const atmosphereMap: Record<string, string> = {
      'warm': '温馨',
      'luxury': '高级',
      'minimal': '简约',
      'fashion': '时尚',
      'nordic': '北欧',
      'chinese': '中式',
      'european': '欧式'
    };
    return atmosphereMap[atmosphere] || atmosphere;
  }

  /**
   * 获取跨空间需求类型名称
   */
  getCrossSpaceRequirementTypeName(type: string): string {
    const typeMap: Record<string, string> = {
      'style': '风格统一',
      'color': '色彩协调',
      'material': '材质搭配',
      'lighting': '照明衔接',
      'functional': '功能关联',
      'structural': '结构连接'
    };
    return typeMap[type] || type;
  }

  /**
   * 计算需求完成度
   */
  calculateRequirementsCompleteness(): number {
    let completedItems = 0;
    let totalItems = 0;

    // 全局需求检查
    if (this.globalRequirements.stylePreference) completedItems++;
    totalItems++;
    if (this.globalRequirements.colorScheme.primary) completedItems++;
    totalItems++;
    if (this.globalRequirements.overallBudget.max > 0) completedItems++;
    totalItems++;
    if (this.globalRequirements.timeline) completedItems++;
    totalItems++;

    // 产品需求检查
    for (const product of this.projectProducts) {
      const productFeedback = this.spaceRequirements.find(req => req.productId === product.id);
      if (productFeedback) {
        completedItems++;
      }
      totalItems++;
    }

    return totalItems > 0 ? Math.round((completedItems / totalItems) * 100) : 0;
  }

  /**
   * 计算产品完成度
   */
  calculateProductCompletion(_productId: string): number {
    // 简化计算，实际应该基于产品的具体需求完成情况
    return Math.floor(Math.random() * 100);
  }

  /**
   * 创建跨产品需求
   */
  async createCrossProductRequirement(requirement?: any): Promise<void> {
    console.log('创建跨产品需求:', requirement || {});
  }

  /**
   * 删除跨产品需求
   */
  async deleteCrossProductRequirement(requirementId: string): Promise<void> {
    console.log('删除跨产品需求:', requirementId);
  }

  /**
   * 获取工序颜色
   */
  getProcessColor(spaceType: string): string {
    const colorMap: Record<string, string> = {
      'living_room': 'primary',
      'bedroom': 'secondary',
      'kitchen': 'tertiary',
      'bathroom': 'success',
      'dining_room': 'warning',
      'study': 'medium'
    };
    return colorMap[spaceType] || 'primary';
  }

  /**
   * 获取图片类型徽章类名
   */
  getImageTypeBadgeClass(imageType: string): string {
    const colorClass = this.getImageTypeColor(imageType);
    return `badge-${colorClass}`;
  }

  /**
   * 获取工序徽章类名
   */
  getProcessBadgeClass(spaceType: string): string {
    const colorClass = this.getProcessColor(spaceType);
    return `badge-${colorClass}`;
  }

  /**
   * 获取关联空间ID列表
   */
  getRelatedSpaceIds(requirement: any): string[] {
    if (!requirement) return [];
    const ids = [requirement.primarySpaceId];
    if (requirement.relatedSpaceIds && Array.isArray(requirement.relatedSpaceIds)) {
      ids.push(...requirement.relatedSpaceIds);
    }
    return ids.filter(id => id); // 过滤掉空值
  }

  /**
   * 根据产品ID获取产品显示名称（用于模板）
   */
  getProductDisplayNameById(productId: string): string {
    const product = this.projectProducts.find(p => p.id === productId);
    return this.getProductDisplayName(product);
  }

  /**
   * 获取产品显示名称
   */
  getProductDisplayName(product: Project | undefined): string {
    return product?.name || '未知产品';
  }

  /**
   * 触发文件选择器点击
   */
  triggerFileClick(inputId: string): void {
    const element = document.getElementById(inputId) as HTMLInputElement;
    if (element) {
      element.click();
    }
  }

  // ===== AI分析辅助方法 =====

  /**
   * 获取分析对应的图片
   */
  getAnalysisImage(imageId: string): any {
    return this.referenceImages.find(img => img.id === imageId);
  }

  /**
   * 获取分析对应的CAD文件
   */
  getAnalysisFile(fileId: string): any {
    return this.cadFiles.find(file => file.id === fileId);
  }

  // === 模板辅助方法：避免在模板中使用箭头函数/复杂表达式 ===
  onAiChatInputChange(value: string): void {
    this.aiChatInput = value;
  }

  isAiChatSendDisabled(): boolean {
    return this.aiAnalyzing || !this.aiChatInput?.trim();
  }

  isSaving(): boolean {
    return this.saving;
  }

  isSubmitDisabled(): boolean {
    return this.saving || this.generating || this.aiAnalyzing;
  }

  hasImageAnalysis(imageId: string): boolean {
    return !!this.aiAnalysisResults.imageAnalysis?.some(x => x.imageId === imageId);
  }

  hasCadAnalysis(fileId: string): boolean {
    return !!this.aiAnalysisResults.cadAnalysis?.some(x => x.fileId === fileId);
  }

  /**
   * 获取风险等级样式类名
   */
  getRiskLevelClass(riskLevel: string): string {
    const classMap: Record<string, string> = {
      'low': 'badge-success',
      'medium': 'badge-warning',
      'high': 'badge-danger'
    };
    return classMap[riskLevel] || 'badge-secondary';
  }

  /**
   * 获取风险等级名称
   */
  getRiskLevelName(riskLevel: string): string {
    const nameMap: Record<string, string> = {
      'low': '低风险',
      'medium': '中等风险',
      'high': '高风险'
    };
    return nameMap[riskLevel] || '未知风险';
  }
}