import { Component, OnInit, Input, ChangeDetectionStrategy, ChangeDetectorRef } 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';

/**
 * 确认需求阶段组件 - 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;

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

  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.referenceImages.push(uploadedFile);
      }

      this.cdr.markForCheck();

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

  /**
   * 删除参考图片
   */
  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方案生成
      this.aiSolution = {
        generated: true,
        content: `基于您的${this.globalRequirements.stylePreference}风格需求，我们为您设计了以下方案...`,
        spaces: this.projectProducts.map(product => ({
          id: product.id,
          name: product.name,
          type: product.type,
          styleDescription: `${this.globalRequirements.stylePreference}风格${product.name}设计`,
          colorPalette: [this.globalRequirements.colorScheme.primary, this.globalRequirements.colorScheme.secondary, this.globalRequirements.colorScheme.accent],
          materials: ['实木', '大理石', '布艺'],
          furnitureRecommendations: this.getFurnitureRecommendations(product.type),
          estimatedCost: this.calculateProductEstimatedCost(product),
          timeline: this.calculateProductTimeline(product)
        })),
        estimatedCost: this.globalRequirements.overallBudget.max || this.calculateTotalEstimatedCost(),
        timeline: this.calculateTotalTimeline(),
        crossSpaceCoordination: this.generateCrossSpaceCoordination()
      };

      this.cdr.markForCheck();

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

  /**
   * 获取家具推荐
   */
  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}个工作日（考虑并行施工）`;
  }

  /**
   * 生成跨空间协调方案
   */
  private generateCrossSpaceCoordination(): any {
    return {
      styleConsistency: {
        description: '确保各空间风格统一协调',
        keyElements: ['色彩搭配', '材质选择', '设计元素']
      },
      functionalFlow: {
        description: '优化空间之间的功能流线',
        considerations: ['动线规划', '采光通风', '噪音控制']
      },
      timelineCoordination: {
        description: '协调各空间施工时间',
        strategy: '并行施工，关键节点协调'
      }
    };
  }

  /**
   * 保存草稿
   */
  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();
    }
  }
}