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

export interface AIQuotationParams {
  area: number;
  style: string;
  level: string;
  specialRequirements?: string;
}

export interface AIQuotationItem {
  category: string;
  name: string;
  quantity: number;
  unit: string;
  unitPrice: number;
  description?: string;
}

export interface AIQuotationResult {
  items: AIQuotationItem[];
  totalAmount: number;
  suggestions?: string[];
}

@Injectable({
  providedIn: 'root'
})
export class AIQuotationService {
  
  // 装修风格价格系数
  private styleMultipliers: { [key: string]: number } = {
    '现代简约': 1.0,
    '北欧风格': 1.1,
    '中式风格': 1.3,
    '欧式风格': 1.4,
    '美式风格': 1.2,
    '工业风格': 1.1,
    '地中海风格': 1.2,
    '日式风格': 1.15
  };

  // 装修档次价格系数
  private levelMultipliers: { [key: string]: number } = {
    '经济型': 0.8,
    '舒适型': 1.0,
    '豪华型': 1.5,
    '奢华型': 2.0
  };

  // 基础报价模板
  private baseQuotationTemplate: AIQuotationItem[] = [
    {
      category: '客餐厅',
      name: '墙面乳胶漆',
      quantity: 1,
      unit: '㎡',
      unitPrice: 35,
      description: '包含基层处理、刮腻子、刷底漆面漆'
    },
    {
      category: '客餐厅',
      name: '地面瓷砖铺贴',
      quantity: 1,
      unit: '㎡',
      unitPrice: 80,
      description: '包含瓷砖、水泥沙浆、人工费'
    },
    {
      category: '客餐厅',
      name: '吊顶造型',
      quantity: 1,
      unit: '㎡',
      unitPrice: 120,
      description: '石膏板吊顶，包含龙骨、石膏板、乳胶漆'
    },
    {
      category: '厨房',
      name: '厨房墙地砖',
      quantity: 1,
      unit: '㎡',
      unitPrice: 90,
      description: '防滑地砖、墙面瓷砖铺贴'
    },
    {
      category: '厨房',
      name: '橱柜定制',
      quantity: 1,
      unit: '延米',
      unitPrice: 1200,
      description: '包含地柜、吊柜、台面、五金配件'
    },
    {
      category: '卫生间',
      name: '卫生间防水',
      quantity: 1,
      unit: '㎡',
      unitPrice: 60,
      description: '聚氨酯防水涂料，包工包料'
    },
    {
      category: '卫生间',
      name: '卫浴洁具',
      quantity: 1,
      unit: '套',
      unitPrice: 2500,
      description: '马桶、洗手盆、花洒、龙头等'
    },
    {
      category: '卧室',
      name: '卧室地板',
      quantity: 1,
      unit: '㎡',
      unitPrice: 150,
      description: '复合地板，包含踢脚线安装'
    },
    {
      category: '卧室',
      name: '衣柜定制',
      quantity: 1,
      unit: '㎡',
      unitPrice: 800,
      description: '整体衣柜，包含五金配件'
    },
    {
      category: '水电改造',
      name: '水电改造',
      quantity: 1,
      unit: '项',
      unitPrice: 8000,
      description: '全屋水电线路改造，包含材料人工'
    }
  ];

  constructor() { }

  /**
   * 生成AI智能报价
   * @param params 报价参数
   * @returns 报价结果
   */
  generateQuotation(params: AIQuotationParams): Observable<AIQuotationResult> {
    // 模拟AI处理延迟
    return of(this.calculateQuotation(params)).pipe(
      delay(2000) // 模拟2秒的AI处理时间
    );
  }

  /**
   * 计算报价
   * @param params 报价参数
   * @returns 报价结果
   */
  private calculateQuotation(params: AIQuotationParams): AIQuotationResult {
    const { area, style, level, specialRequirements } = params;
    
    // 获取价格系数
    const styleMultiplier = this.styleMultipliers[style] || 1.0;
    const levelMultiplier = this.levelMultipliers[level] || 1.0;
    
    // 计算各项目数量和价格
    const items: AIQuotationItem[] = this.baseQuotationTemplate.map(template => {
      let quantity = area;
      let unitPrice = template.unitPrice * styleMultiplier * levelMultiplier;
      
      // 根据项目类型调整数量
      switch (template.category) {
        case '客餐厅':
          quantity = Math.round(area * 0.4); // 客餐厅占40%面积
          break;
        case '厨房':
          if (template.name.includes('橱柜')) {
            quantity = Math.round(area * 0.08); // 橱柜按延米计算
          } else {
            quantity = Math.round(area * 0.1); // 厨房占10%面积
          }
          break;
        case '卫生间':
          if (template.name.includes('洁具')) {
            quantity = Math.ceil(area / 50); // 每50㎡一套洁具
          } else {
            quantity = Math.round(area * 0.08); // 卫生间占8%面积
          }
          break;
        case '卧室':
          if (template.name.includes('衣柜')) {
            quantity = Math.round(area * 0.15); // 衣柜按投影面积
          } else {
            quantity = Math.round(area * 0.3); // 卧室占30%面积
          }
          break;
        case '水电改造':
          quantity = 1; // 水电改造按项目计算
          unitPrice = area * 80 * levelMultiplier; // 按面积计算水电改造费用
          break;
      }
      
      return {
        ...template,
        quantity: Math.max(1, quantity),
        unitPrice: Math.round(unitPrice)
      };
    });

    // 根据特殊需求调整报价
    if (specialRequirements) {
      this.adjustForSpecialRequirements(items, specialRequirements);
    }

    // 计算总金额
    const totalAmount = items.reduce((sum, item) => sum + (item.quantity * item.unitPrice), 0);

    // 生成建议
    const suggestions = this.generateSuggestions(params, totalAmount);

    return {
      items,
      totalAmount: Math.round(totalAmount),
      suggestions
    };
  }

  /**
   * 根据特殊需求调整报价
   * @param items 报价项目
   * @param specialRequirements 特殊需求
   */
  private adjustForSpecialRequirements(items: AIQuotationItem[], specialRequirements: string): void {
    const requirements = specialRequirements.toLowerCase();
    
    // 智能家居需求
    if (requirements.includes('智能') || requirements.includes('智能家居')) {
      items.push({
        category: '智能家居',
        name: '智能家居系统',
        quantity: 1,
        unit: '套',
        unitPrice: 15000,
        description: '包含智能开关、智能门锁、智能窗帘等'
      });
    }

    // 中央空调需求
    if (requirements.includes('中央空调') || requirements.includes('空调')) {
      items.push({
        category: '暖通设备',
        name: '中央空调系统',
        quantity: 1,
        unit: '套',
        unitPrice: 25000,
        description: '包含主机、管道、出风口等'
      });
    }

    // 地暖需求
    if (requirements.includes('地暖') || requirements.includes('采暖')) {
      items.push({
        category: '暖通设备',
        name: '地暖系统',
        quantity: 1,
        unit: '套',
        unitPrice: 18000,
        description: '包含地暖管道、分水器、温控器等'
      });
    }

    // 新风系统需求
    if (requirements.includes('新风') || requirements.includes('通风')) {
      items.push({
        category: '暖通设备',
        name: '新风系统',
        quantity: 1,
        unit: '套',
        unitPrice: 12000,
        description: '包含新风主机、管道、出风口等'
      });
    }

    // 定制家具需求
    if (requirements.includes('定制') || requirements.includes('家具')) {
      items.push({
        category: '定制家具',
        name: '全屋定制家具',
        quantity: 1,
        unit: '套',
        unitPrice: 30000,
        description: '包含鞋柜、电视柜、书柜等定制家具'
      });
    }
  }

  /**
   * 生成装修建议
   * @param params 报价参数
   * @param totalAmount 总金额
   * @returns 建议列表
   */
  private generateSuggestions(params: AIQuotationParams, totalAmount: number): string[] {
    const suggestions: string[] = [];
    const { area, style, level } = params;
    
    // 预算建议
    const budgetPerSqm = totalAmount / area;
    if (budgetPerSqm > 2000) {
      suggestions.push('当前预算较高，建议优化材料选择以控制成本');
    } else if (budgetPerSqm < 800) {
      suggestions.push('当前预算偏低，建议适当提升材料档次以保证质量');
    }

    // 风格建议
    if (style === '现代简约') {
      suggestions.push('现代简约风格注重功能性，建议选择简洁大方的材料和色彩');
    } else if (style === '中式风格') {
      suggestions.push('中式风格建议选用实木材料，注重对称和层次感');
    } else if (style === '北欧风格') {
      suggestions.push('北欧风格建议使用浅色系，注重自然光线和简约线条');
    }

    // 档次建议
    if (level === '经济型') {
      suggestions.push('经济型装修建议重点投入在基础工程，后期可逐步升级软装');
    } else if (level === '豪华型' || level === '奢华型') {
      suggestions.push('高端装修建议选择知名品牌材料，注重细节工艺和环保性能');
    }

    // 面积建议
    if (area < 60) {
      suggestions.push('小户型建议采用开放式设计，合理利用每一寸空间');
    } else if (area > 150) {
      suggestions.push('大户型建议做好功能分区，可考虑增加储物空间和休闲区域');
    }

    return suggestions;
  }

  /**
   * 获取装修风格列表
   * @returns 风格列表
   */
  getStyleOptions(): string[] {
    return Object.keys(this.styleMultipliers);
  }

  /**
   * 获取装修档次列表
   * @returns 档次列表
   */
  getLevelOptions(): string[] {
    return Object.keys(this.levelMultipliers);
  }
}