import { Component, OnInit, Input, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { FmodeObject, FmodeParse } from 'fmode-ng/parse';
import { ProjectFileService } from '../../../services/project-file.service';
import { ProductSpaceService, Project } from '../../../services/product-space.service';
import { WxworkAuth } from 'fmode-ng/social';

const Parse = FmodeParse.with('nova');

/**
 * 支付凭证接口
 */
interface PaymentVoucher {
  id: string;
  projectFileId: string;
  url: string;
  amount: number;
  paymentMethod: string;
  paymentTime: Date;
  productId?: string;
  ocrResult?: {
    amount: number;
    confidence: number;
    paymentTime?: Date;
    paymentMethod?: string;
  };
}

/**
 * 尾款管理接口
 */
interface FinalPayment {
  totalAmount: number;
  paidAmount: number;
  remainingAmount: number;
  status: 'pending' | 'partial' | 'completed' | 'overdue';
  dueDate?: Date;
  overdueDays?: number;
  paymentVouchers: PaymentVoucher[];
  productBreakdown: Array<{
    productId: string;
    productName: string;
    amount: number;
    paidAmount: number;
    percentage: number;
    status: 'pending' | 'partial' | 'completed';
  }>;
}

/**
 * 客户评价接口
 */
interface CustomerFeedback {
  submitted: boolean;
  submittedAt?: Date;
  overallRating: number;
  dimensionRatings: {
    designQuality: number;
    serviceAttitude: number;
    deliveryTimeliness: number;
    valueForMoney: number;
    communication: number;
  };
  productFeedbacks: Array<{
    productId: string;
    productName: string;
    rating: number;
    comments: string;
  }>;
  comments: string;
  improvements: string;
  wouldRecommend: boolean;
  recommendationWillingness: {
    score: number;
    reasons: string[];
    networkScope: string[];
  };
}

/**
 * 项目复盘接口
 */
interface ProjectRetrospective {
  generated: boolean;
  generatedAt?: Date;
  generatedBy?: {
    id: string;
    name: string;
  };
  summary: string;
  highlights: string[];
  challenges: string[];
  lessons: string[];
  recommendations: string[];
  efficiencyAnalysis: {
    overallScore: number;
    grade: 'A' | 'B' | 'C' | 'D' | 'F';
    timeEfficiency: {
      score: number;
      plannedDuration: number;
      actualDuration: number;
      variance: number;
    };
    qualityEfficiency: {
      score: number;
      firstPassYield: number;
      revisionRate: number;
      issueCount: number;
    };
    resourceUtilization: {
      score: number;
      teamSize: number;
      workload: number;
      idleRate: number;
    };
    stageMetrics: Array<{
      stage: string;
      plannedDays: number;
      actualDays: number;
      efficiency: number;
      status: 'on-time' | 'delayed' | 'ahead';
      delayReason?: string;
    }>;
    bottlenecks: Array<{
      stage: string;
      issue: string;
      severity: 'high' | 'medium' | 'low';
      suggestion: string;
    }>;
  };
  teamPerformance: {
    overallScore: number;
    members: Array<{
      memberId: string;
      memberName: string;
      role: string;
      scores: {
        workload: number;
        quality: number;
        efficiency: number;
        collaboration: number;
        innovation: number;
        overall: number;
      };
      timeDistribution: {
        design: number;
        communication: number;
        revision: number;
        admin: number;
      };
      contributions: string[];
      strengths: string[];
      improvements: string[];
      ranking: number;
    }>;
  };
  financialAnalysis: {
    budgetVariance: number;
    profitMargin: number;
    costBreakdown: {
      labor: number;
      materials: number;
      overhead: number;
      revisions: number;
    };
    revenueAnalysis: {
      contracted: number;
      received: number;
      pending: number;
    };
  };
  satisfactionAnalysis: {
    overallScore: number;
    nps: number;
    dimensions: Array<{
      name: string;
      label: string;
      score: number;
      benchmark: number;
      variance: number;
    }>;
    improvementAreas: Array<{
      area: string;
      currentScore: number;
      targetScore: number;
      priority: 'high' | 'medium' | 'low';
      actionPlan: string;
    }>;
  };
  risksAndOpportunities: {
    risks: Array<{
      type: 'timeline' | 'budget' | 'quality' | 'resource' | 'scope';
      description: string;
      likelihood: number;
      impact: number;
      severity: 'high' | 'medium' | 'low';
      mitigation: string;
    }>;
    opportunities: Array<{
      area: string;
      description: string;
      potential: number;
      effort: number;
      priority: 'high' | 'medium' | 'low';
      actionPlan: string;
    }>;
  };
  productRetrospectives: Array<{
    productId: string;
    productName: string;
    performance: number;
    plannedDays: number;
    actualDays: number;
    issues: string[];
    recommendations: string[];
  }>;
  benchmarking: {
    comparisonToHistory: {
      averageEfficiency: number;
      currentEfficiency: number;
      ranking: number;
      percentile: number;
    };
    industryBenchmark: {
      timelineVariance: number;
      satisfactionScore: number;
      profitMargin: number;
    };
  };
}

/**
 * 归档状态接口
 */
interface ArchiveStatus {
  archived: boolean;
  archiveTime?: Date;
  archivedBy?: {
    id: string;
    name: string;
  };
  archiveNotes?: string;
}

/**
 * 售后归档阶段组件
 *
 * 功能：
 * 1. 尾款管理（支持按Product分摊）
 * 2. 客户评价（整体+维度+Product分别评价）
 * 3. 项目复盘（深度分析：效率、团队、财务、满意度等7大维度）
 * 4. 项目归档（完成所有环节后归档）
 */
@Component({
  selector: 'app-stage-aftercare',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './stage-aftercare.component.html',
  styleUrls: ['./stage-aftercare.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class StageAftercareComponent implements OnInit {
  @Input() project: FmodeObject | null = null;
  @Input() customer: FmodeObject | null = null;
  @Input() currentUser: FmodeObject | null = null;
  @Input() canEdit: boolean = true;

  // 路由参数
  cid: string = '';
  projectId: string = '';

  // Product-based 场景管理
  projectProducts: Project[] = [];
  isMultiProductProject: boolean = false;

  // Tab管理
  activeTab: 'overview' | 'payment' | 'feedback' | 'retrospective' = 'overview';

  // 尾款管理
  finalPayment: FinalPayment = {
    totalAmount: 0,
    paidAmount: 0,
    remainingAmount: 0,
    status: 'pending',
    paymentVouchers: [],
    productBreakdown: []
  };

  // 客户评价
  customerFeedback: CustomerFeedback = {
    submitted: false,
    overallRating: 0,
    dimensionRatings: {
      designQuality: 0,
      serviceAttitude: 0,
      deliveryTimeliness: 0,
      valueForMoney: 0,
      communication: 0
    },
    productFeedbacks: [],
    comments: '',
    improvements: '',
    wouldRecommend: false,
    recommendationWillingness: {
      score: 0,
      reasons: [],
      networkScope: []
    }
  };

  // 项目复盘
  projectRetrospective: ProjectRetrospective | null = null;

  // 归档状态
  archiveStatus: ArchiveStatus = {
    archived: false
  };

  // UI状态
  loading: boolean = false;
  saving: boolean = false;
  uploading: boolean = false;
  generating: boolean = false;

  // 统计数据
  stats = {
    completionRate: 0,
    averageRating: 0,
    npsScore: 0
  };

  constructor(
    private cdr: ChangeDetectorRef,
    private route: ActivatedRoute,
    private projectFileService: ProjectFileService,
    public productSpaceService: ProductSpaceService
  ) {}

  async ngOnInit() {
    this.route.queryParams.subscribe(async params => {
      this.cid = params['cid'] || localStorage.getItem("company") || '';
      this.projectId = params['projectId'] || this.project?.id || '';
      
      // @ts-ignore - WxworkAuth type issue with fmode-ng
      let wwauth = new WxworkAuth({cid:this.cid})
      this.currentUser = await wwauth.currentProfile();
      await this.loadData();
    });
  }

  /**
   * 加载数据
   */
  async loadData() {

    // 使用FmodeParse加载项目、客户、当前用户
    if (!this.project && this.projectId) {
      const query = new Parse.Query('Project');
      query.include('customer', 'assignee', 'department');
      this.project = await query.get(this.projectId);
      this.customer = this.project.get('customer');
    }
    
    if (!this.project) return;

    try {
      this.loading = true;
      this.cdr.markForCheck();

      // 加载Product列表
      const projectDataStr = this.project.get('data');
      if (projectDataStr) {
        const projectData = JSON.parse(projectDataStr);
        if (projectData.projects && Array.isArray(projectData.projects)) {
          this.projectProducts = projectData.projects;
          this.isMultiProductProject = this.projectProducts.length > 1;
        }

        // 加载售后归档数据
        if (projectData.finalPayment) {
          this.finalPayment = projectData.finalPayment;
        }
        if (projectData.customerFeedback) {
          this.customerFeedback = projectData.customerFeedback;
        }
        if (projectData.projectRetrospective) {
          this.projectRetrospective = projectData.projectRetrospective;
        }
        if (projectData.archiveStatus) {
          this.archiveStatus = projectData.archiveStatus;
        }
      }

      // 加载支付凭证文件
      await this.loadPaymentVouchers();

      // 初始化尾款分摊
      if (this.isMultiProductProject && this.finalPayment.productBreakdown.length === 0) {
        this.initializeProductBreakdown();
      }

      // 计算统计数据
      this.calculateStats();

      this.cdr.markForCheck();
    } catch (error) {
      console.error('加载数据失败:', error);
    } finally {
      this.loading = false;
      this.cdr.markForCheck();
    }
  }

  /**
   * 加载支付凭证
   */
  async loadPaymentVouchers() {
    if (!this.project) return;

    try {
      const files = await this.projectFileService.getProjectFiles(this.project.id!, {
        fileType: 'payment_voucher',
        stage: 'aftercare'
      });

      // 更新支付凭证列表
      this.finalPayment.paymentVouchers = files.map(file => ({
        id: file.id!,
        projectFileId: file.id!,
        url: file.get('fileUrl') || '',
        amount: file.get('metadata')?.amount || 0,
        paymentMethod: file.get('metadata')?.paymentMethod || '待确认',
        paymentTime: file.get('metadata')?.paymentTime ? new Date(file.get('metadata').paymentTime) : new Date(),
        productId: file.get('spaceId'),
        ocrResult: file.get('metadata')?.ocrResult
      }));

      // 重新计算已支付金额
      this.calculatePaidAmount();
    } catch (error) {
      console.error('加载支付凭证失败:', error);
    }
  }

  /**
   * 初始化Product分摊
   */
  initializeProductBreakdown() {
    const totalAmount = this.finalPayment.totalAmount;
    if (totalAmount === 0 || this.projectProducts.length === 0) return;

    const averageAmount = totalAmount / this.projectProducts.length;

    this.finalPayment.productBreakdown = this.projectProducts.map(product => ({
      productId: product.id,
      productName: product.name || this.productSpaceService.getProductTypeName(product.type),
      amount: averageAmount,
      paidAmount: 0,
      percentage: 100 / this.projectProducts.length,
      status: 'pending' as const
    }));
  }

  /**
   * 计算已支付金额
   */
  calculatePaidAmount() {
    const totalPaid = this.finalPayment.paymentVouchers.reduce((sum, v) => sum + (v.amount || 0), 0);
    this.finalPayment.paidAmount = totalPaid;
    this.finalPayment.remainingAmount = this.finalPayment.totalAmount - totalPaid;

    // 更新支付状态
    if (this.finalPayment.remainingAmount <= 0) {
      this.finalPayment.status = 'completed';
    } else if (this.finalPayment.paidAmount > 0) {
      this.finalPayment.status = 'partial';
    } else {
      this.finalPayment.status = 'pending';
    }

    // 更新Product分摊的已支付金额
    if (this.isMultiProductProject) {
      this.finalPayment.productBreakdown.forEach(item => {
        const productVouchers = this.finalPayment.paymentVouchers.filter(v => v.productId === item.productId);
        item.paidAmount = productVouchers.reduce((sum, v) => sum + (v.amount || 0), 0);
        item.status = item.paidAmount >= item.amount ? 'completed' : item.paidAmount > 0 ? 'partial' : 'pending';
      });
    }
  }

  /**
   * 计算统计数据
   */
  calculateStats() {
    // 完成度计算
    let completedItems = 0;
    const totalItems = 3;

    if (this.finalPayment.status === 'completed') completedItems++;
    if (this.customerFeedback.submitted) completedItems++;
    if (this.projectRetrospective) completedItems++;

    this.stats.completionRate = Math.round((completedItems / totalItems) * 100);

    // 平均评分
    if (this.customerFeedback.overallRating > 0) {
      this.stats.averageRating = this.customerFeedback.overallRating;
    }

    // NPS
    if (this.customerFeedback.recommendationWillingness.score > 0) {
      this.stats.npsScore = this.customerFeedback.recommendationWillingness.score;
    }
  }

  /**
   * 切换Tab
   */
  switchTab(tab: 'overview' | 'payment' | 'feedback' | 'retrospective') {
    this.activeTab = tab;
    this.cdr.markForCheck();
  }

  /**
   * 上传支付凭证
   */
  async uploadPaymentVoucher(event: any, productId?: string) {
    const files = event.target.files;
    if (!files || files.length === 0 || !this.project) return;

    try {
      this.uploading = true;
      this.cdr.markForCheck();

      for (let i = 0; i < files.length; i++) {
        const file = files[i];

        // 使用ProjectFileService上传并创建ProjectFile记录
        const projectFile = await this.projectFileService.uploadProjectFileWithRecord(
          file,
          this.project.id!,
          'payment_voucher',
          productId,
          'aftercare',
          {
            paymentType: 'final_payment',
            uploadSource: 'aftercare',
            productId
          }
        );

        this.finalPayment.paymentVouchers.push({
          id: projectFile.id!,
          projectFileId: projectFile.id!,
          url: projectFile.get('fileUrl') || '',
          amount: 0,
          paymentTime: new Date(),
          paymentMethod: '待确认',
          productId: productId,
          ocrResult: undefined
        });
      }

      await this.saveDraft();
      this.cdr.markForCheck();
      alert('上传成功');
    } catch (error: any) {
      console.error('上传失败:', error);
      alert('上传失败: ' + (error?.message || '未知错误'));
    } finally {
      this.uploading = false;
      this.cdr.markForCheck();
    }
  }

  /**
   * 更新凭证金额
   */
  async updateVoucherAmount(voucherId: string, amount: number) {
    const voucher = this.finalPayment.paymentVouchers.find(v => v.id === voucherId);
    if (voucher) {
      voucher.amount = amount;
      this.calculatePaidAmount();
      await this.saveDraft();
      this.cdr.markForCheck();
    }
  }

  /**
   * 删除支付凭证
   */
  async deletePaymentVoucher(voucherId: string) {
    if (!confirm('确定删除此凭证吗？')) return;

    try {
      const voucher = this.finalPayment.paymentVouchers.find(v => v.id === voucherId);
      if (voucher && voucher.projectFileId) {
        await this.projectFileService.deleteProjectFile(voucher.projectFileId);
      }

      this.finalPayment.paymentVouchers = this.finalPayment.paymentVouchers.filter(v => v.id !== voucherId);
      this.calculatePaidAmount();
      await this.saveDraft();
      this.cdr.markForCheck();
      alert('删除成功');
    } catch (error: any) {
      console.error('删除失败:', error);
      alert('删除失败: ' + (error?.message || '未知错误'));
    }
  }

  /**
   * 设置评分
   */
  setRating(path: string, value: number) {
    if (path === 'overallRating') {
      this.customerFeedback.overallRating = value;
    } else if (path.startsWith('dimensionRatings.')) {
      const dimension = path.split('.')[1] as keyof CustomerFeedback['dimensionRatings'];
      this.customerFeedback.dimensionRatings[dimension] = value;
    }
    this.cdr.markForCheck();
  }

  /**
   * 设置NPS评分
   */
  setNPSScore(score: number) {
    this.customerFeedback.recommendationWillingness.score = score;
    this.cdr.markForCheck();
  }

  /**
   * 提交评价
   */
  async submitFeedback() {
    if (this.customerFeedback.overallRating === 0) {
      alert('请选择综合评分');
      return;
    }

    try {
      this.saving = true;
      this.cdr.markForCheck();

      this.customerFeedback.submitted = true;
      this.customerFeedback.submittedAt = new Date();

      await this.saveDraft();
      this.calculateStats();
      this.cdr.markForCheck();
      alert('评价提交成功');
    } catch (error: any) {
      console.error('提交失败:', error);
      alert('提交失败: ' + (error?.message || '未知错误'));
    } finally {
      this.saving = false;
      this.cdr.markForCheck();
    }
  }

  /**
   * 生成项目复盘
   */
  async generateRetrospective() {

    try {
      this.generating = true;
      this.cdr.markForCheck();

      // 收集项目数据
      const projectData = await this.collectProjectData();

      // 生成复盘报告
      this.projectRetrospective = {
        generated: true,
        generatedAt: new Date(),
        generatedBy: {
          id: this.currentUser!.id!,
          name: this.currentUser!.get('name') || ''
        },
        summary: this.generateSummary(projectData),
        highlights: this.generateHighlights(projectData),
        challenges: this.extractChallenges(projectData),
        lessons: this.generateLessons(projectData),
        recommendations: this.generateRecommendations(projectData),
        efficiencyAnalysis: this.analyzeEfficiency(projectData),
        teamPerformance: this.analyzeTeamPerformance(projectData),
        financialAnalysis: this.analyzeFinancial(projectData),
        satisfactionAnalysis: this.analyzeSatisfaction(projectData),
        risksAndOpportunities: this.identifyRisksAndOpportunities(projectData),
        productRetrospectives: this.generateProductRetrospectives(projectData),
        benchmarking: this.generateBenchmarking(projectData)
      };

      await this.saveDraft();
      this.calculateStats();
      this.cdr.markForCheck();
      alert('项目复盘生成成功');
    } catch (error: any) {
      console.error('生成失败:', error);
      alert('生成失败: ' + (error?.message || '未知错误'));
    } finally {
      this.generating = false;
      this.cdr.markForCheck();
    }
  }

  /**
   * 收集项目数据
   */
  async collectProjectData(): Promise<any> {
    if (!this.project) return {};

    const data = this.project.get('data');
    const parsedData = data ? JSON.parse(data) : {};

    return {
      project: this.project,
      projectData: parsedData,
      products: this.projectProducts,
      finalPayment: this.finalPayment,
      customerFeedback: this.customerFeedback,
      createdAt: this.project.get('createdAt'),
      updatedAt: this.project.get('updatedAt')
    };
  }

  /**
   * 生成项目摘要
   */
  generateSummary(data: any): string {
    const project = data.project;
    const products = data.products || [];
    const feedback = data.customerFeedback;

    let summary = `项目于${this.formatDate(project.get('createdAt'))}启动，`;

    if (products.length > 1) {
      summary += `涵盖${products.length}个空间场景，`;
    }

    if (feedback?.overallRating) {
      summary += `客户综合评分${feedback.overallRating}/5.0，`;
    }

    summary += `整体执行情况良好。`;

    return summary;
  }

  /**
   * 生成项目亮点
   */
  generateHighlights(data: any): string[] {
    const highlights: string[] = [];
    const feedback = data.customerFeedback;

    if (feedback?.dimensionRatings) {
      const ratings = feedback.dimensionRatings;
      if (ratings.designQuality >= 4) highlights.push('设计质量获得客户高度认可');
      if (ratings.serviceAttitude >= 4) highlights.push('服务态度专业热情');
      if (ratings.deliveryTimeliness >= 4) highlights.push('交付及时，进度把控良好');
    }

    if (feedback?.wouldRecommend) {
      highlights.push('客户愿意推荐给他人');
    }

    if (highlights.length === 0) {
      highlights.push('项目按计划完成各项交付');
    }

    return highlights;
  }

  /**
   * 提取挑战
   */
  extractChallenges(data: any): string[] {
    const challenges: string[] = [];
    const feedback = data.customerFeedback;

    if (feedback?.dimensionRatings) {
      const ratings = feedback.dimensionRatings;
      if (ratings.deliveryTimeliness < 3) challenges.push('交付进度存在延迟');
      if (ratings.communication < 3) challenges.push('沟通协作需要加强');
    }

    if (this.finalPayment.status === 'pending') {
      challenges.push('尾款回收存在挑战');
    }

    if (challenges.length === 0) {
      challenges.push('项目执行过程中遇到常规挑战，均已妥善解决');
    }

    return challenges;
  }

  /**
   * 生成经验教训
   */
  generateLessons(data: any): string[] {
    return [
      '需求确认阶段应更加详细，减少后期修改',
      '加强与客户的沟通频率，及时同步进度',
      '预留合理的缓冲时间应对突发情况',
      '建立更完善的质量检查机制'
    ];
  }

  /**
   * 生成改进建议
   */
  generateRecommendations(data: any): string[] {
    return [
      '优化设计流程，提升首次通过率',
      '建立客户反馈快速响应机制',
      '加强团队协作和知识分享',
      '完善项目管理工具和流程'
    ];
  }

  /**
   * 分析效率
   */
  analyzeEfficiency(data: any): ProjectRetrospective['efficiencyAnalysis'] {
    // 模拟效率分析
    const overallScore = 82;
    const grade = overallScore >= 90 ? 'A' : overallScore >= 80 ? 'B' : overallScore >= 70 ? 'C' : overallScore >= 60 ? 'D' : 'F';

    return {
      overallScore,
      grade,
      timeEfficiency: {
        score: 85,
        plannedDuration: 30,
        actualDuration: 32,
        variance: 6.7
      },
      qualityEfficiency: {
        score: 90,
        firstPassYield: 90,
        revisionRate: 10,
        issueCount: 2
      },
      resourceUtilization: {
        score: 80,
        teamSize: 3,
        workload: 85,
        idleRate: 5
      },
      stageMetrics: [
        {
          stage: '需求确认',
          plannedDays: 5,
          actualDays: 5,
          efficiency: 100,
          status: 'on-time'
        },
        {
          stage: '下单洽谈',
          plannedDays: 3,
          actualDays: 3,
          efficiency: 100,
          status: 'on-time'
        },
        {
          stage: '交付执行',
          plannedDays: 15,
          actualDays: 17,
          efficiency: 88,
          status: 'delayed',
          delayReason: '客户需求调整'
        },
        {
          stage: '售后归档',
          plannedDays: 7,
          actualDays: 7,
          efficiency: 100,
          status: 'on-time'
        }
      ],
      bottlenecks: [
        {
          stage: '交付执行',
          issue: '实际耗时17天，超出计划13%',
          severity: 'medium',
          suggestion: '建立更严格的需求变更管理流程'
        }
      ]
    };
  }

  /**
   * 分析团队绩效
   */
  analyzeTeamPerformance(data: any): ProjectRetrospective['teamPerformance'] {
    return {
      overallScore: 85,
      members: [
        {
          memberId: '1',
          memberName: '设计师A',
          role: '主设计师',
          scores: {
            workload: 90,
            quality: 88,
            efficiency: 85,
            collaboration: 92,
            innovation: 80,
            overall: 87
          },
          timeDistribution: {
            design: 60,
            communication: 20,
            revision: 15,
            admin: 5
          },
          contributions: ['完成主要设计方案', '协调客户沟通'],
          strengths: ['设计能力出色', '沟通协作良好'],
          improvements: ['可提升时间管理能力'],
          ranking: 1
        }
      ]
    };
  }

  /**
   * 分析财务
   */
  analyzeFinancial(data: any): ProjectRetrospective['financialAnalysis'] {
    return {
      budgetVariance: 5,
      profitMargin: 25,
      costBreakdown: {
        labor: 60,
        materials: 20,
        overhead: 15,
        revisions: 5
      },
      revenueAnalysis: {
        contracted: 100000,
        received: 80000,
        pending: 20000
      }
    };
  }

  /**
   * 分析满意度
   */
  analyzeSatisfaction(data: any): ProjectRetrospective['satisfactionAnalysis'] {
    const feedback = data.customerFeedback;
    const overallScore = feedback?.overallRating ? feedback.overallRating * 20 : 0;

    return {
      overallScore,
      nps: feedback?.recommendationWillingness?.score ? (feedback.recommendationWillingness.score - 5) * 20 : 0,
      dimensions: [
        {
          name: 'designQuality',
          label: '设计质量',
          score: feedback?.dimensionRatings?.designQuality * 20 || 0,
          benchmark: 75,
          variance: (feedback?.dimensionRatings?.designQuality * 20 || 0) - 75
        },
        {
          name: 'serviceAttitude',
          label: '服务态度',
          score: feedback?.dimensionRatings?.serviceAttitude * 20 || 0,
          benchmark: 80,
          variance: (feedback?.dimensionRatings?.serviceAttitude * 20 || 0) - 80
        },
        {
          name: 'deliveryTimeliness',
          label: '交付及时性',
          score: feedback?.dimensionRatings?.deliveryTimeliness * 20 || 0,
          benchmark: 70,
          variance: (feedback?.dimensionRatings?.deliveryTimeliness * 20 || 0) - 70
        }
      ],
      improvementAreas: []
    };
  }

  /**
   * 识别风险和机会
   */
  identifyRisksAndOpportunities(data: any): ProjectRetrospective['risksAndOpportunities'] {
    return {
      risks: [
        {
          type: 'timeline',
          description: '后续项目可能面临交付延期风险',
          likelihood: 30,
          impact: 60,
          severity: 'medium',
          mitigation: '加强需求确认和进度管理'
        }
      ],
      opportunities: [
        {
          area: '客户推荐',
          description: '客户满意度高，可争取转介绍',
          potential: 80,
          effort: 20,
          priority: 'high',
          actionPlan: '主动询问客户推荐意向'
        }
      ]
    };
  }

  /**
   * 生成Product复盘
   */
  generateProductRetrospectives(data: any): ProjectRetrospective['productRetrospectives'] {
    return this.projectProducts.map(product => ({
      productId: product.id,
      productName: product.name || this.productSpaceService.getProductTypeName(product.type),
      performance: 85,
      plannedDays: 10,
      actualDays: 11,
      issues: ['部分细节需要调整'],
      recommendations: ['加强前期规划']
    }));
  }

  /**
   * 生成对比分析
   */
  generateBenchmarking(data: any): ProjectRetrospective['benchmarking'] {
    return {
      comparisonToHistory: {
        averageEfficiency: 78,
        currentEfficiency: 82,
        ranking: 12,
        percentile: 75
      },
      industryBenchmark: {
        timelineVariance: 5,
        satisfactionScore: 85,
        profitMargin: 25
      }
    };
  }

  /**
   * 归档项目
   */
  async archiveProject() {
    if (!this.canEdit || !this.project) return;

    if (!this.projectRetrospective) {
      alert('请先生成项目复盘');
      return;
    }

    if (!this.customerFeedback.submitted) {
      alert('请先提交客户评价');
      return;
    }

    if (this.finalPayment.status !== 'completed') {
      if (!confirm('尾款尚未结清，确定要归档吗？')) return;
    }

    try {
      this.saving = true;
      this.cdr.markForCheck();

      this.archiveStatus = {
        archived: true,
        archiveTime: new Date(),
        archivedBy: {
          id: this.currentUser!.id!,
          name: this.currentUser!.get('name') || ''
        }
      };

      await this.saveDraft();
      this.calculateStats();
      this.cdr.markForCheck();
      alert('项目归档成功');
    } catch (error: any) {
      console.error('归档失败:', error);
      alert('归档失败: ' + (error?.message || '未知错误'));
    } finally {
      this.saving = false;
      this.cdr.markForCheck();
    }
  }

  /**
   * 保存草稿
   */
  async saveDraft() {
    if (!this.project) return;

    try {
      const data = this.project.get('data');
      const parsedData = data ? JSON.parse(data) : {};

      parsedData.finalPayment = this.finalPayment;
      parsedData.customerFeedback = this.customerFeedback;
      parsedData.projectRetrospective = this.projectRetrospective;
      parsedData.archiveStatus = this.archiveStatus;

      this.project.set('data', JSON.stringify(parsedData));
      await this.project.save();
    } catch (error) {
      console.error('保存失败:', error);
      throw error;
    }
  }

  /**
   * 获取支付状态文本
   */
  getPaymentStatusText(): string {
    switch (this.finalPayment.status) {
      case 'completed': return '已结清';
      case 'partial': return '部分支付';
      case 'overdue': return '已逾期';
      default: return '待支付';
    }
  }

  /**
   * 获取支付状态颜色
   */
  getPaymentStatusColor(): string {
    switch (this.finalPayment.status) {
      case 'completed': return 'success';
      case 'partial': return 'warning';
      case 'overdue': return 'danger';
      default: return 'medium';
    }
  }

  /**
   * 格式化货币
   */
  formatCurrency(amount: number): string {
    return `¥${amount.toLocaleString('zh-CN')}`;
  }

  /**
   * 格式化日期
   */
  formatDate(date: Date | string): string {
    if (!date) return '';
    const d = typeof date === 'string' ? new Date(date) : date;
    return d.toLocaleDateString('zh-CN');
  }

  /**
   * 获取Product评分
   */
  getProductRating(productId: string): number {
    const feedback = this.customerFeedback.productFeedbacks.find(f => f.productId === productId);
    return feedback?.rating || 0;
  }

  /**
   * 获取阶段状态文本
   */
  getStageStatusText(status: string): string {
    switch (status) {
      case 'on-time': return '按时';
      case 'delayed': return '延期';
      default: return '提前';
    }
  }

  /**
   * 获取阶段状态颜色
   */
  getStageStatusColor(status: string): string {
    switch (status) {
      case 'on-time': return 'success';
      case 'delayed': return 'danger';
      default: return 'primary';
    }
  }

  /**
   * 获取瓶颈严重程度文本
   */
  getBottleneckSeverityText(severity: string): string {
    switch (severity) {
      case 'high': return '严重';
      case 'medium': return '一般';
      default: return '轻微';
    }
  }

  /**
   * 获取瓶颈严重程度颜色
   */
  getBottleneckSeverityColor(severity: string): string {
    switch (severity) {
      case 'high': return 'danger';
      case 'medium': return 'warning';
      default: return 'medium';
    }
  }

  /**
   * 获取瓶颈严重程度图标
   */
  getBottleneckSeverityIcon(severity: string): string {
    switch (severity) {
      case 'high': return '⚠️';
      case 'medium': return '⚡';
      default: return 'ℹ️';
    }
  }

  /**
   * 根据productId获取Product名称
   */
  getProductNameById(productId: string): string {
    const item = this.finalPayment.productBreakdown.find(p => p.productId === productId);
    return item?.productName || '';
  }

  /**
   * 获取OCR置信度文本
   */
  getOCRConfidenceText(confidence: number): string {
    return (confidence * 100).toFixed(0) + '%';
  }
}
