import { Component, OnInit, AfterViewInit, OnDestroy, signal } 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 { MatIconModule } from '@angular/material/icon';
import { MatTabsModule } from '@angular/material/tabs';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatChipsModule } from '@angular/material/chips';
import { MatSelectModule } from '@angular/material/select';
import { FormsModule } from '@angular/forms';

// 模拟数据接口
interface EmployeeMovement {
  month: string;
  hired: number;
  resigned: number;
  turnoverRate: number;
}

interface DepartmentData {
  name: string;
  hired: number;
  resigned: number;
  turnoverRate: number;
}

interface PendingProcess {
  type: 'hire' | 'resign';
  count: number;
  progress: number;
}

interface RiskAlert {
  type: string;
  employees: {name: string; position: string; department: string; daysLeft?: number}[];
  count: number;
}

interface PerformanceMetric {
  name: string;
  target: number;
  actual: number;
  unit: string;
}

interface DepartmentPerformance {
  name: string;
  excellentWorkRate: number;
  deliveryOnTimeRate: number;
  customerSatisfaction: number;
}

interface PerformanceTier {
  name: string;
  percentage: number;
  count: number;
}

interface PenaltyWarning {
  issue: string;
  departments: {name: string; count: number}[];
  employees: {name: string; department: string; count: number}[];
}

interface EmployeeStructure {
  category: string;
  data: {name: string; count: number; percentage: number}[];
}

interface MovementTrend {
  month: string;
  hired: number;
  resigned: number;
}

interface TodoItem {
  task: string;
  dueDate: Date;
  priority: 'high' | 'medium' | 'low';
  type: string;
}

@Component({
  selector: 'app-hr-dashboard',
  standalone: true,
  imports: [
    CommonModule,
    RouterModule,
    MatCardModule,
    MatButtonModule,
    MatIconModule,
    MatTabsModule,
    MatProgressBarModule,
    MatChipsModule,
    MatSelectModule,
    FormsModule
  ],
  templateUrl: './dashboard.html',
  styleUrls: ['./dashboard.scss']
})
export class Dashboard implements OnInit, AfterViewInit, OnDestroy {
  // 时间筛选
  timeFilter = signal('month');

  // 图表实例
  private movementChart: any | null = null;
  private performanceChart: any | null = null;
  private trendChart: any | null = null;
  // 入职离职数据
  employeeMovements = signal<EmployeeMovement[]>([
    { month: '1月', hired: 12, resigned: 5, turnoverRate: 3.2 },
    { month: '2月', hired: 8, resigned: 4, turnoverRate: 2.5 },
    { month: '3月', hired: 15, resigned: 6, turnoverRate: 3.8 },
    { month: '4月', hired: 10, resigned: 8, turnoverRate: 5.1 },
    { month: '5月', hired: 14, resigned: 7, turnoverRate: 4.2 },
    { month: '6月', hired: 18, resigned: 5, turnoverRate: 2.9 }
  ]);
  
  departmentData = signal<DepartmentData[]>([
    { name: '设计部', hired: 8, resigned: 3, turnoverRate: 4.2 },
    { name: '客服部', hired: 5, resigned: 2, turnoverRate: 3.1 },
    { name: '技术部', hired: 12, resigned: 4, turnoverRate: 5.3 },
    { name: '行政部', hired: 3, resigned: 1, turnoverRate: 2.8 }
  ]);
  
  pendingProcesses = signal<PendingProcess[]>([
    { type: 'hire', count: 8, progress: 65 },
    { type: 'resign', count: 3, progress: 40 }
  ]);
  
  riskAlerts = signal<RiskAlert[]>([
    { 
      type: '试用期即将到期', 
      employees: [
        { name: '张三', position: '设计师', department: '设计部', daysLeft: 7 },
        { name: '李四', position: '客服专员', department: '客服部', daysLeft: 10 },
        { name: '王五', position: '前端开发', department: '技术部', daysLeft: 15 }
      ],
      count: 3
    },
    { 
      type: '离职关键岗位', 
      employees: [
        { name: '赵六', position: '高级设计师', department: '设计部' },
        { name: '钱七', position: '技术组长', department: '技术部' }
      ],
      count: 2
    }
  ]);
  
  // 绩效数据
  performanceMetrics = signal<PerformanceMetric[]>([
    { name: '优秀作品率', target: 80, actual: 76, unit: '%' },
    { name: '项目交付准时率', target: 95, actual: 92, unit: '%' },
    { name: '客户满意度评分', target: 4.5, actual: 4.3, unit: '分' }
  ]);
  
  departmentPerformance = signal<DepartmentPerformance[]>([
    { name: '设计部', excellentWorkRate: 78, deliveryOnTimeRate: 94, customerSatisfaction: 4.4 },
    { name: '客服部', excellentWorkRate: 82, deliveryOnTimeRate: 96, customerSatisfaction: 4.6 },
    { name: '技术部', excellentWorkRate: 75, deliveryOnTimeRate: 90, customerSatisfaction: 4.2 },
    { name: '行政部', excellentWorkRate: 80, deliveryOnTimeRate: 95, customerSatisfaction: 4.5 }
  ]);
  
  performanceTiers = signal<PerformanceTier[]>([
    { name: '头部20%', percentage: 20, count: 24 },
    { name: '中部70%', percentage: 70, count: 84 },
    { name: '尾部10%', percentage: 10, count: 12 }
  ]);
  
  penaltyWarnings = signal<PenaltyWarning[]>([
    { 
      issue: '项目延期', 
      departments: [
        { name: '设计部', count: 5 },
        { name: '技术部', count: 3 }
      ],
      employees: [
        { name: '张三', department: '设计部', count: 2 },
        { name: '李四', department: '技术部', count: 2 }
      ]
    },
    { 
      issue: '投诉差评', 
      departments: [
        { name: '客服部', count: 4 },
        { name: '设计部', count: 2 }
      ],
      employees: [
        { name: '王五', department: '客服部', count: 3 },
        { name: '赵六', department: '设计部', count: 1 }
      ]
    }
  ]);
  
  // 关键数据
  employeeStructures = signal<EmployeeStructure[]>([
    {
      category: '技术等级',
      data: [
        { name: '初级', count: 45, percentage: 37.5 },
        { name: '中级', count: 55, percentage: 45.8 },
        { name: '高级', count: 20, percentage: 16.7 }
      ]
    },
    {
      category: '岗位类型',
      data: [
        { name: '设计师', count: 60, percentage: 50 },
        { name: '客服', count: 30, percentage: 25 },
        { name: '技术组长', count: 15, percentage: 12.5 },
        { name: '其他', count: 15, percentage: 12.5 }
      ]
    },
    {
      category: '部门',
      data: [
        { name: '设计部', count: 65, percentage: 54.2 },
        { name: '客服部', count: 35, percentage: 29.2 },
        { name: '技术部', count: 20, percentage: 16.6 }
      ]
    }
  ]);
  
  movementTrends = signal<MovementTrend[]>([
    { month: '1月', hired: 12, resigned: 5 },
    { month: '2月', hired: 8, resigned: 4 },
    { month: '3月', hired: 15, resigned: 6 },
    { month: '4月', hired: 10, resigned: 8 },
    { month: '5月', hired: 14, resigned: 7 },
    { month: '6月', hired: 18, resigned: 5 }
  ]);
  
  todoItems = signal<TodoItem[]>([
    { task: '审核张三绩效表', dueDate: new Date('2023-06-15'), priority: 'high', type: '绩效审核' },
    { task: '签署李四离职协议', dueDate: new Date('2023-06-12'), priority: 'high', type: '离职手续' },
    { task: '跟进王五试用期评估', dueDate: new Date('2023-06-20'), priority: 'medium', type: '试用期评估' },
    { task: '审核新员工入职材料', dueDate: new Date('2023-06-18'), priority: 'medium', type: '入职手续' },
    { task: '更新部门人员架构图', dueDate: new Date('2023-06-25'), priority: 'low', type: '文档更新' }
  ]);
  
  ngOnInit() {
    // 实际项目中这里会调用服务获取数据
  }
  
  ngAfterViewInit(): void {
    this.initCharts();
    window.addEventListener('resize', this.handleResize);
  }
  
  ngOnDestroy(): void {
    window.removeEventListener('resize', this.handleResize);
    this.disposeCharts();
  }
  
  // 切换时间维度
  changeTimeFilter(filter: string) {
    this.timeFilter.set(filter);
    // 实际项目中这里会根据筛选条件重新获取数据
    // 刷新图表
    this.initCharts();
  }
  
  // 跳转到对应处理页面
  navigateToProcess(type: 'hire' | 'resign') {
    // 实际项目中这里会导航到对应页面
    console.log(`Navigate to ${type} process page`);
  }
  
  // 获取进度条颜色
  getProgressColor(value: number, target: number): string {
    const percentage = (value / target) * 100;
    if (percentage >= 90) return 'primary';
    if (percentage >= 70) return 'accent';
    return 'warn';
  }
  
  // 获取优先级样式类
  getPriorityClass(priority: string): string {
    switch (priority) {
      case 'high': return 'priority-high';
      case 'medium': return 'priority-medium';
      case 'low': return 'priority-low';
      default: return '';
    }
  }
  
  // ====== 图表相关 ======
  private initCharts(): void {
    this.initMovementChart();
    this.initPerformanceDistributionChart();
    this.initTrendChart();
  }
  
  private disposeCharts(): void {
    if (this.movementChart) { this.movementChart.dispose(); this.movementChart = null; }
    if (this.performanceChart) { this.performanceChart.dispose(); this.performanceChart = null; }
    if (this.trendChart) { this.trendChart.dispose(); this.trendChart = null; }
  }
  
  private initMovementChart(): void {
    const el = document.getElementById('hrMovementChart');
    if (!el) return;
    this.movementChart?.dispose();
    // 使用全局 echarts 变量
    // @ts-ignore
    this.movementChart = echarts.init(el);
  
    const data = this.employeeMovements();
    const months = data.map(d => d.month);
    const hired = data.map(d => d.hired);
    const resigned = data.map(d => d.resigned);
  
    this.movementChart.setOption({
      title: { text: '月度入职/离职', left: 'center', textStyle: { fontSize: 16 } },
      tooltip: { trigger: 'axis' },
      legend: { data: ['入职', '离职'] },
      grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
      xAxis: { type: 'category', data: months },
      yAxis: { type: 'value' },
      series: [
        { name: '入职', type: 'bar', data: hired, itemStyle: { color: '#165DFF' }, barGap: 0 },
        { name: '离职', type: 'bar', data: resigned, itemStyle: { color: '#F53F3F' } }
      ]
    });
  }
  
  private initPerformanceDistributionChart(): void {
    const el = document.getElementById('hrPerformanceDistributionChart');
    if (!el) return;
    this.performanceChart?.dispose();
    // @ts-ignore
    this.performanceChart = echarts.init(el);
  
    const tiers = this.performanceTiers();
    const data = tiers.map(t => ({ value: t.count, name: `${t.name}（${t.count}人）` }));
  
    this.performanceChart.setOption({
      title: { text: '绩效等级分布', left: 'center', textStyle: { fontSize: 16 } },
      tooltip: { trigger: 'item', formatter: '{b}: {c} 人 ({d}%)' },
      legend: { orient: 'horizontal', bottom: 0 },
      series: [{
        type: 'pie', radius: '65%', center: ['50%', '50%'],
        data,
        emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0,0,0,0.3)' } }
      }]
    });
  }
  
  private initTrendChart(): void {
    const el = document.getElementById('hrTrendChart');
    if (!el) return;
    this.trendChart?.dispose();
    // @ts-ignore
    this.trendChart = echarts.init(el);
  
    const trend = this.movementTrends();
    const months = trend.map(t => t.month);
    const hired = trend.map(t => t.hired);
    const resigned = trend.map(t => t.resigned);
  
    this.trendChart.setOption({
      title: { text: '异动趋势', left: 'center', textStyle: { fontSize: 16 } },
      tooltip: { trigger: 'axis' },
      legend: { data: ['入职', '离职'] },
      xAxis: { type: 'category', data: months },
      yAxis: { type: 'value' },
      series: [
        { name: '入职', type: 'line', data: hired, smooth: true, lineStyle: { color: '#00B42A' }, itemStyle: { color: '#00B42A' } },
        { name: '离职', type: 'line', data: resigned, smooth: true, lineStyle: { color: '#F53F3F' }, itemStyle: { color: '#F53F3F' } }
      ]
    });
  }
  
  private handleResize = (): void => {
    this.movementChart?.resize();
    this.performanceChart?.resize();
    this.trendChart?.resize();
  };
}