import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';

// 定义设计师接口
interface Designer {
  id: string;
  name: string;
  workload: 'light' | 'medium' | 'heavy';
  capabilityScore: number;
  satisfactionScore: number;
  completedProjects: number;
  difficultProjects: number;
  skills: string[];
  performanceScore: number;
  onTimeRateScore: number;
  excellentRateScore: number;
  deductions: number;
  lowOrderReason?: string;
}

// 定义任务接口
interface Task {
  id: string;
  projectId: string;
  projectName: string;
  designerId: string;
  phase: string;
  deadline: Date;
  projectType: 'soft' | 'hard';
  priority: number;
}

// 定义721考核分布接口
interface PerformanceDistribution {
  top: Designer[];
  middle: Designer[];
  bottom: Designer[];
}

@Component({
  selector: 'app-team-management',
  templateUrl: './team-management.html',
  styleUrl: './team-management.scss',
  standalone: true,
  imports: [FormsModule, CommonModule]
})
export class TeamManagementComponent implements OnInit {
  // 数据
  designers: Designer[] = [];
  tasks: Task[] = [];
  searchTerm = '';
  filterProjectType = 'all';
  selectedQuarter = '2023-Q4';
  selectedDesignerId = '';
  selectedDesigner: Designer | null = null;
  activeScheduleTab = 'all';
  activeCapabilityTab = 'ranking';
  performanceDistribution: PerformanceDistribution = {
    top: [],
    middle: [],
    bottom: []
  };

  constructor(private router: Router) {}

  ngOnInit() {
    this.initializeMockData();
    this.calculatePerformanceDistribution();
  }

  // 初始化模拟数据
  initializeMockData() {
    // 初始化设计师数据
    this.designers = [
      {
        id: 'd1',
        name: '张三',
        workload: 'heavy',
        capabilityScore: 92,
        satisfactionScore: 95,
        completedProjects: 48,
        difficultProjects: 12,
        skills: ['现代风格', '渲染', '后期'],
        performanceScore: 91,
        onTimeRateScore: 90,
        excellentRateScore: 95,
        deductions: 0
      },
      {
        id: 'd2',
        name: '李四',
        workload: 'medium',
        capabilityScore: 88,
        satisfactionScore: 92,
        completedProjects: 35,
        difficultProjects: 8,
        skills: ['中式风格', '建模', '软装'],
        performanceScore: 87,
        onTimeRateScore: 85,
        excellentRateScore: 90,
        deductions: 2
      },
      {
        id: 'd3',
        name: '王五',
        workload: 'light',
        capabilityScore: 76,
        satisfactionScore: 85,
        completedProjects: 20,
        difficultProjects: 3,
        skills: ['北欧风格', '建模'],
        performanceScore: 78,
        onTimeRateScore: 82,
        excellentRateScore: 80,
        deductions: 1,
        lowOrderReason: '能力匹配度低，近1个月软装需求占比80%，组员擅长硬装'
      },
      {
        id: 'd4',
        name: '赵六',
        workload: 'medium',
        capabilityScore: 82,
        satisfactionScore: 88,
        completedProjects: 30,
        difficultProjects: 5,
        skills: ['工业风格', '后期', '渲染'],
        performanceScore: 84,
        onTimeRateScore: 88,
        excellentRateScore: 85,
        deductions: 3
      },
      {
        id: 'd5',
        name: '钱七',
        workload: 'heavy',
        capabilityScore: 90,
        satisfactionScore: 94,
        completedProjects: 42,
        difficultProjects: 10,
        skills: ['新中式', '渲染', '软装'],
        performanceScore: 89,
        onTimeRateScore: 92,
        excellentRateScore: 93,
        deductions: 0
      }
    ];

    // 初始化任务数据
    const today = new Date();
    this.tasks = [
      {
        id: 't1',
        projectId: 'p1',
        projectName: '现代简约客厅',
        designerId: 'd1',
        phase: '渲染',
        deadline: new Date(today.getTime() - 2 * 24 * 60 * 60 * 1000), // 2天前
        projectType: 'soft',
        priority: 1
      },
      {
        id: 't2',
        projectId: 'p2',
        projectName: '新中式卧室',
        designerId: 'd5',
        phase: '建模',
        deadline: new Date(today.getTime() + 3 * 24 * 60 * 60 * 1000), // 3天后
        projectType: 'hard',
        priority: 2
      },
      {
        id: 't3',
        projectId: 'p3',
        projectName: '北欧风格厨房',
        designerId: 'd3',
        phase: '后期',
        deadline: new Date(today.getTime() + 5 * 24 * 60 * 60 * 1000), // 5天后
        projectType: 'soft',
        priority: 3
      },
      {
        id: 't4',
        projectId: 'p4',
        projectName: '工业风办公室',
        designerId: 'd4',
        phase: '渲染',
        deadline: new Date(today.getTime() + 1 * 24 * 60 * 60 * 1000), // 1天后
        projectType: 'hard',
        priority: 1
      },
      {
        id: 't5',
        projectId: 'p5',
        projectName: '中式餐厅',
        designerId: 'd2',
        phase: '软装',
        deadline: new Date(today.getTime() - 1 * 24 * 60 * 60 * 1000), // 1天前
        projectType: 'soft',
        priority: 2
      },
      {
        id: 't6',
        projectId: 'p6',
        projectName: '现代轻奢卫生间',
        designerId: 'd1',
        phase: '建模',
        deadline: new Date(today.getTime() + 4 * 24 * 60 * 60 * 1000), // 4天后
        projectType: 'hard',
        priority: 3
      }
    ];
  }

  // 计算721绩效分布
  calculatePerformanceDistribution() {
    // 按绩效分数排序
    const sortedDesigners = [...this.designers].sort((a, b) => b.performanceScore - a.performanceScore);
    const total = sortedDesigners.length;
    const topCount = Math.ceil(total * 0.2);
    const bottomCount = Math.floor(total * 0.1);

    this.performanceDistribution = {
      top: sortedDesigners.slice(0, topCount),
      middle: sortedDesigners.slice(topCount, total - bottomCount),
      bottom: sortedDesigners.slice(total - bottomCount)
    };
  }

  // 获取筛选后的设计师
  get filteredDesigners() {
    return this.designers.filter(designer => 
      designer.name.toLowerCase().includes(this.searchTerm.toLowerCase())
    );
  }

  // 获取设计师的任务
  getDesignerTasks(designerId: string): Task[] {
    let filtered = this.tasks.filter(task => task.designerId === designerId);
    
    // 根据项目类型筛选
    if (this.filterProjectType !== 'all') {
      filtered = filtered.filter(task => task.projectType === this.filterProjectType);
    }
    
    // 按优先级和截止日期排序
    return filtered.sort((a, b) => {
      if (a.priority !== b.priority) {
        return a.priority - b.priority;
      }
      return a.deadline.getTime() - b.deadline.getTime();
    });
  }

  // 获取超期任务
  getOverdueTasks(): Task[] {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    let overdueTasks = this.tasks.filter(task => {
      const taskDate = new Date(task.deadline);
      taskDate.setHours(0, 0, 0, 0);
      return taskDate < today;
    });
    
    // 根据项目类型筛选
    if (this.filterProjectType !== 'all') {
      overdueTasks = overdueTasks.filter(task => task.projectType === this.filterProjectType);
    }
    
    // 按超期天数排序
    return overdueTasks.sort((a, b) => this.getOverdueDays(a) - this.getOverdueDays(b));
  }

  // 获取超期天数
  getOverdueDays(task: Task): number {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const taskDate = new Date(task.deadline);
    taskDate.setHours(0, 0, 0, 0);
    
    const diffTime = Math.abs(today.getTime() - taskDate.getTime());
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    
    return diffDays;
  }

  // 判断任务是否超期
  isTaskOverdue(task: Task): boolean {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const taskDate = new Date(task.deadline);
    taskDate.setHours(0, 0, 0, 0);
    
    return taskDate < today;
  }

  // 获取工作量等级的CSS类名
  getWorkloadClass(workload: string): string {
    return workload;
  }

  // 获取工作量等级的文本
  getWorkloadText(workload: string): string {
    switch (workload) {
      case 'light': return '空闲';
      case 'medium': return '中等';
      case 'heavy': return '繁忙';
      default: return '未知';
    }
  }

  // 根据能力分值排序设计师
  getDesignersByCapability(): Designer[] {
    return [...this.designers].sort((a, b) => b.capabilityScore - a.capabilityScore);
  }

  // 根据满意度排序设计师
  getDesignersBySatisfaction(): Designer[] {
    return [...this.designers].sort((a, b) => b.satisfactionScore - a.satisfactionScore);
  }

  // 获取排名
  getRank(designerId: string): number {
    const sorted = this.getDesignersByCapability();
    return sorted.findIndex(d => d.id === designerId) + 1;
  }

  // 获取满意度排名
  getSatisfactionRank(designerId: string): number {
    const sorted = this.getDesignersBySatisfaction();
    return sorted.findIndex(d => d.id === designerId) + 1;
  }

  // 获取设计师姓名
  getDesignerName(designerId: string): string {
    const designer = this.designers.find(d => d.id === designerId);
    return designer ? designer.name : '未知';
  }

  // 获取设计师技能
  getDesignerSkills(designer: Designer): string {
    return designer.skills.join(', ');
  }

  // 获取雷达图点坐标
  getRadarPoints(designer: Designer): string {
    // 简化实现，实际项目中应使用专业的图表库
    const centerX = 150;
    const centerY = 150;
    const maxRadius = 120;
    
    // 假设设计师各能力维度得分
    const modelingScore = 85; // 建模能力
    const renderingScore = 90; // 渲染能力
    const softDecorationScore = 75; // 软装能力
    const communicationScore = 88; // 沟通能力
    
    // 计算各点坐标
    const modelingX = centerX + (modelingScore / 100) * maxRadius;
    const modelingY = centerY - (modelingScore / 100) * maxRadius;
    
    const renderingX = centerX + (renderingScore / 100) * maxRadius;
    const renderingY = centerY;
    
    const softDecorationX = centerX;
    const softDecorationY = centerY + (softDecorationScore / 100) * maxRadius;
    
    const communicationX = centerX - (communicationScore / 100) * maxRadius;
    const communicationY = centerY;
    
    return `${modelingX},${modelingY} ${renderingX},${renderingY} ${softDecorationX},${softDecorationY} ${communicationX},${communicationY}`;
  }

  // 获取头部绩效人员
  getTopPerformers(): Designer[] {
    return this.performanceDistribution.top;
  }

  // 获取中部绩效人员
  getMiddlePerformers(): Designer[] {
    return this.performanceDistribution.middle;
  }

  // 获取尾部绩效人员
  getBottomPerformers(): Designer[] {
    return this.performanceDistribution.bottom;
  }

  // 查看项目详情
  viewProjectDetails(projectId: string): void {
    // 改为复用设计师项目详情（组长上下文），具备审核/同步权限
    this.router.navigate(['/team-leader/project-detail', projectId]);
  }

  // 调整任务优先级
  adjustTaskPriority(taskId: string): void {
    const task = this.tasks.find(t => t.id === taskId);
    if (task) {
      // 在实际项目中，这里应该弹出一个对话框让用户选择新的优先级
      // 这里简单地循环切换优先级
      task.priority = task.priority % 3 + 1;
      alert(`任务优先级已调整为: ${task.priority}`);
    }
  }

  // 调整任务截止日期
  adjustTaskDeadline(taskId: string): void {
    const task = this.tasks.find(t => t.id === taskId);
    if (task) {
      // 在实际项目中，这里应该弹出一个日期选择器让用户选择新的截止日期
      // 这里简单地将截止日期延长3天
      const newDeadline = new Date(task.deadline);
      newDeadline.setDate(newDeadline.getDate() + 3);
      task.deadline = newDeadline;
      alert(`任务截止日期已调整为: ${newDeadline.toLocaleDateString()}`);
    }
  }

  // 设计师选择变更
  onDesignerChange(): void {
    if (this.selectedDesignerId) {
      this.selectedDesigner = this.designers.find(d => d.id === this.selectedDesignerId) || null;
    } else {
      this.selectedDesigner = null;
    }
  }

  // 季度选择变更
  onQuarterChange(): void {
    // 在实际项目中，这里应该根据选择的季度加载对应的绩效数据
    // 这里简单地重新计算绩效分布
    this.calculatePerformanceDistribution();
  }

  // 生成考核报告
  generateReport(): void {
    // 在实际项目中，这里应该生成并下载考核报告
    alert(`已生成${this.selectedQuarter}考核报告`);
  }

  // 查看绩效报告
  viewPerformanceReport(designerId: string): void {
    // 在实际项目中，这里应该显示该设计师的详细绩效报告
    const designer = this.designers.find(d => d.id === designerId);
    if (designer) {
      alert(`查看${designer.name}的绩效报告`);
    }
  }

  // 同步至人事系统
  syncToHR(designerId: string): void {
    // 在实际项目中，这里应该调用API将绩效数据同步至人事系统
    const designer = this.designers.find(d => d.id === designerId);
    if (designer) {
      alert(`${designer.name}的绩效数据已同步至人事系统`);
    }
  }

  // 查看晋级条件
  showPromotionCriteria(): void {
    alert('头部20%员工可获得晋级机会，具体条件：\n1. 绩效分数≥90分\n2. 无重大客户投诉\n3. 连续2个季度保持头部20%');
  }

  // 查看提升建议
  showImprovementSuggestions(): void {
    alert('中部70%员工提升建议：\n1. 参加技能培训课程\n2. 多与优秀员工交流学习\n3. 针对薄弱环节进行专项练习');
  }

  // 查看整改计划
  showRectificationPlan(): void {
    alert('尾部10%员工整改计划：\n1. 制定个性化提升计划\n2. 每周提交学习进度\n3. 1个月后进行重新评估，仍未达标者将进行转岗或其他处理');
  }
}
