import { Component, Input, Output, EventEmitter, signal, computed } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

export interface QuotationItem {
  id: string;
  roomType: string;
  amount: number;
  description?: string;
}

@Component({
  selector: 'app-quotation-detail',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './quotation-detail.component.html',
  styleUrls: ['./quotation-detail.component.scss']
})
export class QuotationDetailComponent {
  @Input() quotationItems = signal<QuotationItem[]>([]);
  @Input() decorationType?: string;
  @Input() orderAmount?: number;
  @Output() quotationChange = new EventEmitter<QuotationItem[]>();

  isGenerating = signal(false);
  editingItemId = signal<string | null>(null);
  editingItem: Partial<QuotationItem> = {};

  roomTypeOptions = [
    '客厅', '餐厅', '客餐厅', '主卧', '次卧', '儿童房', 
    '书房', '厨房', '主卫', '客卫', '阳台', '玄关', 
    '走廊', '储物间', '衣帽间', '其他空间'
  ];

  // 计算总金额
  totalAmount = computed(() => {
    return this.quotationItems().reduce((sum, item) => sum + item.amount, 0);
  });

  constructor() {}

  // AI智能报价生成
  async generateAIQuotation() {
    if (this.isGenerating()) return;
    
    this.isGenerating.set(true);
    
    try {
      // 模拟AI生成报价（实际项目中应调用AI服务）
      await this.simulateAIGeneration();
      
      const aiQuotation = this.generateDefaultQuotation();
      this.quotationItems.set(aiQuotation);
      this.emitChange();
    } catch (error) {
      console.error('AI报价生成失败:', error);
    } finally {
      this.isGenerating.set(false);
    }
  }

  private async simulateAIGeneration(): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, 2000));
  }

  private generateDefaultQuotation(): QuotationItem[] {
    const baseAmount = this.orderAmount || 100000;
    const isHomeDecoration = this.decorationType === '家装';
    
    if (isHomeDecoration) {
      return [
        {
          id: this.generateId(),
          roomType: '客餐厅',
          amount: Math.round(baseAmount * 0.35),
          description: '包含客厅和餐厅的整体设计，含家具配置和软装搭配'
        },
        {
          id: this.generateId(),
          roomType: '主卧',
          amount: Math.round(baseAmount * 0.25),
          description: '主卧室设计，包含衣柜、床品和照明设计'
        },
        {
          id: this.generateId(),
          roomType: '次卧',
          amount: Math.round(baseAmount * 0.15),
          description: '次卧室或儿童房设计'
        },
        {
          id: this.generateId(),
          roomType: '厨房',
          amount: Math.round(baseAmount * 0.15),
          description: '厨房功能设计和橱柜配置'
        },
        {
          id: this.generateId(),
          roomType: '卫生间',
          amount: Math.round(baseAmount * 0.1),
          description: '卫生间设计和洁具配置'
        }
      ];
    } else {
      // 工装报价
      return [
        {
          id: this.generateId(),
          roomType: '办公区域',
          amount: Math.round(baseAmount * 0.4),
          description: '办公空间设计，包含工位和公共区域'
        },
        {
          id: this.generateId(),
          roomType: '会议室',
          amount: Math.round(baseAmount * 0.2),
          description: '会议室设计和设备配置'
        },
        {
          id: this.generateId(),
          roomType: '接待区',
          amount: Math.round(baseAmount * 0.2),
          description: '前台接待区域设计'
        },
        {
          id: this.generateId(),
          roomType: '其他区域',
          amount: Math.round(baseAmount * 0.2),
          description: '茶水间、休息区等其他功能区域'
        }
      ];
    }
  }

  // 添加报价项目
  addQuotationItem() {
    const newItem: QuotationItem = {
      id: this.generateId(),
      roomType: '',
      amount: 0,
      description: ''
    };
    
    const currentItems = this.quotationItems();
    this.quotationItems.set([...currentItems, newItem]);
    this.editItem(newItem);
  }

  // 编辑项目
  editItem(item: QuotationItem) {
    this.editingItemId.set(item.id);
    this.editingItem = { ...item };
  }

  // 保存编辑
  saveItem() {
    const editingId = this.editingItemId();
    if (!editingId || !this.editingItem.roomType || !this.editingItem.amount) {
      return;
    }

    const currentItems = this.quotationItems();
    const updatedItems = currentItems.map(item => 
      item.id === editingId 
        ? { ...item, ...this.editingItem } as QuotationItem
        : item
    );
    
    this.quotationItems.set(updatedItems);
    this.cancelEdit();
    this.emitChange();
  }

  // 取消编辑
  cancelEdit() {
    const editingId = this.editingItemId();
    
    // 如果是新添加的空项目，删除它
    if (editingId) {
      const currentItems = this.quotationItems();
      const editingItem = currentItems.find(item => item.id === editingId);
      
      if (editingItem && !editingItem.roomType && !editingItem.amount) {
        this.deleteItem(editingId);
      }
    }
    
    this.editingItemId.set(null);
    this.editingItem = {};
  }

  // 删除项目
  deleteItem(itemId: string) {
    const currentItems = this.quotationItems();
    const filteredItems = currentItems.filter(item => item.id !== itemId);
    this.quotationItems.set(filteredItems);
    
    if (this.editingItemId() === itemId) {
      this.editingItemId.set(null);
      this.editingItem = {};
    }
    
    this.emitChange();
  }

  private emitChange() {
    this.quotationChange.emit(this.quotationItems());
  }

  private generateId(): string {
    return 'quotation_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
  }
}