import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';

// 质感分析结果接口
export interface TextureAnalysisResult {
  surfaceProperties: SurfaceProperties;
  tactilePredict: TactilePredict;
  materialClassification: MaterialClassification;
  textureQuality: TextureQuality;
  recommendations: string[];
}

// 表面属性
export interface SurfaceProperties {
  roughness: {
    level: 'very-smooth' | 'smooth' | 'moderate' | 'rough' | 'very-rough';
    value: number; // 0-100
    description: string;
  };
  glossiness: {
    level: 'matte' | 'satin' | 'semi-gloss' | 'gloss' | 'high-gloss';
    value: number; // 0-100
    reflectivity: number; // 0-100
  };
  transparency: {
    level: 'opaque' | 'translucent' | 'semi-transparent' | 'transparent';
    value: number; // 0-100
  };
  porosity: {
    level: 'non-porous' | 'low-porous' | 'moderate-porous' | 'high-porous';
    value: number; // 0-100
  };
}

// 触感预测
export interface TactilePredict {
  temperature: {
    perceived: 'cold' | 'cool' | 'neutral' | 'warm' | 'hot';
    thermalConductivity: number; // 0-100
  };
  hardness: {
    level: 'very-soft' | 'soft' | 'medium' | 'hard' | 'very-hard';
    value: number; // 0-100
  };
  flexibility: {
    level: 'rigid' | 'semi-rigid' | 'flexible' | 'very-flexible';
    value: number; // 0-100
  };
  weight: {
    perceived: 'very-light' | 'light' | 'medium' | 'heavy' | 'very-heavy';
    density: number; // 0-100
  };
  comfort: {
    tactileComfort: number; // 0-100
    ergonomicSuitability: number; // 0-100
  };
}

// 材质分类
export interface MaterialClassification {
  primaryMaterial: {
    category: 'wood' | 'metal' | 'fabric' | 'leather' | 'plastic' | 'glass' | 'ceramic' | 'stone' | 'composite';
    confidence: number; // 0-100
    subcategory?: string;
  };
  secondaryMaterials: Array<{
    category: string;
    percentage: number;
    confidence: number;
  }>;
  materialProperties: {
    durability: number; // 0-100
    maintenance: 'low' | 'medium' | 'high';
    sustainability: number; // 0-100
    costLevel: 'budget' | 'mid-range' | 'premium' | 'luxury';
  };
}

// 质感质量评估
export interface TextureQuality {
  overallQuality: number; // 0-100
  consistency: number; // 0-100
  authenticity: number; // 0-100
  visualAppeal: number; // 0-100
  functionalSuitability: number; // 0-100
  ageingCharacteristics: {
    wearResistance: number; // 0-100
    patinaPotential: number; // 0-100
    maintenanceNeeds: string[];
  };
}

@Injectable({
  providedIn: 'root'
})
export class TextureAnalysisService {

  constructor() { }

  /**
   * 分析图片中的质感特征
   * @param imageFile 图片文件
   */
  analyzeImageTexture(imageFile: File): Observable<TextureAnalysisResult> {
    return of(this.simulateTextureAnalysis(imageFile));
  }

  /**
   * 分析URL图片的质感
   * @param imageUrl 图片URL
   */
  analyzeTextureFromUrl(imageUrl: string): Observable<TextureAnalysisResult> {
    return of(this.simulateTextureAnalysisFromUrl(imageUrl));
  }

  /**
   * 模拟质感分析
   */
  private simulateTextureAnalysis(imageFile: File): TextureAnalysisResult {
    const fileName = imageFile.name.toLowerCase();
    return this.generateTextureAnalysis(fileName);
  }

  private simulateTextureAnalysisFromUrl(imageUrl: string): TextureAnalysisResult {
    const urlLower = imageUrl.toLowerCase();
    return this.generateTextureAnalysis(urlLower);
  }

  private generateTextureAnalysis(context: string): TextureAnalysisResult {
    // 根据上下文推断材质类型
    const materialType = this.inferMaterialType(context);
    
    return {
      surfaceProperties: this.generateSurfaceProperties(materialType, context),
      tactilePredict: this.generateTactilePredict(materialType, context),
      materialClassification: this.generateMaterialClassification(materialType, context),
      textureQuality: this.generateTextureQuality(materialType, context),
      recommendations: this.generateTextureRecommendations(materialType, context)
    };
  }

  private inferMaterialType(context: string): string {
    if (context.includes('wood') || context.includes('timber')) return 'wood';
    if (context.includes('metal') || context.includes('steel') || context.includes('aluminum')) return 'metal';
    if (context.includes('fabric') || context.includes('textile') || context.includes('cloth')) return 'fabric';
    if (context.includes('leather')) return 'leather';
    if (context.includes('glass')) return 'glass';
    if (context.includes('ceramic') || context.includes('porcelain')) return 'ceramic';
    if (context.includes('stone') || context.includes('marble') || context.includes('granite')) return 'stone';
    if (context.includes('plastic') || context.includes('polymer')) return 'plastic';
    return 'composite'; // 默认复合材料
  }

  private generateSurfaceProperties(materialType: string, context: string): SurfaceProperties {
    const baseProperties = this.getMaterialBaseProperties(materialType);
    
    // 根据上下文调整属性
    const isPolished = context.includes('polished') || context.includes('glossy');
    const isRough = context.includes('rough') || context.includes('textured');
    
    // 确定最终的粗糙度级别
    const finalRoughnessLevel = isRough ? 'rough' : isPolished ? 'smooth' : baseProperties.roughness.level;
    
    return {
      roughness: {
        level: finalRoughnessLevel,
        value: isRough ? 75 : isPolished ? 15 : baseProperties.roughness.value,
        description: this.getRoughnessDescription(finalRoughnessLevel)
      },
      glossiness: {
        level: isPolished ? 'high-gloss' : baseProperties.glossiness.level,
        value: isPolished ? 90 : baseProperties.glossiness.value,
        reflectivity: isPolished ? 85 : baseProperties.glossiness.reflectivity
      },
      transparency: baseProperties.transparency,
      porosity: baseProperties.porosity
    };
  }

  private getMaterialBaseProperties(materialType: string): SurfaceProperties {
    const properties: { [key: string]: SurfaceProperties } = {
      wood: {
        roughness: { level: 'moderate', value: 45, description: '天然木纹质感' },
        glossiness: { level: 'satin', value: 40, reflectivity: 35 },
        transparency: { level: 'opaque', value: 5 },
        porosity: { level: 'moderate-porous', value: 60 }
      },
      metal: {
        roughness: { level: 'smooth', value: 20, description: '金属光滑表面' },
        glossiness: { level: 'gloss', value: 80, reflectivity: 85 },
        transparency: { level: 'opaque', value: 0 },
        porosity: { level: 'non-porous', value: 5 }
      },
      fabric: {
        roughness: { level: 'moderate', value: 55, description: '织物纤维质感' },
        glossiness: { level: 'matte', value: 15, reflectivity: 10 },
        transparency: { level: 'translucent', value: 30 },
        porosity: { level: 'high-porous', value: 85 }
      },
      leather: {
        roughness: { level: 'moderate', value: 50, description: '皮革天然纹理' },
        glossiness: { level: 'semi-gloss', value: 60, reflectivity: 45 },
        transparency: { level: 'opaque', value: 0 },
        porosity: { level: 'low-porous', value: 25 }
      },
      glass: {
        roughness: { level: 'very-smooth', value: 5, description: '玻璃光滑表面' },
        glossiness: { level: 'high-gloss', value: 95, reflectivity: 90 },
        transparency: { level: 'transparent', value: 90 },
        porosity: { level: 'non-porous', value: 0 }
      },
      ceramic: {
        roughness: { level: 'smooth', value: 25, description: '陶瓷光滑质感' },
        glossiness: { level: 'gloss', value: 75, reflectivity: 70 },
        transparency: { level: 'opaque', value: 0 },
        porosity: { level: 'low-porous', value: 15 }
      },
      stone: {
        roughness: { level: 'rough', value: 70, description: '石材天然质感' },
        glossiness: { level: 'matte', value: 20, reflectivity: 15 },
        transparency: { level: 'opaque', value: 0 },
        porosity: { level: 'moderate-porous', value: 45 }
      },
      plastic: {
        roughness: { level: 'smooth', value: 30, description: '塑料表面质感' },
        glossiness: { level: 'semi-gloss', value: 65, reflectivity: 55 },
        transparency: { level: 'translucent', value: 40 },
        porosity: { level: 'non-porous', value: 5 }
      },
      composite: {
        roughness: { level: 'moderate', value: 40, description: '复合材料质感' },
        glossiness: { level: 'satin', value: 50, reflectivity: 40 },
        transparency: { level: 'opaque', value: 10 },
        porosity: { level: 'moderate-porous', value: 35 }
      }
    };

    return properties[materialType] || properties['composite'];
  }

  private generateTactilePredict(materialType: string, context: string): TactilePredict {
    const baseTactile = this.getMaterialTactileProperties(materialType);
    
    // 根据上下文调整
    const isLuxury = context.includes('luxury') || context.includes('premium');
    
    return {
      temperature: baseTactile.temperature,
      hardness: baseTactile.hardness,
      flexibility: baseTactile.flexibility,
      weight: baseTactile.weight,
      comfort: {
        tactileComfort: isLuxury ? Math.min(100, baseTactile.comfort.tactileComfort + 15) : baseTactile.comfort.tactileComfort,
        ergonomicSuitability: baseTactile.comfort.ergonomicSuitability
      }
    };
  }

  private getMaterialTactileProperties(materialType: string): TactilePredict {
    const properties: { [key: string]: TactilePredict } = {
      wood: {
        temperature: { perceived: 'neutral', thermalConductivity: 30 },
        hardness: { level: 'medium', value: 60 },
        flexibility: { level: 'semi-rigid', value: 25 },
        weight: { perceived: 'medium', density: 50 },
        comfort: { tactileComfort: 80, ergonomicSuitability: 85 }
      },
      metal: {
        temperature: { perceived: 'cold', thermalConductivity: 90 },
        hardness: { level: 'very-hard', value: 95 },
        flexibility: { level: 'rigid', value: 5 },
        weight: { perceived: 'heavy', density: 85 },
        comfort: { tactileComfort: 45, ergonomicSuitability: 60 }
      },
      fabric: {
        temperature: { perceived: 'warm', thermalConductivity: 15 },
        hardness: { level: 'soft', value: 20 },
        flexibility: { level: 'very-flexible', value: 90 },
        weight: { perceived: 'light', density: 20 },
        comfort: { tactileComfort: 95, ergonomicSuitability: 90 }
      },
      leather: {
        temperature: { perceived: 'neutral', thermalConductivity: 35 },
        hardness: { level: 'medium', value: 55 },
        flexibility: { level: 'flexible', value: 70 },
        weight: { perceived: 'medium', density: 45 },
        comfort: { tactileComfort: 85, ergonomicSuitability: 80 }
      }
    };

    return properties[materialType] || properties['wood'];
  }

  private generateMaterialClassification(materialType: string, context: string): MaterialClassification {
    const isLuxury = context.includes('luxury') || context.includes('premium');
    const isEco = context.includes('eco') || context.includes('sustainable');
    
    return {
      primaryMaterial: {
        category: materialType as any,
        confidence: 85 + Math.random() * 10,
        subcategory: this.getSubcategory(materialType, context)
      },
      secondaryMaterials: this.getSecondaryMaterials(materialType),
      materialProperties: {
        durability: this.getDurability(materialType),
        maintenance: this.getMaintenanceLevel(materialType),
        sustainability: isEco ? 85 + Math.random() * 10 : this.getSustainability(materialType),
        costLevel: isLuxury ? 'luxury' : this.getCostLevel(materialType)
      }
    };
  }

  private generateTextureQuality(materialType: string, context: string): TextureQuality {
    const isHighEnd = context.includes('luxury') || context.includes('premium') || context.includes('high-end');
    const baseQuality = isHighEnd ? 85 : 70;
    
    return {
      overallQuality: baseQuality + Math.random() * 10,
      consistency: baseQuality + Math.random() * 15,
      authenticity: this.getAuthenticity(materialType, context),
      visualAppeal: baseQuality + Math.random() * 15,
      functionalSuitability: this.getFunctionalSuitability(materialType),
      ageingCharacteristics: {
        wearResistance: this.getWearResistance(materialType),
        patinaPotential: this.getPatinaPotential(materialType),
        maintenanceNeeds: this.getMaintenanceNeeds(materialType)
      }
    };
  }

  private generateTextureRecommendations(materialType: string, context: string): string[] {
    const recommendations = [];
    
    switch (materialType) {
      case 'wood':
        recommendations.push('定期保养以维持木材质感');
        recommendations.push('注意防潮和防虫处理');
        break;
      case 'metal':
        recommendations.push('定期清洁以保持光泽');
        recommendations.push('注意防锈处理');
        break;
      case 'fabric':
        recommendations.push('选择合适的清洁方式');
        recommendations.push('注意防污和防褪色');
        break;
      case 'leather':
        recommendations.push('定期使用皮革保养剂');
        recommendations.push('避免长期暴露在阳光下');
        break;
    }
    
    if (context.includes('outdoor')) {
      recommendations.push('选择耐候性强的材质');
    }
    
    return recommendations;
  }

  // 辅助方法
  private getRoughnessDescription(level: string): string {
    const descriptions: { [key: string]: string } = {
      'very-smooth': '极其光滑的表面',
      'smooth': '光滑的表面',
      'moderate': '中等粗糙度',
      'rough': '粗糙的表面',
      'very-rough': '非常粗糙的表面'
    };
    return descriptions[level] || '表面质感';
  }

  private getSubcategory(materialType: string, context: string): string {
    // 根据材质类型和上下文返回子类别
    const subcategories: { [key: string]: string[] } = {
      wood: ['硬木', '软木', '复合木材', '竹材'],
      metal: ['不锈钢', '铝合金', '铜', '铁'],
      fabric: ['棉质', '丝质', '羊毛', '合成纤维'],
      leather: ['真皮', '人造革', '绒面革', '漆皮']
    };
    
    const options = subcategories[materialType];
    return options ? options[Math.floor(Math.random() * options.length)] : '标准类型';
  }

  private getSecondaryMaterials(materialType: string): Array<{category: string; percentage: number; confidence: number}> {
    // 返回次要材质
    return [
      { category: '涂层', percentage: 15, confidence: 70 },
      { category: '粘合剂', percentage: 5, confidence: 60 }
    ];
  }

  private getDurability(materialType: string): number {
    const durability: { [key: string]: number } = {
      wood: 75, metal: 90, fabric: 60, leather: 80, glass: 85, ceramic: 80, stone: 95, plastic: 65
    };
    return durability[materialType] || 70;
  }

  private getMaintenanceLevel(materialType: string): 'low' | 'medium' | 'high' {
    const maintenance: { [key: string]: 'low' | 'medium' | 'high' } = {
      wood: 'medium', metal: 'low', fabric: 'high', leather: 'medium', glass: 'low', ceramic: 'low', stone: 'low', plastic: 'low'
    };
    return maintenance[materialType] || 'medium';
  }

  private getSustainability(materialType: string): number {
    const sustainability: { [key: string]: number } = {
      wood: 85, metal: 70, fabric: 60, leather: 50, glass: 80, ceramic: 75, stone: 90, plastic: 30
    };
    return sustainability[materialType] || 60;
  }

  private getCostLevel(materialType: string): 'budget' | 'mid-range' | 'premium' | 'luxury' {
    const cost: { [key: string]: 'budget' | 'mid-range' | 'premium' | 'luxury' } = {
      wood: 'mid-range', metal: 'mid-range', fabric: 'budget', leather: 'premium', glass: 'mid-range', ceramic: 'mid-range', stone: 'premium', plastic: 'budget'
    };
    return cost[materialType] || 'mid-range';
  }

  private getAuthenticity(materialType: string, context: string): number {
    const base = 80;
    const isNatural = context.includes('natural') || context.includes('authentic');
    return isNatural ? base + 15 : base;
  }

  private getFunctionalSuitability(materialType: string): number {
    const suitability: { [key: string]: number } = {
      wood: 85, metal: 80, fabric: 75, leather: 80, glass: 70, ceramic: 75, stone: 85, plastic: 70
    };
    return suitability[materialType] || 75;
  }

  private getWearResistance(materialType: string): number {
    const resistance: { [key: string]: number } = {
      wood: 70, metal: 95, fabric: 50, leather: 75, glass: 60, ceramic: 85, stone: 90, plastic: 65
    };
    return resistance[materialType] || 70;
  }

  private getPatinaPotential(materialType: string): number {
    const patina: { [key: string]: number } = {
      wood: 85, metal: 70, fabric: 30, leather: 90, glass: 10, ceramic: 20, stone: 60, plastic: 15
    };
    return patina[materialType] || 40;
  }

  private getMaintenanceNeeds(materialType: string): string[] {
    const needs: { [key: string]: string[] } = {
      wood: ['定期打蜡', '防潮处理', '避免划伤'],
      metal: ['防锈处理', '定期清洁', '避免腐蚀'],
      fabric: ['定期清洗', '防污处理', '避免褪色'],
      leather: ['皮革保养', '防干裂', '避免暴晒']
    };
    return needs[materialType] || ['常规保养'];
  }
}