import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';

// 方案版本接口
interface ProposalVersion {
  id: string;
  name: string;
  description: string;
  version: string;
  mainColor: { rgb: string; colorTemp: string };
  materialRatio: { material: string; percentage: number }[];
  budget: number;
  workDays: number;
  preview?: string;
  isSelected?: boolean;
}

// 量化方案清单接口
interface QuantifiedProposal {
  spaceModules: SpaceModule[];
  colorAndTexture: ColorTextureModule;
  structuralAdaptation: StructuralModule;
  feasibilityVerification: FeasibilityModule;
}

// 空间功能模块接口
interface SpaceModule {
  id: string;
  name: string;
  furniture: FurnitureItem[];
  requirements: string;
  verified: boolean;
}

// 家具项接口
interface FurnitureItem {
  name: string;
  size: string;
  material: string;
  color: string;
  features: string[];
  price?: number;
}

// 色彩质感模块接口
interface ColorTextureModule {
  mainColor: { rgb: string; colorTemp: string };
  materialRatio: { material: string; percentage: number }[];
  colorSamples: ColorSample[];
  verified: boolean;
}

// 色彩样本接口
interface ColorSample {
  name: string;
  rgb: string;
  reference: string;
  actual: string;
  difference: number;
}

// 结构适配模块接口
interface StructuralModule {
  constraints: StructuralConstraint[];
  adaptations: StructuralAdaptation[];
  cadOverlay?: string;
  verified: boolean;
}

// 结构约束接口
interface StructuralConstraint {
  type: 'load-bearing' | 'window' | 'door' | 'pipe';
  position: string;
  size: string;
  changeable: boolean;
}

// 结构适配接口
interface StructuralAdaptation {
  area: string;
  solution: string;
  flowWidth: string;
  compliance: boolean;
}

// 可行性模块接口
interface FeasibilityModule {
  structural: { status: 'verified' | 'warning' | 'error'; message: string };
  cost: { budget: number; timeline: string; risks: string[] };
  timeline: { totalDays: number; phases: TimelinePhase[] };
  verified: boolean;
}

// 时间线阶段接口
interface TimelinePhase {
  name: string;
  days: number;
  dependencies: string[];
}

// 协作批注接口
interface CollaborationAnnotation {
  id: string;
  x: number;
  y: number;
  author: string;
  role: 'client' | 'designer' | 'manager';
  type: 'question' | 'suggestion' | 'confirmation';
  content: string;
  timestamp: Date;
  replies: AnnotationReply[];
  status: 'open' | 'resolved';
  position?: { x: number; y: number; element?: string };
  resolvedAt?: Date;
  resolvedBy?: string;
}

// 批注回复接口
interface AnnotationReply {
  id: string;
  author: string;
  role: 'client' | 'designer' | 'manager';
  content: string;
  timestamp: Date;
  mentions?: string[];
}

// 确认步骤接口
interface ConfirmationStep {
  id: string;
  name: string;
  description: string;
  status: 'pending' | 'confirmed' | 'rejected';
  required: boolean;
  timestamp?: Date;
  confirmedAt?: Date;
  confirmedBy?: string;
  rejectedAt?: Date;
  rejectedBy?: string;
  rejectionReason?: string;
}

// 批注数据模型接口
interface Annotation {
  id: string;
  x?: number;
  y?: number;
  type: 'question' | 'suggestion' | 'confirmation';
  content: string;
  author: string;
  role: 'client' | 'designer' | 'manager';
  timestamp: Date;
  status: 'open' | 'resolved';
  position?: { x: number; y: number; element?: string };
  mentions?: string[];
  replies: AnnotationReply[];
  resolvedAt?: Date;
  resolvedBy?: string;
}

// 用户接口
interface User {
  id: string;
  name: string;
  role: 'client' | 'designer' | 'manager';
  avatar?: string;
}

@Component({
  selector: 'app-proposal-confirm-card',
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule],
  templateUrl: './proposal-confirm-card.html',
  styleUrls: ['./proposal-confirm-card.scss']
})
export class ProposalConfirmCardComponent implements OnInit {
  @Input() projectId?: string;
  @Input() proposal?: any; // 添加proposal输入属性
  @Output() proposalConfirmed = new EventEmitter<any>();
  @Output() progressUpdated = new EventEmitter<number>();
  @Output() versionSelected = new EventEmitter<ProposalVersion>();
  @Output() annotationAdded = new EventEmitter<CollaborationAnnotation>();
  @Output() stepConfirmed = new EventEmitter<ConfirmationStep>();
  @Output() finalConfirmed = new EventEmitter<any>();
  @Output() allConfirmed = new EventEmitter<any>();
  @Output() confirmationHistoryUpdated = new EventEmitter<any>();
  @Output() confirmationReportExported = new EventEmitter<any>();

  // 表单
  annotationForm!: FormGroup;
  adjustmentForm!: FormGroup;

  // 数据
  proposalVersions: ProposalVersion[] = [];
  selectedVersion?: ProposalVersion;
  quantifiedProposal?: QuantifiedProposal;
  annotations: Annotation[] = [];
  confirmationSteps: ConfirmationStep[] = [];
  
  // 状态管理
  activeTab: 'overview' | 'versions' | 'details' | 'collaboration' | 'confirmation' = 'overview';
  showVersionComparison = false;
  comparisonVersions: any = null;
  versionDifferences: { [key: string]: { field: string; valueA: any; valueB: any; difference: number; type: string } } | null = null;
  isAdjusting = false;
  show3DPreview = false;
  showCADOverlay = false;
  
  // 确认相关状态
  overallProgress = 0;
  allStepsConfirmed = false;
  allStepsConfirmedAt?: Date;
  isFinalConfirmed = false;
  finalConfirmedAt?: Date;
  confirmationHistory: any[] = [];
  
  // 历史版本
  versionHistory: VersionHistoryItem[] = [];
  showVersionHistory = false;
  
  // 方案调整相关
  adjustmentHistory: ProposalAdjustment[] = [];
  canUndo = false;
  canRedo = false;
  undoStack: VersionHistoryItem[] = [];
  redoStack: VersionHistoryItem[] = [];
  
  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.initializeForms();
    this.initializeProposalData();
    this.initializeConfirmationSteps();
  }

  private initializeForms() {
    // 初始化批注表单
    this.annotationForm = this.fb.group({
      type: ['question', Validators.required],
      content: ['', [Validators.required, Validators.minLength(1)]]
    });

    // 初始化方案调整表单
    this.adjustmentForm = this.fb.group({
      element: ['furniture', Validators.required],
      parameter: ['', Validators.required],
      newValue: ['', Validators.required],
      reason: ['', [Validators.required, Validators.minLength(5)]]
    });

    // 初始化提及用户列表
    this.mentionUsers = [
      { id: '1', name: '张设计师', role: 'designer' },
      { id: '2', name: '李经理', role: 'manager' },
      { id: '3', name: '王客户', role: 'client' }
    ];
  }

  private initializeProposalData() {
     // 初始化方案版本数据
     this.proposalVersions = [
       {
         id: 'version-a',
         name: '版本A（暖木色主导）',
         description: '以实木材质为主，营造温馨家庭氛围',
         version: '1.0',
         mainColor: { rgb: '255,230,180', colorTemp: '2800K' },
         materialRatio: [
           { material: '实木', percentage: 40 },
           { material: '布艺', percentage: 35 },
           { material: '金属', percentage: 25 }
         ],
         budget: 18000,
         workDays: 25,
         isSelected: true
       },
       {
         id: 'version-b',
         name: '版本B（浅米色主导）',
         description: '以布艺材质为主，打造舒适休闲空间',
         version: '1.1',
         mainColor: { rgb: '240,235,220', colorTemp: '3200K' },
         materialRatio: [
           { material: '布艺', percentage: 60 },
           { material: '实木', percentage: 25 },
           { material: '金属', percentage: 15 }
         ],
         budget: 16000,
         workDays: 20
       }
     ];

    this.selectedVersion = this.proposalVersions[0];
    this.generateQuantifiedProposal();
  }

  private initializeConfirmationSteps() {
    this.confirmationSteps = [
      {
        id: 'space-modules',
        name: '空间功能模块',
        description: '确认各空间的功能布局和家具配置',
        status: 'pending',
        required: true
      },
      {
        id: 'color-texture',
        name: '色彩与质感',
        description: '确认整体色调、材质比例和色彩样本',
        status: 'pending',
        required: true
      },
      {
        id: 'structural-adaptation',
        name: '结构适配',
        description: '确认方案与现有结构的适配性',
        status: 'pending',
        required: true
      },
      {
        id: 'budget-timeline',
        name: '预算与工期',
        description: '确认项目预算和时间安排',
        status: 'pending',
        required: true
      }
    ];
  }

  private generateQuantifiedProposal() {
    if (!this.selectedVersion) return;

    this.quantifiedProposal = {
      spaceModules: [
        {
          id: 'living-room',
          name: '客厅亲子互动区',
          furniture: [
            {
              name: 'L型布艺沙发',
              size: '2.8m×1.8m',
              material: '棉麻',
              color: 'RGB 255,230,180',
              features: ['防污处理', '圆角设计', '可拆洗'],
              price: 4500
            },
            {
              name: '圆形实木茶几',
              size: '直径80cm',
              material: '橡木',
              color: '原木色',
              features: ['圆角3cm', '承重≥50kg', '环保漆面'],
              price: 1200
            }
          ],
          requirements: '符合亲子家庭（孩子3-6岁）的安全+温馨需求',
          verified: true
        }
      ],
      colorAndTexture: {
        mainColor: this.selectedVersion.mainColor,
        materialRatio: this.selectedVersion.materialRatio,
        colorSamples: [
          {
            name: '主色调',
            rgb: '255,230,180',
            reference: '参考色',
            actual: '实际方案色',
            difference: 3
          }
        ],
        verified: true
      },
      structuralAdaptation: {
        constraints: [
          {
            type: 'load-bearing',
            position: '客厅东侧距墙1.2m处',
            size: '40cm×40cm',
            changeable: false
          }
        ],
        adaptations: [
          {
            area: '客厅',
            solution: '方案避开承重柱，保持人流动线',
            flowWidth: '1.1m',
            compliance: true
          }
        ],
        verified: true
      },
      feasibilityVerification: {
        structural: {
          status: 'verified',
          message: '所有家具尺寸均适配空间，无遮挡问题'
        },
        cost: {
          budget: this.selectedVersion.budget,
          timeline: '采购周期7-10天',
          risks: ['实木茶几需提前15天下单']
        },
        timeline: {
          totalDays: this.selectedVersion.workDays,
          phases: [
            { name: '材料采购', days: 10, dependencies: [] },
            { name: '施工安装', days: 12, dependencies: ['材料采购'] },
            { name: '验收整理', days: 3, dependencies: ['施工安装'] }
          ]
        },
        verified: true
      }
    };
  }

  // 版本选择和对比
  selectVersion(version: ProposalVersion) {
    this.selectedVersion = version;
    this.proposalVersions.forEach(v => v.isSelected = v.id === version.id);
    this.generateQuantifiedProposal();
    this.versionSelected.emit(version);
  }

  toggleVersionComparison() {
    this.showVersionComparison = !this.showVersionComparison;
    if (this.showVersionComparison && this.proposalVersions.length >= 2) {
      this.compareVersions(this.proposalVersions[0].id, this.proposalVersions[1].id);
    }
  }

  // 协作批注功能
  addAnnotation(event?: Event): void {
    if (this.annotationForm.valid) {
      const formValue = this.annotationForm.value;
      const content = formValue.content;
      
      // 检测@提及
      const mentions = this.extractMentions(content);
      
      const annotation: Annotation = {
        id: this.generateId(),
        type: formValue.type,
        content: content,
        author: '当前用户',
        role: 'client',
        timestamp: new Date(),
        status: 'open',
        mentions: mentions,
        replies: [],
        x: 0,
        y: 0
      };
  
      // 如果是点击事件，记录位置
      if (event && event.target) {
        const rect = (event.target as HTMLElement).getBoundingClientRect();
        annotation.x = rect.left;
        annotation.y = rect.top;
        annotation.position = {
          x: rect.left,
          y: rect.top,
          element: (event.target as HTMLElement).tagName
        };
      }
  
      this.annotations.unshift(annotation);
      this.annotationForm.reset({ type: 'question', content: '' });
  
      // 发送提及通知
      if (mentions.length > 0) {
        this.sendMentionNotifications(mentions, annotation);
      }
    }
  }

  replyToAnnotation(annotationId: string, content: string, inputElement?: HTMLInputElement): void {
    const annotation = this.annotations.find(a => a.id === annotationId);
    if (annotation && content.trim()) {
      const mentions = this.extractMentions(content);
  
      const reply: AnnotationReply = {
        id: this.generateId(),
        author: '当前用户',
        role: 'designer',
        content: content.trim(),
        timestamp: new Date(),
        mentions: mentions
      };
  
      annotation.replies.push(reply);
      this.sendMentionNotifications(mentions, annotation, reply);
      
      // 清空输入框
      if (inputElement) {
        inputElement.value = '';
      }
    }
  }

  resolveAnnotation(annotationId: string): void {
    const annotation = this.annotations.find(a => a.id === annotationId);
    if (annotation) {
      annotation.status = 'resolved';
      annotation.resolvedAt = new Date();
      annotation.resolvedBy = '当前用户';
    }
  }

  // 方案调整功能
  adjustProposal(): void {
    if (!this.adjustmentForm.valid) return;

    const formValue = this.adjustmentForm.value;
    const adjustment: ProposalAdjustment = {
      id: this.generateId(),
      element: formValue.element,
      parameter: formValue.parameter,
      oldValue: this.getCurrentParameterValue(formValue.element, formValue.parameter),
      newValue: formValue.newValue,
      reason: formValue.reason,
      timestamp: new Date(),
      operator: '当前用户'
    };

    // 保存当前状态到历史
    this.saveVersionHistory(adjustment);
    
    // 应用调整
    this.applyAdjustment(adjustment);
    
    // 记录调整历史
    this.adjustmentHistory.push(adjustment);
    
    // 更新撤销重做状态
    this.updateUndoRedoState();
    
    this.adjustmentForm.reset();
    this.isAdjusting = false;
  }

  private getCurrentParameterValue(element: string, parameter: string): string {
    // 根据元素类型和参数获取当前值
    if (!this.selectedVersion || !this.quantifiedProposal) return '';
    
    switch (element) {
      case 'furniture':
        // 从家具配置中获取参数值
        const furniture = this.quantifiedProposal.spaceModules[0]?.furniture.find(f => f.name.includes(parameter));
        return furniture ? JSON.stringify(furniture) : '';
      case 'color':
        return this.selectedVersion.mainColor.rgb;
      case 'material':
        const material = this.selectedVersion.materialRatio.find(m => m.material === parameter);
        return material ? material.percentage.toString() : '';
      case 'layout':
        return '当前布局配置';
      default:
        return '';
    }
  }

  private applyAdjustment(adjustment: ProposalAdjustment): void {
    if (!this.selectedVersion || !this.quantifiedProposal) return;

    // 根据调整类型更新方案数据
    switch (adjustment.element) {
      case 'furniture':
        this.applyFurnitureAdjustment(adjustment);
        break;
      case 'color':
        this.applyColorAdjustment(adjustment);
        break;
      case 'material':
        this.applyMaterialAdjustment(adjustment);
        break;
      case 'layout':
        this.applyLayoutAdjustment(adjustment);
        break;
    }
    
    // 重新生成量化方案
    this.generateQuantifiedProposal();
    
    // 更新预览
    this.updatePreview();
  }

  private applyFurnitureAdjustment(adjustment: ProposalAdjustment): void {
    // 应用家具调整
    if (this.quantifiedProposal?.spaceModules[0]?.furniture) {
      const furniture = this.quantifiedProposal.spaceModules[0].furniture.find(f => 
        f.name.includes(adjustment.parameter)
      );
      if (furniture) {
        // 根据新值更新家具属性
        try {
          const newFurnitureData = JSON.parse(adjustment.newValue);
          Object.assign(furniture, newFurnitureData);
        } catch {
          // 如果不是JSON格式，则作为简单值处理
          furniture.name = adjustment.newValue;
        }
      }
    }
  }

  private applyColorAdjustment(adjustment: ProposalAdjustment): void {
    // 应用色彩调整
    if (this.selectedVersion) {
      this.selectedVersion.mainColor.rgb = adjustment.newValue;
      if (this.quantifiedProposal?.colorAndTexture) {
        this.quantifiedProposal.colorAndTexture.mainColor = this.selectedVersion.mainColor;
      }
    }
  }

  private applyMaterialAdjustment(adjustment: ProposalAdjustment): void {
    // 应用材质调整
    if (this.selectedVersion) {
      const material = this.selectedVersion.materialRatio.find(m => m.material === adjustment.parameter);
      if (material) {
        material.percentage = parseInt(adjustment.newValue);
      }
    }
  }

  private applyLayoutAdjustment(adjustment: ProposalAdjustment): void {
    // 应用布局调整
    console.log('应用布局调整:', adjustment);
    // 这里可以根据具体的布局调整逻辑进行实现
  }

  private saveVersionHistory(adjustment?: ProposalAdjustment): void {
    if (this.selectedVersion && this.quantifiedProposal) {
      const historyItem: VersionHistoryItem = {
        id: this.generateId(),
        timestamp: new Date(),
        version: JSON.parse(JSON.stringify(this.selectedVersion)),
        proposal: JSON.parse(JSON.stringify(this.quantifiedProposal)),
        adjustment: adjustment,
        description: adjustment ? 
          `调整${adjustment.element}: ${adjustment.parameter} -> ${adjustment.newValue}` : 
          '保存当前版本'
      };
      
      this.versionHistory.push(historyItem);
      this.undoStack.push(historyItem);
      this.redoStack = []; // 清空重做栈
      this.updateUndoRedoState();
    }
  }

  restoreVersion(index: number): void {
    if (this.versionHistory[index]) {
      const historyItem = this.versionHistory[index];
      
      // 保存当前状态到重做栈
      if (this.selectedVersion && this.quantifiedProposal) {
        this.redoStack.push({
          id: this.generateId(),
          timestamp: new Date(),
          version: JSON.parse(JSON.stringify(this.selectedVersion)),
          proposal: JSON.parse(JSON.stringify(this.quantifiedProposal)),
          description: '恢复前状态'
        });
      }
      
      this.selectedVersion = JSON.parse(JSON.stringify(historyItem.version));
      this.quantifiedProposal = JSON.parse(JSON.stringify(historyItem.proposal));
      
      this.updateUndoRedoState();
      this.updatePreview();
    }
  }

  // 撤销功能
  undoAdjustment(): void {
    if (this.canUndo && this.undoStack.length > 1) {
      // 保存当前状态到重做栈
      const currentState: VersionHistoryItem = {
        id: this.generateId(),
        timestamp: new Date(),
        version: JSON.parse(JSON.stringify(this.selectedVersion)),
        proposal: JSON.parse(JSON.stringify(this.quantifiedProposal)),
        description: '撤销前状态'
      };
      this.redoStack.push(currentState);
      
      // 移除当前状态
      this.undoStack.pop();
      
      // 恢复到上一个状态
      const previousState = this.undoStack[this.undoStack.length - 1];
      this.selectedVersion = JSON.parse(JSON.stringify(previousState.version));
      this.quantifiedProposal = JSON.parse(JSON.stringify(previousState.proposal));
      
      this.updateUndoRedoState();
      this.updatePreview();
    }
  }

  // 重做功能
  redoAdjustment(): void {
    if (this.canRedo && this.redoStack.length > 0) {
      const redoState = this.redoStack.pop()!;
      
      // 保存当前状态到撤销栈
      this.undoStack.push({
        id: this.generateId(),
        timestamp: new Date(),
        version: JSON.parse(JSON.stringify(this.selectedVersion)),
        proposal: JSON.parse(JSON.stringify(this.quantifiedProposal)),
        description: '重做前状态'
      });
      
      this.selectedVersion = JSON.parse(JSON.stringify(redoState.version));
      this.quantifiedProposal = JSON.parse(JSON.stringify(redoState.proposal));
      
      this.updateUndoRedoState();
      this.updatePreview();
    }
  }

  private updateUndoRedoState(): void {
    this.canUndo = this.undoStack.length > 1;
    this.canRedo = this.redoStack.length > 0;
  }

  // 快速调整方法
  quickAdjustColor(newColor: string): void {
    const adjustment: ProposalAdjustment = {
      id: this.generateId(),
      element: 'color',
      parameter: 'mainColor',
      oldValue: this.selectedVersion?.mainColor.rgb || '',
      newValue: newColor,
      reason: '快速色彩调整',
      timestamp: new Date(),
      operator: '当前用户'
    };
    
    this.saveVersionHistory(adjustment);
    this.applyAdjustment(adjustment);
    this.adjustmentHistory.push(adjustment);
    this.updateUndoRedoState();
  }

  quickAdjustMaterial(material: string, percentage: number): void {
    const adjustment: ProposalAdjustment = {
      id: this.generateId(),
      element: 'material',
      parameter: material,
      oldValue: this.getCurrentParameterValue('material', material),
      newValue: percentage.toString(),
      reason: '快速材质比例调整',
      timestamp: new Date(),
      operator: '当前用户'
    };
    
    this.saveVersionHistory(adjustment);
    this.applyAdjustment(adjustment);
    this.adjustmentHistory.push(adjustment);
    this.updateUndoRedoState();
  }

  // 切换调整面板
  toggleAdjustmentPanel(): void {
    this.isAdjusting = !this.isAdjusting;
    if (this.isAdjusting) {
      this.adjustmentForm.reset({
        element: 'furniture',
        parameter: '',
        newValue: '',
        reason: ''
      });
    }
  }

  // 切换版本历史面板
  toggleVersionHistory(): void {
    this.showVersionHistory = !this.showVersionHistory;
  }

  // 清空调整历史
  clearAdjustmentHistory(): void {
    this.adjustmentHistory = [];
    this.versionHistory = [];
    this.undoStack = [];
    this.redoStack = [];
    this.updateUndoRedoState();
  }

  // 工具方法
  generateId(): string {
    return Math.random().toString(36).substr(2, 9);
  }

  getRoleClass(role: string): string {
    switch (role) {
      case 'client': return 'role-client';
      case 'designer': return 'role-designer';
      case 'manager': return 'role-manager';
      case 'customer-service': return 'role-customer-service';
      default: return 'role-default';
    }
  }

  switchTab(tab: 'overview' | 'versions' | 'details' | 'collaboration' | 'confirmation') {
    this.activeTab = tab;
  }

  toggle3DPreview() {
    this.show3DPreview = !this.show3DPreview;
    if (this.show3DPreview) {
      this.initialize3DPreview();
    }
  }

  toggleCADOverlay() {
    this.showCADOverlay = !this.showCADOverlay;
    if (this.showCADOverlay) {
      this.loadCADOverlay();
    }
  }

  // 3D预览功能
  private initialize3DPreview() {
    // 初始化3D预览组件
    // 这里可以集成Three.js或其他3D库
    console.log('初始化3D预览');
  }

  // CAD叠加功能
  private loadCADOverlay() {
    // 加载CAD图层
    console.log('加载CAD叠加图层');
  }

  // 色彩对比功能
  adjustColorSample(sampleName: string, newRgb: string) {
    if (this.quantifiedProposal?.colorAndTexture.colorSamples) {
      const sample = this.quantifiedProposal.colorAndTexture.colorSamples.find(s => s.name === sampleName);
      if (sample) {
        sample.actual = newRgb;
        sample.difference = this.calculateColorDifference(sample.rgb, newRgb);
      }
    }
  }

  private calculateColorDifference(rgb1: string, rgb2: string): number {
    // 简化的色彩差异计算
    const [r1, g1, b1] = rgb1.split(',').map(Number);
    const [r2, g2, b2] = rgb2.split(',').map(Number);
    
    const deltaR = r1 - r2;
    const deltaG = g1 - g2;
    const deltaB = b1 - b2;
    
    const distance = Math.sqrt(deltaR * deltaR + deltaG * deltaG + deltaB * deltaB);
    return Math.round((distance / 441.67) * 100); // 归一化到百分比
  }

  // 偏好标记功能
  markPreference(elementType: string, elementId: string, preference: 'like' | 'dislike') {
    // 记录用户偏好
    console.log(`标记偏好: ${elementType} ${elementId} - ${preference}`);
    // 这里可以保存到后端或本地存储
  }

  // 实时预览更新
  updatePreview() {
    if (this.show3DPreview) {
      this.initialize3DPreview();
    }
    if (this.showCADOverlay) {
      this.loadCADOverlay();
    }
  }

  // 版本对比功能
  compareVersions(versionA: string, versionB: string): void {
    this.showVersionComparison = true;
    this.comparisonVersions = {
      versionA: this.proposalVersions.find(v => v.id === versionA)!,
      versionB: this.proposalVersions.find(v => v.id === versionB)!
    };
    this.generateVersionDifferences();
  }

  generateVersionDifferences(): void {
    if (!this.comparisonVersions) return;
    
    const { versionA, versionB } = this.comparisonVersions;
    this.versionDifferences = {
      budget: {
        field: '预算',
        valueA: `¥${versionA.budget}`,
        valueB: `¥${versionB.budget}`,
        difference: versionB.budget - versionA.budget,
        type: versionB.budget > versionA.budget ? 'increase' : 'decrease'
      },
      workDays: {
        field: '工期',
        valueA: `${versionA.workDays}天`,
        valueB: `${versionB.workDays}天`,
        difference: versionB.workDays - versionA.workDays,
        type: versionB.workDays > versionA.workDays ? 'increase' : 'decrease'
      },
      mainColor: {
        field: '主色调',
        valueA: versionA.mainColor,
        valueB: versionB.mainColor,
        difference: 0,
        type: versionA.mainColor === versionB.mainColor ? 'same' : 'different'
      },
      style: {
        field: '风格',
        valueA: versionA.description,
        valueB: versionB.description,
        difference: 0,
        type: versionA.description === versionB.description ? 'same' : 'different'
      }
    };
  }

  highlightDifferences(field: string): void {
    // 高亮显示差异项
    const element = document.querySelector(`[data-field="${field}"]`);
    if (element) {
      element.classList.add('highlight-difference');
      setTimeout(() => {
        element.classList.remove('highlight-difference');
      }, 2000);
    }
  }

  // 方案确认与闭环功能
  confirmStep(stepId: string): void {
    const step = this.confirmationSteps.find(s => s.id === stepId);
    if (step) {
      step.status = 'confirmed';
      step.confirmedAt = new Date();
      step.confirmedBy = '当前用户'; // 实际应用中从用户服务获取
      
      // 记录电子留痕
      this.recordConfirmationTrace(stepId, 'confirmed');
      
      // 更新整体进度
      this.updateOverallProgress();
      
      // 检查是否所有步骤都已确认
      this.checkAllStepsConfirmed();
    }
  }

  rejectStep(stepId: string, reason: string): void {
    const step = this.confirmationSteps.find(s => s.id === stepId);
    if (step) {
      step.status = 'rejected';
      step.rejectedAt = new Date();
      step.rejectedBy = '当前用户';
      step.rejectionReason = reason;
      
      // 记录电子留痕
      this.recordConfirmationTrace(stepId, 'rejected', reason);
      
      // 更新整体进度
      this.updateOverallProgress();
    }
  }

  recordConfirmationTrace(stepId: string, action: 'confirmed' | 'rejected', reason?: string): void {
    const trace = {
      id: this.generateId(),
      stepId,
      action,
      timestamp: new Date(),
      user: '当前用户',
      reason: reason || '',
      ipAddress: '127.0.0.1', // 实际应用中获取真实IP
      userAgent: navigator.userAgent
    };
    
    // 存储到确认历史中
    if (!this.confirmationHistory) {
      this.confirmationHistory = [];
    }
    this.confirmationHistory.push(trace);
    
    // 触发确认历史更新事件
    this.confirmationHistoryUpdated.emit(trace);
  }

  updateOverallProgress(): void {
    const totalSteps = this.confirmationSteps.length;
    const confirmedSteps = this.confirmationSteps.filter(s => s.status === 'confirmed').length;
    this.overallProgress = Math.round((confirmedSteps / totalSteps) * 100);
  }

  checkAllStepsConfirmed(): void {
    const allConfirmed = this.confirmationSteps.every(s => s.status === 'confirmed');
    if (allConfirmed) {
      this.allStepsConfirmed = true;
      this.allStepsConfirmedAt = new Date();
      
      // 触发全部确认完成事件
      this.allConfirmed.emit({
        proposalId: this.proposal?.id,
        confirmedAt: this.allStepsConfirmedAt,
        confirmationHistory: this.confirmationHistory
      });
    }
  }

  finalConfirm(): void {
    if (this.allStepsConfirmed) {
      const finalConfirmation = {
        id: this.generateId(),
        proposalId: this.proposal?.id,
        versionId: this.selectedVersion?.id,
        confirmedAt: new Date(),
        confirmedBy: '当前用户',
        digitalSignature: this.generateDigitalSignature(),
        confirmationSteps: this.confirmationSteps,
        confirmationHistory: this.confirmationHistory
      };
      
      // 触发最终确认事件
      this.finalConfirmed.emit(finalConfirmation);
      
      // 更新组件状态
      this.isFinalConfirmed = true;
      this.finalConfirmedAt = new Date();
    }
  }

  generateDigitalSignature(): string {
    // 简化的数字签名生成（实际应用中应使用加密算法）
    const data = {
      proposalId: this.proposal?.id,
      versionId: this.selectedVersion?.id,
      timestamp: new Date().getTime(),
      user: '当前用户'
    };
    
    return btoa(JSON.stringify(data));
  }

  // 对话框状态
  showRejectReasonDialog = false;
  showConfirmationHistory = false;
  rejectionReason = '';
  currentRejectingStepId: string | null = null;

  // 显示拒绝对话框
  showRejectDialog(stepId: string): void {
    this.currentRejectingStepId = stepId;
    this.rejectionReason = '';
    this.showRejectReasonDialog = true;
  }

  // 关闭拒绝对话框
  closeRejectDialog(): void {
    this.showRejectReasonDialog = false;
    this.currentRejectingStepId = null;
    this.rejectionReason = '';
  }

  // 确认拒绝
  confirmReject(): void {
    if (this.currentRejectingStepId && this.rejectionReason.trim()) {
      this.rejectStep(this.currentRejectingStepId, this.rejectionReason.trim());
      this.closeRejectDialog();
    }
  }

  // 批注相关属性
  mentionUsers: User[] = [];
  showMentionSuggestions = false;
  filteredMentionUsers: User[] = [];
  currentMentionQuery = '';
  mentionFilter = '';

  // 提取@提及
  extractMentions(content: string): string[] {
    const mentionRegex = /@(\w+)/g;
    const mentions: string[] = [];
    let match;
    
    while ((match = mentionRegex.exec(content)) !== null) {
      const username = match[1];
      // 验证用户是否存在
      const user = this.mentionUsers.find(u => u.name.toLowerCase() === username.toLowerCase());
      if (user) {
        mentions.push(user.id);
      }
    }
    
    return mentions;
  }

  // 发送提及通知
  sendMentionNotifications(mentions: string[], annotation: Annotation, reply?: AnnotationReply): void {
    mentions.forEach(userId => {
      const user = this.mentionUsers.find(u => u.id === userId);
      if (user) {
        console.log(`发送提及通知给 ${user.name}`);
        // 这里可以集成实际的通知系统
      }
    });
  }

  // 内容输入处理
  onContentInput(event: Event): void {
    const target = event.target as HTMLTextAreaElement;
    const content = target.value;
    const cursorPosition = target.selectionStart;
    
    // 检查是否在输入@提及
    const beforeCursor = content.substring(0, cursorPosition);
    const mentionMatch = beforeCursor.match(/@(\w*)$/);
    
    if (mentionMatch) {
      this.currentMentionQuery = mentionMatch[1];
      this.showMentionSuggestions = true;
      this.filteredMentionUsers = this.mentionUsers.filter(user => 
        user.name.toLowerCase().includes(this.currentMentionQuery.toLowerCase())
      );
    } else {
      this.showMentionSuggestions = false;
    }
  }

  // 选择提及用户
  selectMention(user: User): void {
    const textarea = document.querySelector('textarea[formControlName="content"]') as HTMLTextAreaElement;
    if (textarea) {
      const content = textarea.value;
      const cursorPosition = textarea.selectionStart;
      const beforeCursor = content.substring(0, cursorPosition);
      const afterCursor = content.substring(cursorPosition);
      const newContent = beforeCursor.replace(/@\w*$/, `@${user.name} `) + afterCursor;
      this.annotationForm.patchValue({ content: newContent });
    }
    this.showMentionSuggestions = false;
  }

  // 格式化包含提及的内容
  formatContentWithMentions(content: string): string {
    return content.replace(/@(\w+)/g, '<span class="mention">@$1</span>');
  }

  // 获取状态样式类
  getStatusClass(status: string): string {
    switch (status) {
      case 'open': return 'status-open';
      case 'resolved': return 'status-resolved';
      case 'pending': return 'status-pending';
      case 'confirmed': return 'status-confirmed';
      case 'rejected': return 'status-rejected';
      default: return '';
    }
  }

  // 导出确认报告
  exportConfirmationReport(): void {
    const report = {
      projectId: this.projectId,
      proposalVersion: this.selectedVersion,
      confirmationSteps: this.confirmationSteps,
      overallProgress: this.overallProgress,
      allStepsConfirmed: this.allStepsConfirmed,
      allStepsConfirmedAt: this.allStepsConfirmedAt,
      isFinalConfirmed: this.isFinalConfirmed,
      finalConfirmedAt: this.finalConfirmedAt,
      confirmationHistory: this.confirmationHistory,
      annotations: this.annotations,
      exportedAt: new Date(),
      digitalSignature: this.generateDigitalSignature()
    };

    const blob = new Blob([JSON.stringify(report, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `confirmation-report-${this.projectId}-${Date.now()}.json`;
    a.click();
    URL.revokeObjectURL(url);

    this.confirmationReportExported.emit(report);
  }

  // 获取操作文本
  getActionText(action: string): string {
    switch (action) {
      case 'confirmed': return '确认';
      case 'rejected': return '拒绝';
      default: return action;
    }
  }

  // 获取进度百分比
  getProgressPercentage(): number {
    return Math.round(this.overallProgress);
  }

  // 获取未确认的必需项目数量
  getRequiredUnconfirmedCount(): number {
    if (!this.confirmationSteps) {
      return 0;
    }
    return this.confirmationSteps.filter(s => s && s.required && s.status !== 'confirmed').length;
  }
  getRequiredCount(): number {
    if (!this.confirmationSteps) {
      return 0;
    }
    return this.confirmationSteps.filter(s => s && s.required).length;
  }
  getConfirmedRequiredCount(): number {
    if (!this.confirmationSteps) return 0;
    return this.confirmationSteps.filter(s => s && s.required && s.status === 'confirmed').length;
  }

  getSpaceModulesVerified(): boolean {
    if (!this.quantifiedProposal?.spaceModules) return false;
    return this.quantifiedProposal.spaceModules.every(m => m.verified);
  }
}

// 方案调整接口
interface ProposalAdjustment {
  id: string;
  element: 'furniture' | 'color' | 'material' | 'layout';
  parameter: string;
  oldValue: string;
  newValue: string;
  reason: string;
  timestamp: Date;
  operator: string;
}

// 版本历史接口
interface VersionHistoryItem {
  id: string;
  timestamp: Date;
  version: ProposalVersion;
  proposal: QuantifiedProposal;
  adjustment?: ProposalAdjustment;
  description: string;
}