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

// 形体分析结果接口
export interface FormAnalysisResult {
  lineAnalysis: LineAnalysis;
  geometryAnalysis: GeometryAnalysis;
  proportionAnalysis: ProportionAnalysis;
  overallAssessment: OverallFormAssessment;
}

// 线条分析
export interface LineAnalysis {
  dominantLineType: 'straight' | 'curved' | 'mixed';
  lineDirection: {
    horizontal: number; // 0-100
    vertical: number;   // 0-100
    diagonal: number;   // 0-100
  };
  lineWeight: 'thin' | 'medium' | 'thick' | 'varied';
  lineQuality: {
    smoothness: number; // 0-100
    continuity: number; // 0-100
    precision: number;  // 0-100
  };
  suggestions: string[];
}

// 几何形状分析
export interface GeometryAnalysis {
  primaryShapes: Array<{
    shape: 'circle' | 'square' | 'rectangle' | 'triangle' | 'polygon' | 'organic';
    percentage: number;
    characteristics: string[];
  }>;
  complexity: 'simple' | 'moderate' | 'complex';
  symmetry: {
    type: 'bilateral' | 'radial' | 'asymmetric';
    score: number; // 0-100
  };
  balance: {
    visual: number; // 0-100
    compositional: number; // 0-100
  };
}

// 比例分析
export interface ProportionAnalysis {
  goldenRatio: {
    present: boolean;
    score: number; // 0-100
    applications: string[];
  };
  aspectRatio: {
    width: number;
    height: number;
    ratio: string;
  };
  scaleRelationships: Array<{
    element1: string;
    element2: string;
    ratio: number;
    harmony: number; // 0-100
  }>;
  proportionalHarmony: number; // 0-100
}

// 整体形体评估
export interface OverallFormAssessment {
  styleClassification: string[];
  designPrinciples: {
    unity: number;      // 0-100
    balance: number;    // 0-100
    emphasis: number;   // 0-100
    rhythm: number;     // 0-100
  };
  spatialQuality: {
    openness: number;   // 0-100
    flow: number;       // 0-100
    hierarchy: number;  // 0-100
  };
  recommendations: string[];
}

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

  constructor() { }

  /**
   * 分析图片中的形体特征
   * @param imageFile 图片文件
   */
  analyzeImageForm(imageFile: File): Observable<FormAnalysisResult> {
    // 模拟分析过程
    return of(this.simulateFormAnalysis(imageFile));
  }

  /**
   * 分析上传的图片文件形体
   * @param imageUrl 图片URL
   */
  analyzeFormFromUrl(imageUrl: string): Observable<FormAnalysisResult> {
    return of(this.simulateFormAnalysisFromUrl(imageUrl));
  }

  /**
   * 模拟形体分析（实际项目中应该调用AI服务）
   */
  private simulateFormAnalysis(imageFile: File): FormAnalysisResult {
    // 基于文件名或随机生成模拟数据
    const fileName = imageFile.name.toLowerCase();
    
    return {
      lineAnalysis: this.generateLineAnalysis(fileName),
      geometryAnalysis: this.generateGeometryAnalysis(fileName),
      proportionAnalysis: this.generateProportionAnalysis(fileName),
      overallAssessment: this.generateOverallAssessment(fileName)
    };
  }

  private simulateFormAnalysisFromUrl(imageUrl: string): FormAnalysisResult {
    const urlLower = imageUrl.toLowerCase();
    
    return {
      lineAnalysis: this.generateLineAnalysis(urlLower),
      geometryAnalysis: this.generateGeometryAnalysis(urlLower),
      proportionAnalysis: this.generateProportionAnalysis(urlLower),
      overallAssessment: this.generateOverallAssessment(urlLower)
    };
  }

  private generateLineAnalysis(context: string): LineAnalysis {
    // 根据上下文生成不同的线条分析
    const isModern = context.includes('modern') || context.includes('contemporary');
    const isClassical = context.includes('classic') || context.includes('traditional');
    
    if (isModern) {
      return {
        dominantLineType: 'straight',
        lineDirection: { horizontal: 60, vertical: 30, diagonal: 10 },
        lineWeight: 'thin',
        lineQuality: { smoothness: 90, continuity: 85, precision: 95 },
        suggestions: ['保持简洁的线条设计', '强调水平线条的延展感', '注意线条的精确度']
      };
    } else if (isClassical) {
      return {
        dominantLineType: 'curved',
        lineDirection: { horizontal: 40, vertical: 35, diagonal: 25 },
        lineWeight: 'medium',
        lineQuality: { smoothness: 85, continuity: 90, precision: 80 },
        suggestions: ['增强曲线的优雅感', '平衡各方向线条的比例', '注意线条的流畅性']
      };
    } else {
      return {
        dominantLineType: 'mixed',
        lineDirection: { horizontal: 45, vertical: 35, diagonal: 20 },
        lineWeight: 'varied',
        lineQuality: { smoothness: 75, continuity: 80, precision: 85 },
        suggestions: ['协调直线与曲线的关系', '统一线条的视觉重量', '提升整体线条质量']
      };
    }
  }

  private generateGeometryAnalysis(context: string): GeometryAnalysis {
    const isMinimalist = context.includes('minimal') || context.includes('simple');
    const isOrganic = context.includes('organic') || context.includes('natural');
    
    if (isMinimalist) {
      return {
        primaryShapes: [
          { shape: 'rectangle', percentage: 60, characteristics: ['简洁', '规整', '现代'] },
          { shape: 'square', percentage: 25, characteristics: ['稳定', '平衡'] },
          { shape: 'circle', percentage: 15, characteristics: ['柔和', '完整'] }
        ],
        complexity: 'simple',
        symmetry: { type: 'bilateral', score: 90 },
        balance: { visual: 95, compositional: 90 }
      };
    } else if (isOrganic) {
      return {
        primaryShapes: [
          { shape: 'organic', percentage: 70, characteristics: ['自然', '流动', '有机'] },
          { shape: 'circle', percentage: 20, characteristics: ['柔和', '和谐'] },
          { shape: 'polygon', percentage: 10, characteristics: ['变化', '动态'] }
        ],
        complexity: 'moderate',
        symmetry: { type: 'asymmetric', score: 30 },
        balance: { visual: 75, compositional: 80 }
      };
    } else {
      return {
        primaryShapes: [
          { shape: 'rectangle', percentage: 40, characteristics: ['结构化', '功能性'] },
          { shape: 'circle', percentage: 30, characteristics: ['和谐', '完整'] },
          { shape: 'triangle', percentage: 20, characteristics: ['动态', '指向性'] },
          { shape: 'polygon', percentage: 10, characteristics: ['复杂', '装饰性'] }
        ],
        complexity: 'moderate',
        symmetry: { type: 'bilateral', score: 70 },
        balance: { visual: 80, compositional: 85 }
      };
    }
  }

  private generateProportionAnalysis(context: string): ProportionAnalysis {
    const hasGoldenRatio = Math.random() > 0.5;
    
    return {
      goldenRatio: {
        present: hasGoldenRatio,
        score: hasGoldenRatio ? 85 + Math.random() * 15 : 30 + Math.random() * 40,
        applications: hasGoldenRatio ? 
          ['主要构图比例', '元素间距关系', '视觉焦点定位'] : 
          ['可考虑应用黄金比例优化构图']
      },
      aspectRatio: {
        width: 16,
        height: 9,
        ratio: '16:9'
      },
      scaleRelationships: [
        { element1: '主体', element2: '背景', ratio: 1.618, harmony: 85 },
        { element1: '前景', element2: '中景', ratio: 1.414, harmony: 75 },
        { element1: '细节', element2: '整体', ratio: 0.618, harmony: 90 }
      ],
      proportionalHarmony: 75 + Math.random() * 20
    };
  }

  private generateOverallAssessment(context: string): OverallFormAssessment {
    const isContemporary = context.includes('contemporary') || context.includes('modern');
    
    const baseStyles = ['现代简约', '功能主义'];
    if (context.includes('luxury')) baseStyles.push('奢华风格');
    if (context.includes('natural')) baseStyles.push('自然风格');
    if (context.includes('industrial')) baseStyles.push('工业风格');
    
    return {
      styleClassification: baseStyles,
      designPrinciples: {
        unity: 80 + Math.random() * 15,
        balance: 75 + Math.random() * 20,
        emphasis: 70 + Math.random() * 25,
        rhythm: 65 + Math.random() * 30
      },
      spatialQuality: {
        openness: isContemporary ? 85 + Math.random() * 10 : 60 + Math.random() * 25,
        flow: 70 + Math.random() * 25,
        hierarchy: 75 + Math.random() * 20
      },
      recommendations: [
        '保持设计的整体一致性',
        '注意元素间的比例关系',
        '强化视觉层次的表达',
        '优化空间的流动性'
      ]
    };
  }

  /**
   * 获取形体分析建议
   * @param result 分析结果
   */
  getFormRecommendations(result: FormAnalysisResult): string[] {
    const recommendations = [];
    
    // 基于线条分析的建议
    if (result.lineAnalysis.lineQuality.smoothness < 70) {
      recommendations.push('提升线条的流畅度和精确性');
    }
    
    // 基于几何分析的建议
    if (result.geometryAnalysis.balance.visual < 70) {
      recommendations.push('调整元素布局以改善视觉平衡');
    }
    
    // 基于比例分析的建议
    if (result.proportionAnalysis.proportionalHarmony < 70) {
      recommendations.push('优化元素间的比例关系');
    }
    
    // 基于整体评估的建议
    if (result.overallAssessment.designPrinciples.unity < 70) {
      recommendations.push('增强设计的统一性');
    }
    
    return recommendations.length > 0 ? recommendations : ['当前形体设计已达到良好水平'];
  }
}