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

/**
 * 报价编辑器组件
 *
 * 功能:
 * 1. 展示报价明细,支持折叠/展开
 * 2. 编辑工序价格和数量
 * 3. 自动计算小计和总价
 * 4. 支持表格和卡片两种展示模式
 */
@Component({
  selector: 'app-quotation-editor',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './quotation-editor.component.html',
  styleUrls: ['./quotation-editor.component.scss']
})
export class QuotationEditorComponent implements OnChanges {
  @Input() quotation: any = { spaces: [], total: 0 };
  @Input() canEdit: boolean = false;
  @Input() viewMode: 'table' | 'card' = 'card'; // 展示模式

  @Output() quotationChange = new EventEmitter<any>();
  @Output() totalChange = new EventEmitter<number>();

  // 工序类型定义
  processTypes = [
    { key: 'modeling', name: '建模', color: 'primary', icon: 'cube-outline' },
    { key: 'softDecor', name: '软装', color: 'secondary', icon: 'color-palette-outline' },
    { key: 'rendering', name: '渲染', color: 'tertiary', icon: 'image-outline' },
    { key: 'postProcess', name: '后期', color: 'success', icon: 'sparkles-outline' }
  ];

  // 折叠状态
  expandedSpaces: Set<string> = new Set();

  ngOnChanges(changes: SimpleChanges) {
    if (changes['quotation'] && this.quotation?.spaces?.length > 0) {
      // 默认展开第一个空间
      if (this.expandedSpaces.size === 0) {
        this.expandedSpaces.add(this.quotation.spaces[0].name);
      }
    }
  }

  /**
   * 切换空间展开/折叠状态
   */
  toggleSpaceExpand(spaceName: string) {
    if (this.expandedSpaces.has(spaceName)) {
      this.expandedSpaces.delete(spaceName);
    } else {
      this.expandedSpaces.add(spaceName);
    }
  }

  /**
   * 检查空间是否展开
   */
  isSpaceExpanded(spaceName: string): boolean {
    return this.expandedSpaces.has(spaceName);
  }

  /**
   * 展开所有空间
   */
  expandAll() {
    this.quotation.spaces.forEach((space: any) => {
      this.expandedSpaces.add(space.name);
    });
  }

  /**
   * 折叠所有空间
   */
  collapseAll() {
    this.expandedSpaces.clear();
  }

  /**
   * 切换工序启用状态
   */
  toggleProcess(space: any, processKey: string) {
    const process = space.processes[processKey];
    process.enabled = !process.enabled;
    if (!process.enabled) {
      process.price = 0;
      process.quantity = 0;
    }
    this.calculateTotal();
  }

  /**
   * 工序价格或数量变化
   */
  onProcessChange() {
    this.calculateTotal();
  }

  /**
   * 计算报价总额
   */
  calculateTotal() {
    let total = 0;
    for (const space of this.quotation.spaces) {
      for (const processKey of Object.keys(space.processes)) {
        const process = space.processes[processKey];
        if (process.enabled) {
          total += process.price * process.quantity;
        }
      }
    }
    this.quotation.total = total;
    this.quotationChange.emit(this.quotation);
    this.totalChange.emit(total);
  }

  /**
   * 计算空间小计
   */
  calculateSpaceSubtotal(space: any): number {
    let subtotal = 0;
    for (const processKey of Object.keys(space.processes)) {
      const process = space.processes[processKey];
      if (process.enabled) {
        subtotal += process.price * process.quantity;
      }
    }
    return subtotal;
  }

  /**
   * 辅助方法：检查工序是否启用
   */
  isProcessEnabled(space: any, processKey: string): boolean {
    const process = space.processes?.[processKey];
    return process?.enabled || false;
  }

  /**
   * 辅助方法：设置工序价格
   */
  setProcessPrice(space: any, processKey: string, value: any): void {
    const process = space.processes?.[processKey];
    if (process) {
      process.price = value;
    }
  }

  /**
   * 辅助方法：设置工序数量
   */
  setProcessQuantity(space: any, processKey: string, value: any): void {
    const process = space.processes?.[processKey];
    if (process) {
      process.quantity = value;
    }
  }

  /**
   * 辅助方法：获取工序价格
   */
  getProcessPrice(space: any, processKey: string): number {
    const process = space.processes?.[processKey];
    return process?.price || 0;
  }

  /**
   * 辅助方法：获取工序数量
   */
  getProcessQuantity(space: any, processKey: string): number {
    const process = space.processes?.[processKey];
    return process?.quantity || 0;
  }

  /**
   * 辅助方法：获取工序单位
   */
  getProcessUnit(space: any, processKey: string): string {
    const process = space.processes?.[processKey];
    return process?.unit || '';
  }

  /**
   * 辅助方法：计算工序小计
   */
  calculateProcessSubtotal(space: any, processKey: string): number {
    const process = space.processes?.[processKey];
    return (process?.price || 0) * (process?.quantity || 0);
  }
}
