import { Component, OnInit, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { MatCardModule } from '@angular/material/card';
import { MatButtonModule } from '@angular/material/button';
import { MatTabsModule } from '@angular/material/tabs';
import { MatIconModule } from '@angular/material/icon';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatChipsModule } from '@angular/material/chips';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatBadgeModule } from '@angular/material/badge';
import { DragDropModule, CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { Chart, ChartConfiguration, registerables } from 'chart.js';
import { trigger, state, style, transition, animate } from '@angular/animations';

// 数据模型定义
export interface TodoItem {
  id: number;
  title: string;
  description: string;
  priority: 'high' | 'medium' | 'low';
  status: 'pending' | 'completed' | 'in_progress';
  type: 'resume' | 'onboarding' | 'promotion' | 'resignation';
}

export interface RankDistribution {
  junior: number;
  intermediate: number;
  senior: number;
}

export interface MonthlyData {
  month: string;
  hired: number;
  left: number;
  notes?: string;
}

export interface DepartmentPerformance {
  department: string;
  completionRate: number;
  excellentWorkRate: number;
  satisfactionRate: number;
  overdueRate: number;
}

export interface PromotionRule {
  id: number;
  title: string;
  description: string;
  conditions: string[];
}

export interface PromotionSuggestion {
  employeeId: number;
  employeeName: string;
  currentRank: string;
  suggestedRank: string;
  reasons: string[];
  status: 'pending' | 'approved' | 'rejected';
}

export interface OnboardingCheckpoint {
  id: number;
  title: string;
  description: string;
  dueDate: Date;
  completed: boolean;
  interviewTemplate: string[];
}

@Component({
  selector: 'app-hr-dashboard',
  standalone: true,
  imports: [
    CommonModule,
    RouterModule,
    MatCardModule,
    MatButtonModule,
    MatTabsModule,
    MatIconModule,
    MatCheckboxModule,
    MatChipsModule,
    MatProgressBarModule,
    MatBadgeModule,
    DragDropModule
  ],
  templateUrl: './dashboard.html',
  styleUrls: ['./dashboard.scss'],
  animations: [
    trigger('slideInOut', [
      transition(':enter', [
        style({ height: '0', opacity: 0, overflow: 'hidden' }),
        animate('300ms ease-in-out', style({ height: '*', opacity: 1 }))
      ]),
      transition(':leave', [
        animate('300ms ease-in-out', style({ height: '0', opacity: 0, overflow: 'hidden' }))
      ])
    ])
  ]
})
export class Dashboard implements OnInit, AfterViewInit {
  @ViewChild('pieChart', { static: false }) pieChartRef!: ElementRef<HTMLCanvasElement>;
  @ViewChild('lineChart', { static: false }) lineChartRef!: ElementRef<HTMLCanvasElement>;
  @ViewChild('radarChart', { static: false }) radarChartRef!: ElementRef<HTMLCanvasElement>;
  
  private pieChart!: Chart;
  private lineChart!: Chart;
  private radarChart!: Chart;
  // 当前激活的标签页
  activeTab: 'visualization' | 'promotion' | 'onboarding' = 'visualization';
  
  // 待办事项是否展开
  isTodoExpanded = false;
  
  // 当前页面
  currentPage: string = 'dashboard';
  
  // 待办事项展开状态
  showTodoList: boolean = false;

  // 待办事项列表（用于右侧展示）
  todoList = [
    {
      id: 1,
      title: '简历初筛',
      description: '筛选新收到的设计师简历',
      priority: 'high',
      dueDate: '2024-01-25'
    },
    {
      id: 2,
      title: '入职评定',
      description: '完成新员工入职评定表',
      priority: 'medium',
      dueDate: '2024-01-28'
    },
    {
      id: 3,
      title: '晋升审核',
      description: '审核中级设计师晋升申请',
      priority: 'high',
      dueDate: '2024-01-30'
    },
    {
      id: 4,
      title: '离职面谈',
      description: '安排资深设计师离职面谈',
      priority: 'medium',
      dueDate: '2024-02-02'
    }
  ];
  
  // 模拟数据
  todoItems: TodoItem[] = [
    {
      id: 1,
      title: '简历初筛',
      description: '筛选新收到的设计师简历',
      priority: 'high',
      status: 'pending',
      type: 'resume'
    },
    {
      id: 2,
      title: '入职评定',
      description: '完成新员工入职评定表',
      priority: 'medium',
      status: 'pending',
      type: 'onboarding'
    },
    {
      id: 3,
      title: '晋升审核',
      description: '审核中级设计师晋升申请',
      priority: 'high',
      status: 'pending',
      type: 'promotion'
    },
    {
      id: 4,
      title: '离职面谈',
      description: '安排资深设计师离职面谈',
      priority: 'medium',
      status: 'pending',
      type: 'resignation'
    }
  ];

  // 职级分布数据
  rankDistribution = [
    { level: '初级设计师', count: 15, percentage: 45, color: '#4CAF50' },
    { level: '中级设计师', count: 12, percentage: 36, color: '#FF9800' },
    { level: '高级设计师', count: 6, percentage: 19, color: '#2196F3' }
  ];

  monthlyHireData: MonthlyData[] = [
    { month: '10月', hired: 8, left: 3, notes: '秋季招聘高峰' },
    { month: '11月', hired: 5, left: 2, notes: '' },
    { month: '12月', hired: 3, left: 4, notes: '年底离职高峰' },
    { month: '1月', hired: 10, left: 1, notes: '新年新气象' },
    { month: '2月', hired: 6, left: 2, notes: '' },
    { month: '3月', hired: 12, left: 3, notes: '春季招聘启动' }
  ];

  // 关键节点数据
  keyNotes = [
    { month: '3月', description: '入职10人：因春季招聘' },
    { month: '5月', description: '离职5人：因项目不饱和' },
    { month: '8月', description: '入职15人：暑期实习转正' },
    { month: '12月', description: '离职8人：年底跳槽高峰' }
  ];

  // 关键岗位空缺数据
  keyVacancies = [
    { position: '高级UI设计师', count: 2, priority: 'high', duration: 45 },
    { position: '3D建模师', count: 1, priority: 'medium', duration: 20 },
    { position: '前端开发工程师', count: 1, priority: 'medium', duration: 15 },
    { position: '产品经理', count: 1, priority: 'high', duration: 60 }
  ];

  // 新人列表数据
  newbieList = [
    { id: 1, name: '张三', position: 'UI设计师', joinDate: '2024-01-15', progress: 75 },
    { id: 2, name: '李四', position: '前端开发', joinDate: '2024-01-20', progress: 60 },
    { id: 3, name: '王五', position: '3D建模师', joinDate: '2024-02-01', progress: 40 }
  ];

  departmentPerformance: DepartmentPerformance[] = [
    {
      department: 'UI设计部',
      completionRate: 92,
      excellentWorkRate: 78,
      satisfactionRate: 88,
      overdueRate: 8
    },
    {
      department: '3D建模部', 
      completionRate: 85,
      excellentWorkRate: 82,
      satisfactionRate: 90,
      overdueRate: 15
    },
    {
      department: '前端开发部',
      completionRate: 88,
      excellentWorkRate: 75,
      satisfactionRate: 85,
      overdueRate: 12
    }
  ];

  promotionRules: PromotionRule[] = [
    {
      id: 1,
      title: '初级→中级晋升标准',
      description: '设计师晋升中级标准',
      conditions: [
        '连续3个月优秀作品率超过80%',
        '逾期率低于5%',
        '客户满意度评分4.5以上',
        '至少完成12个主要项目'
      ]
    },
    {
      id: 2,
      title: '中级→高级晋升标准',
      description: '设计师晋升高级标准',
      conditions: [
        '连续6个月优秀作品率超过85%',
        '逾期率低于3%',
        '客户满意度评分4.8以上',
        '带领过至少2个大型项目',
        '有 mentorship 经验'
      ]
    }
  ];

  promotionSuggestions: PromotionSuggestion[] = [
    {
      employeeId: 1001,
      employeeName: '张三',
      currentRank: '初级设计师',
      suggestedRank: '中级设计师',
      reasons: [
        '连续3个月优秀作品率85%',
        '逾期率仅2%',
        '客户满意度4.7分',
        '已完成15个主要项目'
      ],
      status: 'pending'
    },
    {
      employeeId: 1002,
      employeeName: '李四',
      currentRank: '中级设计师',
      suggestedRank: '高级设计师',
      reasons: [
        '连续6个月优秀作品率88%',
        '逾期率1.5%',
        '客户满意度4.9分',
        '成功带领3个大型项目'
      ],
      status: 'pending'
    }
  ];

  onboardingCheckpoints: OnboardingCheckpoint[] = [
    {
      id: 1,
      title: '入职1周面谈',
      description: '了解新人工作适应情况',
      dueDate: new Date(),
      completed: false,
      interviewTemplate: [
        '工作环境是否适应？',
        '是否有不清楚的工作流程？',
        '团队沟通是否顺畅？',
        '是否需要额外的工作工具？'
      ]
    },
    {
      id: 2,
      title: '入职1个月评估',
      description: '评估新人技能掌握情况',
      dueDate: new Date(Date.now() + 21 * 24 * 60 * 60 * 1000),
      completed: false,
      interviewTemplate: [
        '主要工作技能掌握程度？',
        '遇到的最大挑战是什么？',
        '对团队文化的感受？',
        '个人职业发展期望？'
      ]
    },
    {
      id: 3,
      title: '入职3个月总结',
      description: '全面评估新人表现',
      dueDate: new Date(Date.now() + 83 * 24 * 60 * 60 * 1000),
      completed: false,
      interviewTemplate: [
        '工作成果总体评价',
        '需要改进的技能领域',
        '长期职业规划讨论',
        '转正评估准备'
      ]
    }
  ];

  ngOnInit() {
    // 注册Chart.js组件
    Chart.register(...registerables);
    // 初始化图表数据
    this.initCharts();
  }

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

  // 切换标签页
  switchTab(tab: 'visualization' | 'promotion' | 'onboarding') {
    this.activeTab = tab;
  }



  // 初始化图表（这里需要后续集成ECharts）
  private initCharts() {
    // 图表初始化逻辑将在后续实现
    console.log('初始化图表数据');
  }

  // 拖拽排序
  drop(event: CdkDragDrop<TodoItem[]>) {
    moveItemInArray(this.todoItems, event.previousIndex, event.currentIndex);
  }



  // 获取优先级颜色
  getPriorityColor(priority: string): string {
    switch (priority) {
      case 'high': return '#ff4757';
      case 'medium': return '#ffa502';
      case 'low': return '#2ed573';
      default: return '#a4b0be';
    }
  }

  // 获取空缺岗位图标
  getVacancyIcon(urgency: string): string {
    switch (urgency) {
      case 'urgent': return 'warning';
      case 'normal': return 'info';
      default: return 'help';
    }
  }

  // 获取部门颜色
  getDepartmentColor(department: string): string {
    const colors: { [key: string]: string } = {
      'UI设计部': '#2196F3',
      '3D建模部': '#4CAF50',
      '前端开发部': '#FF9800',
      '产品部': '#9C27B0'
    };
    return colors[department] || '#757575';
  }

  // 获取优先级类名
  getPriorityClass(priority: string): string {
    return `priority-${priority}`;
  }

  toggleTodoList(): void {
    this.showTodoList = !this.showTodoList;
  }

  // 获取甜甜圈图表特定选项
  private getDoughnutOptions(): any {
    return {
      cutout: '60%'
    };
  }

  // 初始化所有图表
  private initializeCharts() {
    this.initPieChart();
    this.initLineChart();
    this.initRadarChart();
  }

  // 初始化职级分布饼图
  private initPieChart() {
    if (!this.pieChartRef?.nativeElement) return;

    const ctx = this.pieChartRef.nativeElement.getContext('2d');
    if (!ctx) return;

    const config: ChartConfiguration = {
      type: 'doughnut',
      data: {
        labels: this.rankDistribution.map(item => item.level),
        datasets: [{
          data: this.rankDistribution.map(item => item.percentage),
          backgroundColor: this.rankDistribution.map(item => item.color),
          borderWidth: 0,
          hoverBorderWidth: 2,
          hoverBorderColor: '#fff'
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: false
          },
          tooltip: {
            callbacks: {
              label: (context) => {
                const label = context.label || '';
                const value = context.parsed;
                const count = this.rankDistribution[context.dataIndex].count;
                return `${label}: ${value}% (${count}人)`;
              }
            }
          }
        },
        ...(this.getDoughnutOptions())
      }
    };

    this.pieChart = new Chart(ctx, config);
  }

  // 初始化入职离职趋势折线图
  private initLineChart() {
    if (!this.lineChartRef?.nativeElement) return;

    const ctx = this.lineChartRef.nativeElement.getContext('2d');
    if (!ctx) return;

    const config: ChartConfiguration = {
      type: 'line',
      data: {
        labels: this.monthlyHireData.map(item => item.month),
        datasets: [
          {
            label: '入职人数',
            data: this.monthlyHireData.map(item => item.hired),
            borderColor: '#4CAF50',
            backgroundColor: 'rgba(76, 175, 80, 0.1)',
            tension: 0.4,
            fill: true
          },
          {
            label: '离职人数',
            data: this.monthlyHireData.map(item => item.left),
            borderColor: '#f44336',
            backgroundColor: 'rgba(244, 67, 54, 0.1)',
            tension: 0.4,
            fill: true
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: 'top'
          },
          tooltip: {
            mode: 'index',
            intersect: false
          }
        },
        scales: {
          y: {
            beginAtZero: true,
            grid: {
              color: 'rgba(0, 0, 0, 0.1)'
            }
          },
          x: {
            grid: {
              color: 'rgba(0, 0, 0, 0.1)'
            }
          }
        },
        interaction: {
          mode: 'nearest',
          axis: 'x',
          intersect: false
        }
      }
    };

    this.lineChart = new Chart(ctx, config);
  }

  // 初始化绩效总览雷达图
  private initRadarChart() {
    if (!this.radarChartRef?.nativeElement) return;

    const ctx = this.radarChartRef.nativeElement.getContext('2d');
    if (!ctx) return;

    const config: ChartConfiguration = {
      type: 'radar',
      data: {
        labels: ['项目完成率', '优秀作品率', '客户满意度', '逾期率'],
        datasets: this.departmentPerformance.map((dept, index) => ({
          label: dept.department,
          data: [
            dept.completionRate,
            dept.excellentWorkRate,
            dept.satisfactionRate,
            100 - dept.overdueRate // 逾期率转换为正向指标
          ],
          borderColor: this.getDepartmentColor(dept.department),
          backgroundColor: this.getDepartmentColor(dept.department) + '20',
          pointBackgroundColor: this.getDepartmentColor(dept.department),
          pointBorderColor: '#fff',
          pointHoverBackgroundColor: '#fff',
          pointHoverBorderColor: this.getDepartmentColor(dept.department)
        }))
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: 'bottom'
          }
        },
        scales: {
          r: {
            beginAtZero: true,
            max: 100,
            grid: {
              color: 'rgba(0, 0, 0, 0.1)'
            },
            angleLines: {
              color: 'rgba(0, 0, 0, 0.1)'
            },
            pointLabels: {
              font: {
                size: 12
              }
            }
          }
        }
      }
    };

    this.radarChart = new Chart(ctx, config);
  }

  getPriorityLabel(priority: string): string {
    switch (priority) {
      case 'high': return '紧急';
      case 'medium': return '重要';
      case 'low': return '一般';
      default: return '未知';
    }
  }

  getTypeLabel(type: string): string {
    switch (type) {
      case 'resume': return '简历初筛';
      case 'onboarding': return '入职评定';
      case 'promotion': return '晋升审核';
      case 'resignation': return '离职面谈';
      default: return '其他';
    }
  }

  getStatusLabel(status: string): string {
    const statusMap: { [key: string]: string } = {
      'pending': '待处理',
      'in_progress': '进行中',
      'completed': '已完成',
      'urgent': '紧急',
      'normal': '普通'
    };
    return statusMap[status] || status;
  }

  // 拖拽排序功能
  onTodoDrop(event: CdkDragDrop<TodoItem[]>): void {
    moveItemInArray(this.todoItems, event.previousIndex, event.currentIndex);
  }

  // 更新待办事项状态
  updateTodoStatus(todo: TodoItem, status: 'pending' | 'completed' | 'in_progress'): void {
    todo.status = status;
  }

  // 处理按钮按压效果
  isButtonPressed = false;
  handleButtonPress(action: 'press' | 'release') {
    this.isButtonPressed = action === 'press';
  }
}