import { Component, Input, Output, EventEmitter, OnInit, signal } from '@angular/core';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { QuotationDetailsComponent, QuotationData } from '../quotation-details/quotation-details.component';

export interface OrderCreationData {
  orderAmount: number;
  deliveryTime: string;
  quotationData?: QuotationData;
}

// 报价规则接口
export interface PricingRule {
  spaceType: string;
  basePrice: number; // 基础价格（元/人天）
  styleMultiplier: number; // 风格系数
  finalPrice: number; // 最终价格
  description: string; // 服务内容描述
}

// 空间类型配置
export interface SpaceTypeConfig {
  type: string;
  basePrice: number; // 元/人天
  description: string;
}

// 风格等级配置
export interface StyleLevelConfig {
  level: string;
  name: string;
  multiplier: number;
  description: string;
}

@Component({
  selector: 'app-order-creation',
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule, QuotationDetailsComponent],
  templateUrl: './order-creation.component.html',
  styleUrls: ['./order-creation.component.scss']
})
export class OrderCreationComponent implements OnInit {
  @Input() initialData?: OrderCreationData;
  @Output() dataChange = new EventEmitter<OrderCreationData>();
  @Output() validityChange = new EventEmitter<boolean>();

  orderForm: FormGroup;
  quotationData?: QuotationData;
  // 替换为停滞项目筛选的本地状态
  hideStagnantProjects = false;

  // 报价规则配置
  showPricingRulesModal = signal(false);
  showAdjustModal = false; // 添加调整价格模态框状态
  
  // 空间类型配置
  spaceTypeConfig = signal<SpaceTypeConfig[]>([
    { type: '客餐厅', basePrice: 600, description: '客厅餐厅一体化设计' },
    { type: '卧室', basePrice: 400, description: '主卧/次卧设计' },
    { type: '厨房', basePrice: 500, description: '厨房空间设计' },
    { type: '卫生间', basePrice: 350, description: '卫生间设计' },
    { type: '书房', basePrice: 450, description: '书房/工作区设计' },
    { type: '阳台', basePrice: 300, description: '阳台/露台设计' }
  ]);

  // 风格等级配置
  styleLevelConfig = signal<StyleLevelConfig[]>([
    { level: 'standard', name: '标准', multiplier: 1.0, description: '基础设计方案' },
    { level: 'premium', name: '高端', multiplier: 1.5, description: '精装设计方案，4K单张，6K全景' },
    { level: 'luxury', name: '奢华', multiplier: 2.0, description: '顶级设计方案，8K渲染' }
  ]);

  // 当前选择的报价配置
  selectedSpaceType = signal<string>('');
  selectedStyleLevel = signal<string>('');
  
  // 生成的报价清单
  generatedQuotation = signal<PricingRule[]>([]);

  constructor(private fb: FormBuilder) {
    this.orderForm = this.fb.group({
      orderAmount: ['', [
        Validators.required, 
        Validators.min(0.01),
        Validators.pattern(/^\d+(\.\d{1,2})?$/)
      ]],
      deliveryTime: ['', Validators.required]
    });
  }

  ngOnInit() {
    if (this.initialData) {
      this.orderForm.patchValue(this.initialData);
      this.quotationData = this.initialData.quotationData;
    }

    // 监听表单变化
    this.orderForm.valueChanges.subscribe(value => {
      this.emitDataChange();
      this.validityChange.emit(this.isFormValid());
    });

    // 初始状态发送
    this.validityChange.emit(this.isFormValid());
  }

  // 显示报价规则配置
  showPricingRules(): void {
    this.showPricingRulesModal.set(true);
  }

  // 隐藏报价规则配置
  hidePricingRules(): void {
    this.showPricingRulesModal.set(false);
  }

  // 添加空间类型
  addSpaceType(): void {
    const current = this.spaceTypeConfig();
    current.push({ type: '', basePrice: 400, description: '' });
    this.spaceTypeConfig.set([...current]);
  }

  // 删除空间类型
  removeSpaceType(index: number): void {
    const current = this.spaceTypeConfig();
    current.splice(index, 1);
    this.spaceTypeConfig.set([...current]);
  }

  // 添加风格等级
  addStyleLevel(): void {
    const current = this.styleLevelConfig();
    current.push({ level: '', name: '', multiplier: 1.0, description: '' });
    this.styleLevelConfig.set([...current]);
  }

  // 删除风格等级
  removeStyleLevel(index: number): void {
    const current = this.styleLevelConfig();
    current.splice(index, 1);
    this.styleLevelConfig.set([...current]);
  }

  // 保存报价规则配置
  savePricingRules(): void {
    // 这里应该调用服务保存配置到后端
    console.log('保存报价规则配置:', {
      spaceTypes: this.spaceTypeConfig(),
      styleLevels: this.styleLevelConfig()
    });
    this.hidePricingRules();
  }

  // 生成自动报价
  generateAutoQuotation(): void {
    if (!this.selectedSpaceType() || !this.selectedStyleLevel()) {
      alert('请先选择空间类型和风格等级');
      return;
    }

    const spaceConfig = this.spaceTypeConfig().find(s => s.type === this.selectedSpaceType());
    const styleConfig = this.styleLevelConfig().find(s => s.level === this.selectedStyleLevel());

    if (!spaceConfig || !styleConfig) {
      alert('配置信息不完整');
      return;
    }

    const finalPrice = spaceConfig.basePrice * styleConfig.multiplier;
    const rule: PricingRule = {
      spaceType: spaceConfig.type,
      basePrice: spaceConfig.basePrice,
      styleMultiplier: styleConfig.multiplier,
      finalPrice: finalPrice,
      description: `${styleConfig.name}${spaceConfig.type}项目 - ${spaceConfig.description}，${styleConfig.description}`
    };

    this.generatedQuotation.set([rule]);
    
    // 更新订单金额
    this.orderForm.patchValue({
      orderAmount: finalPrice
    });

    // 生成报价数据
    this.quotationData = {
      items: [{
        id: '1',
        category: '设计服务', // 添加category属性
        name: `${styleConfig.name}${spaceConfig.type}设计`,
        quantity: 1,
        unit: '项',
        unitPrice: finalPrice,
        totalPrice: finalPrice,
        description: rule.description
      }],
      totalAmount: finalPrice,
      materialCost: 0,
      laborCost: finalPrice,
      designFee: finalPrice,
      managementFee: 0
    };

    this.emitDataChange();
  }

  // 调整报价
  adjustQuotation(newPrice: number, reason: string): void {
    if (this.generatedQuotation().length === 0) {
      alert('请先生成报价');
      return;
    }

    const currentRule = this.generatedQuotation()[0];
    const adjustedRule: PricingRule = {
      ...currentRule,
      finalPrice: newPrice,
      description: `${currentRule.description} (调整原因: ${reason})`
    };

    this.generatedQuotation.set([adjustedRule]);
    
    // 更新订单金额
    this.orderForm.patchValue({
      orderAmount: newPrice
    });

    // 更新报价数据
    if (this.quotationData) {
      this.quotationData.items[0].unitPrice = newPrice;
      this.quotationData.items[0].totalPrice = newPrice;
      this.quotationData.totalAmount = newPrice;
      this.quotationData.laborCost = newPrice;
      this.quotationData.designFee = newPrice;
    }

    this.emitDataChange();
    
    // 记录调整日志（应该发送到后端）
    console.log('报价调整记录:', {
      originalPrice: currentRule.finalPrice,
      adjustedPrice: newPrice,
      reason: reason,
      timestamp: new Date(),
      spaceType: currentRule.spaceType
    });
  }

  // 获取服务内容说明
  getServiceDescription(spaceType: string, styleLevel: string): string {
    const spaceConfig = this.spaceTypeConfig().find(s => s.type === spaceType);
    const styleConfig = this.styleLevelConfig().find(s => s.level === styleLevel);
    
    if (!spaceConfig || !styleConfig) return '';
    
    const baseServices = ['建模', '渲染', '1次小图修改'];
    const premiumServices = styleLevel === 'premium' ? ['4K单张交付', '6K全景交付'] : [];
    const luxuryServices = styleLevel === 'luxury' ? ['8K渲染', '无限次修改'] : [];
    
    return [...baseServices, ...premiumServices, ...luxuryServices].join('、');
  }

  // 处理报价明细数据变化
  onQuotationDataChange(data: QuotationData) {
    this.quotationData = data;
    this.emitDataChange();
    this.validityChange.emit(this.isFormValid());
  }

  // 发送数据变化事件
  private emitDataChange() {
    const formData = this.orderForm.value;
    const completeData: OrderCreationData = {
      ...formData,
      quotationData: this.quotationData
    };
    this.dataChange.emit(completeData);
  }

  // 检查表单有效性
  private isFormValid(): boolean {
    return this.orderForm.valid && !!this.quotationData && this.quotationData.items.length > 0;
  }

  // 获取表单控件
  get orderAmount() { return this.orderForm.get('orderAmount'); }
  get deliveryTime() { return this.orderForm.get('deliveryTime'); }

  // 获取表单数据
  getFormData(): OrderCreationData {
    return {
      ...this.orderForm.value,
      quotationData: this.quotationData
    };
  }

  // 重置表单
  resetForm() {
    this.orderForm.reset();
    this.quotationData = undefined;
    this.generatedQuotation.set([]);
    this.selectedSpaceType.set('');
    this.selectedStyleLevel.set('');
  }

  // 验证表单
  validateForm(): boolean {
    this.orderForm.markAllAsTouched();
    return this.isFormValid();
  }

  // 切换停滞项目筛选（仅本地UI状态）
  toggleStagnantFilter() {
    this.hideStagnantProjects = !this.hideStagnantProjects;
  }
}