import { Component, signal, ViewChild, ElementRef, AfterViewInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';
import { MatInputModule } from '@angular/material/input';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatChipsModule } from '@angular/material/chips';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatTooltipModule } from '@angular/material/tooltip';
import { FormsModule } from '@angular/forms';
import * as echarts from 'echarts';

interface ResumeAnalysis {
  id: string;
  fileName: string;
  uploadTime: Date;
  status: 'processing' | 'completed' | 'failed';
  analysisResult?: {
    recommendation: '推荐' | '不推荐' | '待定';
    reason: string;
    coreSkills: Array<{
      name: string;
      score: number;
      matched: boolean;
    }>;
    screeningInfo: {
      education: string;
      workYears: string;
      coreSkills: string[];
    };
  };
}

interface RecruitmentStage {
  stage: string;
  result: string;
  evaluator: string;
  evaluationTime: Date;
  comments?: string;
}

interface PerformanceMetric {
  department: string;
  positionLevel: string;
  projectCompletionRate: number;
  excellentWorkRate: number;
  customerSatisfaction: number;
  overdueRate: number;
  trainingCompletionRate: number;
}

interface TurnoverAnalysis {
  category: string;
  reasons: Array<{
    reason: string;
    count: number;
    percentage: number;
  }>;
}

@Component({
  selector: 'app-recruitment-performance',
  standalone: true,
  imports: [
    CommonModule,
    MatButtonModule,
    MatIconModule,
    MatCardModule,
    MatFormFieldModule,
    MatSelectModule,
    MatInputModule,
    MatProgressBarModule,
    MatChipsModule,
    MatExpansionModule,
    MatProgressSpinnerModule,
    MatTooltipModule,
    FormsModule
  ],
  templateUrl: './recruitment-performance.html',
  styleUrls: ['./recruitment-performance.scss']
})
export class RecruitmentPerformanceComponent implements AfterViewInit, OnDestroy {
  // 页面状态管理
  activeTab = signal(0);
  
  // AI简历分析相关
  resumeAnalyses = signal<ResumeAnalysis[]>([]);
  selectedResume = signal<ResumeAnalysis | null>(null);
  
  // 招聘流程跟踪
  recruitmentStages = signal<RecruitmentStage[]>([]);
  newStage = {
    stage: '简历初筛',
    result: '通过',
    evaluator: '',
    comments: ''
  };

  // 招聘四阶段定义
  recruitmentPhases = [
    {
      name: '简历初筛',
      description: '筛选符合基本要求的简历',
      icon: 'description',
      color: '#2196F3'
    },
    {
      name: '面试评估',
      description: '技能和文化匹配度评估',
      icon: 'person',
      color: '#FF9800'
    },
    {
      name: '入职评定',
      description: '最终录用决定和入职准备',
      icon: 'how_to_reg',
      color: '#4CAF50'
    },
    {
      name: '试用期跟踪',
      description: '试用期表现跟踪和评估',
      icon: 'track_changes',
      color: '#9C27B0'
    }
  ];

  // 招聘统计数据
  recruitmentStats = signal({
    totalCandidates: 156,
    resumeScreened: 89,
    interviewed: 34,
    hired: 12,
    onProbation: 8
  });
  
  // ECharts 实例
  @ViewChild('turnoverPieChart', { static: false }) turnoverPieChart!: ElementRef;
  @ViewChild('categoryPieChart', { static: false }) categoryPieChart!: ElementRef;
  private turnoverChart: echarts.ECharts | null = null;
  private categoryChart: echarts.ECharts | null = null;
  
  // 筛选表单数据
  filterForm = {
    department: '',
    dateRange: '',
    position: '',
    performanceLevel: ''
  };
  filterDepartment = '';
  filterPositionLevel = '';
  filterHireDate = '';
  filterTurnoverDepartment = '';
  filterTurnoverDateRange = '';

  // 筛选选项
  departments = ['技术部', '产品部', '设计部', '市场部', '销售部', '人事部'];
  positions = ['初级', '中级', '高级', '专家', '主管', '经理'];
  performanceLevels = ['优秀', '良好', '一般', '待改进'];
  dateRanges = [
    { value: 'current_month', label: '本月' },
    { value: 'last_month', label: '上月' },
    { value: 'current_quarter', label: '本季度' },
    { value: 'last_quarter', label: '上季度' },
    { value: 'current_year', label: '本年度' },
    { value: 'last_year', label: '去年' }
  ];
  
  // 绩效统计数据
  performanceMetrics = signal<PerformanceMetric[]>([
    {
      department: '设计部',
      positionLevel: '高级',
      projectCompletionRate: 95,
      excellentWorkRate: 88,
      customerSatisfaction: 92,
      overdueRate: 5,
      trainingCompletionRate: 100
    },
    {
      department: '设计部',
      positionLevel: '中级',
      projectCompletionRate: 87,
      excellentWorkRate: 75,
      customerSatisfaction: 85,
      overdueRate: 12,
      trainingCompletionRate: 95
    },
    {
      department: '技术部',
      positionLevel: '高级',
      projectCompletionRate: 92,
      excellentWorkRate: 82,
      customerSatisfaction: 89,
      overdueRate: 8,
      trainingCompletionRate: 98
    },
    {
      department: '技术部',
      positionLevel: '中级',
      projectCompletionRate: 85,
      excellentWorkRate: 70,
      customerSatisfaction: 82,
      overdueRate: 15,
      trainingCompletionRate: 90
    },
    {
      department: '市场部',
      positionLevel: '高级',
      projectCompletionRate: 90,
      excellentWorkRate: 78,
      customerSatisfaction: 88,
      overdueRate: 10,
      trainingCompletionRate: 96
    }
  ]);
  
  // 离职分析数据
  turnoverAnalyses = signal<TurnoverAnalysis[]>([
    {
      category: '新人离职',
      reasons: [
        { reason: '工作压力大', count: 12, percentage: 35 },
        { reason: '薪资不满', count: 8, percentage: 24 },
        { reason: '发展空间有限', count: 7, percentage: 21 },
        { reason: '团队氛围', count: 4, percentage: 12 },
        { reason: '其他', count: 3, percentage: 8 }
      ]
    },
    {
      category: '资深员工离职',
      reasons: [
        { reason: '职业发展', count: 15, percentage: 42 },
        { reason: '薪资待遇', count: 10, percentage: 28 },
        { reason: '工作内容', count: 6, percentage: 17 },
        { reason: '管理问题', count: 3, percentage: 8 },
        { reason: '其他', count: 2, percentage: 5 }
      ]
    }
  ]);

  ngAfterViewInit() {
    // 初始化模拟数据
    this.initializeMockData();
    
    // 延迟初始化图表，确保DOM已渲染
    setTimeout(() => {
      this.initializeCharts();
    }, 100);
  }

  ngOnDestroy() {
    // 清理图表实例
    if (this.turnoverChart) {
      this.turnoverChart.dispose();
    }
    if (this.categoryChart) {
      this.categoryChart.dispose();
    }
  }

  private initializeMockData() {
    // 模拟简历分析数据
    const mockAnalyses: ResumeAnalysis[] = [
      {
        id: '1',
        fileName: '张三_UI设计师_简历.pdf',
        uploadTime: new Date('2024-01-15T10:30:00'),
        status: 'completed',
        analysisResult: {
          recommendation: '推荐',
          reason: '具备丰富的UI设计经验，技能匹配度高，作品质量优秀',
          coreSkills: [
            { name: 'Figma', score: 95, matched: true },
            { name: 'Sketch', score: 88, matched: true },
            { name: 'Adobe XD', score: 92, matched: true },
            { name: '用户体验设计', score: 85, matched: true },
            { name: '原型设计', score: 90, matched: true }
          ],
          screeningInfo: {
            education: '本科',
            workYears: '3-5年',
            coreSkills: ['UI设计', '交互设计', '用户体验']
          }
        }
      },
      {
        id: '2',
        fileName: '李四_前端开发_简历.pdf',
        uploadTime: new Date('2024-01-16T14:20:00'),
        status: 'completed',
        analysisResult: {
          recommendation: '待定',
          reason: '技术能力符合要求，但项目经验相对较少，建议进一步面试评估',
          coreSkills: [
            { name: 'Vue.js', score: 82, matched: true },
            { name: 'React', score: 75, matched: false },
            { name: 'TypeScript', score: 78, matched: true },
            { name: 'Node.js', score: 65, matched: false },
            { name: '前端工程化', score: 70, matched: true }
          ],
          screeningInfo: {
            education: '本科',
            workYears: '1-3年',
            coreSkills: ['Vue.js', 'JavaScript', 'CSS3']
          }
        }
      }
    ];
    
    this.resumeAnalyses.set(mockAnalyses);
    this.selectedResume.set(mockAnalyses[0]);
    
    // 模拟招聘流程数据
    const mockStages: RecruitmentStage[] = [
      {
        stage: '简历初筛',
        result: '通过',
        evaluator: '王经理',
        evaluationTime: new Date('2024-01-15T16:00:00'),
        comments: '简历质量较高，技能匹配度好'
      },
      {
        stage: '面试评估',
        result: '通过',
        evaluator: '李主管',
        evaluationTime: new Date('2024-01-18T10:00:00'),
        comments: '面试表现优秀，沟通能力强，技术功底扎实'
      }
    ];
    
    this.recruitmentStages.set(mockStages);
  }

  private initializeCharts() {
    if (this.turnoverPieChart?.nativeElement) {
      this.initTurnoverChart();
    }
    if (this.categoryPieChart?.nativeElement) {
      this.initCategoryChart();
    }
  }

  private initTurnoverChart() {
    this.turnoverChart = echarts.init(this.turnoverPieChart.nativeElement);
    
    const option = {
      title: {
        text: '总体离职原因分布',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'normal'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: ['工作压力大', '薪资不满', '发展空间有限', '职业发展', '团队氛围']
      },
      series: [
        {
          name: '离职原因',
          type: 'pie',
          radius: '50%',
          data: [
            { value: 27, name: '工作压力大' },
            { value: 18, name: '薪资不满' },
            { value: 13, name: '发展空间有限' },
            { value: 15, name: '职业发展' },
            { value: 7, name: '团队氛围' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };
    
    this.turnoverChart.setOption(option);
  }

  private initCategoryChart() {
    this.categoryChart = echarts.init(this.categoryPieChart.nativeElement);
    
    const option = {
      title: {
        text: '分类离职原因对比',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'normal'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: ['新人离职', '资深员工离职']
      },
      series: [
        {
          name: '离职类别',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          data: [
            { value: 34, name: '新人离职' },
            { value: 36, name: '资深员工离职' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };
    
    this.categoryChart.setOption(option);
  }

  // 切换标签页
  switchTab(index: number) {
    this.activeTab.set(index);
    
    // 如果切换到绩效分析页面，重新初始化图表
    if (index === 1) {
      setTimeout(() => {
        this.initializeCharts();
      }, 100);
    }
  }



  // 简历上传处理
  onResumeUpload(event: any) {
    const file = event.target.files[0];
    if (file) {
      const newAnalysis: ResumeAnalysis = {
        id: Date.now().toString(),
        fileName: file.name,
        uploadTime: new Date(),
        status: 'processing'
      };
      
      this.resumeAnalyses.update(analyses => [...analyses, newAnalysis]);
      
      // 模拟AI分析过程
      setTimeout(() => {
        this.simulateAIAnalysis(newAnalysis.id);
      }, 3000);
    }
  }

  private simulateAIAnalysis(analysisId: string) {
    this.resumeAnalyses.update(analyses => 
      analyses.map(analysis => 
        analysis.id === analysisId 
          ? {
              ...analysis,
              status: 'completed' as const,
              analysisResult: {
                recommendation: '推荐' as const,
                reason: '候选人技能匹配度较高，具备相关工作经验',
                coreSkills: [
                  { name: '专业技能', score: 85, matched: true },
                  { name: '工作经验', score: 78, matched: true },
                  { name: '学历背景', score: 90, matched: true }
                ],
                screeningInfo: {
                  education: '本科',
                  workYears: '2-3年',
                  coreSkills: ['专业技能', '沟通能力']
                }
              }
            }
          : analysis
      )
    );
  }

  // 添加招聘阶段
  addRecruitmentStage() {
    if (this.newStage.evaluator.trim()) {
      const newStageRecord: RecruitmentStage = {
        ...this.newStage,
        evaluationTime: new Date()
      };
      
      this.recruitmentStages.update(stages => [...stages, newStageRecord]);
      
      // 重置表单
      this.newStage = {
        stage: '简历初筛',
        result: '通过',
        evaluator: '',
        comments: ''
      };
    }
  }

  // 获取当前阶段状态
  getCurrentStageStatus(): string {
    const stages = this.recruitmentStages();
    if (stages.length === 0) return '未开始';
    
    const lastStage = stages[stages.length - 1];
    return `${lastStage.stage} - ${lastStage.result}`;
  }

  // 获取阶段进度
  getStageProgress(): number {
    const stages = this.recruitmentStages();
    const totalStages = 4; // 简历初筛、面试评估、入职评定、试用期跟踪
    return Math.round((stages.length / totalStages) * 100);
  }

  // 计算各阶段通过率
  getPhasePassRate(phaseName: string): number {
    const stats = this.recruitmentStats();
    switch (phaseName) {
      case '简历初筛':
        return Math.round((stats.resumeScreened / stats.totalCandidates) * 100);
      case '面试评估':
        return Math.round((stats.interviewed / stats.resumeScreened) * 100);
      case '入职评定':
        return Math.round((stats.hired / stats.interviewed) * 100);
      case '试用期跟踪':
        return Math.round((stats.onProbation / stats.hired) * 100);
      default:
        return 0;
    }
  }

  // 获取阶段候选人数量
  getPhaseCount(phaseName: string): number {
    const stats = this.recruitmentStats();
    switch (phaseName) {
      case '简历初筛':
        return stats.resumeScreened;
      case '面试评估':
        return stats.interviewed;
      case '入职评定':
        return stats.hired;
      case '试用期跟踪':
        return stats.onProbation;
      default:
        return 0;
    }
  }

  // 获取阶段状态
  getPhaseStatus(phaseName: string): 'completed' | 'in-progress' | 'pending' {
    const stages = this.recruitmentStages();
    const hasStage = stages.some(stage => stage.stage === phaseName);
    
    if (hasStage) {
      const stageIndex = this.recruitmentPhases.findIndex(phase => phase.name === phaseName);
      const currentStageIndex = this.recruitmentPhases.findIndex(phase => 
        phase.name === stages[stages.length - 1]?.stage
      );
      
      if (stageIndex < currentStageIndex) return 'completed';
      if (stageIndex === currentStageIndex) return 'in-progress';
    }
    
    return 'pending';
  }

  // 计算平均分数
  calculateAverageScore(skills: Array<{score: number}>): number {
    if (!skills || skills.length === 0) return 0;
    const total = skills.reduce((sum, skill) => sum + skill.score, 0);
    return Math.round(total / skills.length);
  }

  // 获取匹配技能数量
  getMatchedSkillsCount(analysis: ResumeAnalysis): number {
    if (!analysis.analysisResult?.coreSkills) return 0;
    return analysis.analysisResult.coreSkills.filter(skill => skill.matched).length;
  }

  // 获取部门列表
  getDepartments(): string[] {
    const departments = this.performanceMetrics().map(metric => metric.department);
    return [...new Set(departments)];
  }

  // 计算部门平均值
  calculateDepartmentAverage(department: string) {
    const deptMetrics = this.performanceMetrics().filter(metric => metric.department === department);
    
    if (deptMetrics.length === 0) {
      return {
        projectCompletionRate: 0,
        excellentWorkRate: 0,
        customerSatisfaction: 0,
        overdueRate: 0,
        trainingCompletionRate: 0
      };
    }
    
    const totals = deptMetrics.reduce((acc, metric) => ({
      projectCompletionRate: acc.projectCompletionRate + metric.projectCompletionRate,
      excellentWorkRate: acc.excellentWorkRate + metric.excellentWorkRate,
      customerSatisfaction: acc.customerSatisfaction + metric.customerSatisfaction,
      overdueRate: acc.overdueRate + metric.overdueRate,
      trainingCompletionRate: acc.trainingCompletionRate + metric.trainingCompletionRate
    }), {
      projectCompletionRate: 0,
      excellentWorkRate: 0,
      customerSatisfaction: 0,
      overdueRate: 0,
      trainingCompletionRate: 0
    });
    
    const count = deptMetrics.length;
    return {
      projectCompletionRate: Math.round(totals.projectCompletionRate / count),
      excellentWorkRate: Math.round(totals.excellentWorkRate / count),
      customerSatisfaction: Math.round(totals.customerSatisfaction / count),
      overdueRate: Math.round(totals.overdueRate / count),
      trainingCompletionRate: Math.round(totals.trainingCompletionRate / count)
    };
  }

  // 获取离职统计数据
  getTurnoverStats() {
    const allReasons = this.turnoverAnalyses().flatMap(analysis => analysis.reasons);
    const reasonMap = new Map<string, { totalCount: number; totalPercentage: number }>();
    
    allReasons.forEach(reason => {
      if (reasonMap.has(reason.reason)) {
        const existing = reasonMap.get(reason.reason)!;
        reasonMap.set(reason.reason, {
          totalCount: existing.totalCount + reason.count,
          totalPercentage: existing.totalPercentage + reason.percentage
        });
      } else {
        reasonMap.set(reason.reason, {
          totalCount: reason.count,
          totalPercentage: reason.percentage
        });
      }
    });
    
    return Array.from(reasonMap.entries()).map(([reason, data]) => ({
      reason,
      totalCount: data.totalCount,
      totalPercentage: Math.round(data.totalPercentage / 2) // 平均值
    }));
  }

  // 获取离职原因颜色
  public getReasonColor(reason: string): string {
    const colorMap: { [key: string]: string } = {
      '工作压力大': '#ff6b6b',
      '薪资不满': '#ffa726',
      '发展空间有限': '#42a5f5',
      '职业发展': '#66bb6a',
      '团队氛围': '#ab47bc',
      '工作内容': '#26c6da',
      '管理问题': '#ef5350',
      '其他': '#bdbdbd'
    };
    return colorMap[reason] || '#bdbdbd';
  }

  // 应用离职筛选
  applyTurnoverFilters() {
    // 根据筛选条件重新加载数据
    const filteredData = this.getFilteredTurnoverData();
    this.updateTurnoverCharts(filteredData);
    
    console.log('应用筛选:', {
      department: this.filterTurnoverDepartment,
      dateRange: this.filterTurnoverDateRange
    });
  }

  // 重置离职筛选
  resetTurnoverFilters() {
    this.filterTurnoverDepartment = '';
    this.filterTurnoverDateRange = '';
    
    // 重置图表数据
    this.updateTurnoverCharts();
  }

  // 获取筛选后的离职数据
  private getFilteredTurnoverData() {
    let filteredAnalyses = [...this.turnoverAnalyses()];
    
    // 根据部门筛选
    if (this.filterTurnoverDepartment) {
      // 这里可以根据实际需求添加部门筛选逻辑
      // 目前保持原数据
    }
    
    // 根据时间范围筛选
    if (this.filterTurnoverDateRange) {
      // 根据时间范围调整数据
      const multiplier = this.getTimeRangeMultiplier(this.filterTurnoverDateRange);
      filteredAnalyses = filteredAnalyses.map(analysis => ({
        ...analysis,
        reasons: analysis.reasons.map(reason => ({
          ...reason,
          count: Math.round(reason.count * multiplier),
          percentage: Math.round(reason.percentage * multiplier)
        }))
      }));
    }
    
    return filteredAnalyses;
  }

  // 获取时间范围乘数
  private getTimeRangeMultiplier(dateRange: string): number {
    switch (dateRange) {
      case 'last3months': return 0.25;
      case 'last6months': return 0.5;
      case 'lastyear': return 1;
      default: return 1;
    }
  }

  // 更新离职图表
  private updateTurnoverCharts(filteredData?: TurnoverAnalysis[]) {
    const data = filteredData || this.turnoverAnalyses();
    
    if (this.turnoverChart) {
      this.updateTurnoverPieChart(data);
    }
    
    if (this.categoryChart) {
      this.updateCategoryPieChart(data);
    }
  }

  // 更新总体离职原因饼图
  private updateTurnoverPieChart(data: TurnoverAnalysis[]) {
    const allReasons = data.flatMap(analysis => analysis.reasons);
    const reasonMap = new Map<string, number>();
    
    allReasons.forEach(reason => {
      const current = reasonMap.get(reason.reason) || 0;
      reasonMap.set(reason.reason, current + reason.count);
    });
    
    const chartData = Array.from(reasonMap.entries()).map(([name, value]) => ({
      name,
      value,
      itemStyle: {
        color: this.getReasonColor(name)
      }
    }));
    
    const option = {
      series: [{
        data: chartData
      }]
    };
    
    this.turnoverChart?.setOption(option);
  }

  // 更新分类离职饼图
  private updateCategoryPieChart(data: TurnoverAnalysis[]) {
    const chartData = data.map(analysis => {
      const totalCount = analysis.reasons.reduce((sum, reason) => sum + reason.count, 0);
      return {
        name: analysis.category,
        value: totalCount
      };
    });
    
    const option = {
      series: [{
        data: chartData
      }]
    };
    
    this.categoryChart?.setOption(option);
  }

  // 生成离职分析报告
  generateTurnoverReport() {
    const stats = this.getTurnoverStats();
    const totalTurnover = stats.reduce((sum, stat) => sum + stat.totalCount, 0);
    
    const reportData = {
      title: '离职分析报告',
      generateTime: new Date().toLocaleString(),
      summary: {
        totalTurnover,
        mainReasons: stats.slice(0, 3).map(stat => ({
          reason: stat.reason,
          count: stat.totalCount,
          percentage: stat.totalPercentage
        }))
      },
      details: this.turnoverAnalyses(),
      filters: {
        department: this.filterTurnoverDepartment || '全部',
        dateRange: this.filterTurnoverDateRange || '全部时间'
      }
    };
    
    console.log('生成离职分析报告:', reportData);
    // 这里可以实现实际的报告导出功能
  }

  // 生成绩效报告
  generatePerformanceReport() {
    const overallStats = this.calculateOverallAverage();
    const departmentStats = this.getDepartments().map(dept => ({
      department: dept,
      stats: this.calculateDepartmentAverage(dept)
    }));
    
    const reportData = {
      title: '绩效分析报告',
      generateTime: new Date().toLocaleString(),
      overall: overallStats,
      departments: departmentStats,
      filters: this.filterForm
    };
    
    console.log('生成绩效报告:', reportData);
    // 这里可以实现实际的报告导出功能
  }

  // 筛选绩效数据
  getFilteredPerformanceMetrics() {
    let filtered = this.performanceMetrics();
    
    if (this.filterForm.department) {
      filtered = filtered.filter(metric => metric.department === this.filterForm.department);
    }
    
    if (this.filterForm.position) {
      filtered = filtered.filter(metric => metric.positionLevel === this.filterForm.position);
    }
    
    if (this.filterForm.performanceLevel) {
      filtered = filtered.filter(metric => {
        const overall = this.calculateEmployeeOverall(metric);
        switch (this.filterForm.performanceLevel) {
          case '优秀': return overall >= 90;
          case '良好': return overall >= 80 && overall < 90;
          case '一般': return overall >= 70 && overall < 80;
          case '待改进': return overall < 70;
          default: return true;
        }
      });
    }
    
    return filtered;
  }

  // 计算员工综合评分
  calculateEmployeeOverall(metric: PerformanceMetric) {
    return Math.round((
      metric.projectCompletionRate + 
      metric.excellentWorkRate + 
      metric.customerSatisfaction + 
      (100 - metric.overdueRate) + 
      metric.trainingCompletionRate
    ) / 5);
  }

  // 应用筛选
  applyFilters() {
    // 重新计算筛选后的数据
    const filteredMetrics = this.getFilteredPerformanceMetrics();
    
    // 更新图表数据
    this.updateChartsWithFilteredData(filteredMetrics);
  }

  // 重置筛选
  resetFilters() {
    this.filterForm = {
      department: '',
      dateRange: '',
      position: '',
      performanceLevel: ''
    };
    this.applyFilters();
  }

  // 更新图表数据
  updateChartsWithFilteredData(filteredMetrics: PerformanceMetric[]) {
    // 这里可以根据筛选后的数据更新图表
    // 暂时保持原有逻辑
  }

  // 计算整体平均绩效
  calculateOverallAverage() {
    const metrics = this.getFilteredPerformanceMetrics();
    if (metrics.length === 0) {
      return {
        overall: 0,
        projectCompletionRate: 0,
        excellentWorkRate: 0,
        customerSatisfaction: 0,
        overdueRate: 0,
        trainingCompletionRate: 0
      };
    }
    
    const totals = metrics.reduce((acc, metric) => ({
      projectCompletionRate: acc.projectCompletionRate + metric.projectCompletionRate,
      excellentWorkRate: acc.excellentWorkRate + metric.excellentWorkRate,
      customerSatisfaction: acc.customerSatisfaction + metric.customerSatisfaction,
      overdueRate: acc.overdueRate + metric.overdueRate,
      trainingCompletionRate: acc.trainingCompletionRate + metric.trainingCompletionRate
    }), {
      projectCompletionRate: 0,
      excellentWorkRate: 0,
      customerSatisfaction: 0,
      overdueRate: 0,
      trainingCompletionRate: 0
    });
    
    const count = metrics.length;
    const overall = Math.round((
      totals.projectCompletionRate + 
      totals.excellentWorkRate + 
      totals.customerSatisfaction + 
      (100 - totals.overdueRate) + 
      totals.trainingCompletionRate
    ) / (count * 5));
    
    return {
      overall,
      projectCompletionRate: Math.round(totals.projectCompletionRate / count),
      excellentWorkRate: Math.round(totals.excellentWorkRate / count),
      customerSatisfaction: Math.round(totals.customerSatisfaction / count),
      overdueRate: Math.round(totals.overdueRate / count),
      trainingCompletionRate: Math.round(totals.trainingCompletionRate / count)
    };
  }

  // 计算离职率
  calculateTurnoverRate(): number {
    const totalEmployees = this.performanceMetrics().length;
    const totalTurnover = this.getTurnoverStats().reduce((sum, stat) => sum + stat.totalCount, 0);
    
    if (totalEmployees === 0) return 0;
    return (totalTurnover / (totalEmployees + totalTurnover)) * 100;
  }

  // 导出报表
  exportReport(templateId: string) {
    // 模拟导出报表
    console.log('导出报表:', templateId);
    // 这里可以调用后端API导出对应的报表
  }
}