import { Component, OnInit, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Router } from '@angular/router';
import { AuthService } from '../../../services/auth.service';
import { WorkHourService } from '../../../services/work-hour.service';
import { WorkHourDashboardData, MonthlyWorkHourStats, PerformanceLevel } from '../../../models/work-hour.model';

@Component({
  selector: 'app-dashboard',
  imports: [CommonModule, RouterModule],
  templateUrl: './dashboard.html',
  styleUrl: './dashboard.scss'
})
export class Dashboard implements OnInit {
  // 添加today属性用于模板中的日期显示
  today = new Date();
  
  // 待办任务数据
  todoTasks = signal([
    { id: 1, title: '临时收款待核定', priority: 'high', source: 'reconciliation', dueTime: '10:30' },
    { id: 2, title: '报价待审核', priority: 'medium', source: 'project-records', dueTime: '14:00' },
    { id: 3, title: '素材成本待录入', priority: 'low', source: 'reconciliation', dueTime: '16:30' },
    { id: 4, title: '临时收款待核定', priority: 'high', source: 'reconciliation', dueTime: '11:00' },
    { id: 5, title: '销售监管提醒', priority: 'high', source: 'project-records', dueTime: '09:30' }
  ]);

  // 数据概览数据
  dashboardStats = signal({
    todayOrders: 12,
    pendingPayment: 156800,
    quotedProjects: 28,
    materialCostSaved: 8900
  });

  // 用户角色
  userRole = signal('teamLead'); // teamLead 或 juniorMember

  // 工时统计数据
  workHourDashboard = signal<WorkHourDashboardData | null>(null);
  monthlyStats = signal<MonthlyWorkHourStats[]>([]);
  showWorkHourModule = signal(false);

  constructor(private authService: AuthService, private workHourService: WorkHourService, private router: Router) {}

  ngOnInit(): void {
    // 初始化用户角色
    this.initializeUserRole();
    
    // 加载工时统计数据
    this.loadWorkHourData();
  }
  
  // 初始化用户角色
  initializeUserRole(): void {
    // 从AuthService获取用户角色
    const roles = this.authService.getUserRoles();
    // 默认使用teamLead角色
    let userRole = 'teamLead';
    
    // 如果用户有admin角色，也视为teamLead
    if (roles.includes('admin')) {
      userRole = 'teamLead';
    } else if (roles.length > 0) {
      // 否则使用第一个角色
      userRole = roles[0];
    }
    
    this.userRole.set(userRole);
    
    // 根据用户角色过滤待办任务
    this.filterTasksByRole();
  }
  
  // 根据用户角色过滤待办任务
  filterTasksByRole(): void {
    if (this.userRole() !== 'teamLead') {
      // 初级组员只显示非财务审批类任务
      const filteredTasks = this.todoTasks().filter(task => 
        task.title !== '临时收款待核定' && task.title !== '报价待审核'
      );
      this.todoTasks.set(filteredTasks);
    }
  }
  
  // 检查用户角色
  checkUserRole(requiredRole: string): boolean {
    return this.authService.hasRole(requiredRole);
  }

  // 处理待办任务点击
  handleTaskClick(task: any) {
    // 检查财务相关任务的权限
    if ((task.title === '临时收款待核定' || task.title === '报价待审核') && !this.checkUserRole('teamLead')) {
      console.warn('权限不足：只有组长可以处理此任务');
      return;
    }
    
    // 根据任务来源跳转到对应页面
    switch(task.source) {
      case 'reconciliation':
        window.location.href = '/finance/reconciliation';
        break;
      case 'project-records':
        window.location.href = '/finance/project-records';
        break;
    }
  }

  // 处理快捷操作点击
  handleQuickAction(action: string) {
    // 检查权限
    if ((action === 'recordPayment' || action === 'generateReport') && !this.checkUserRole('teamLead')) {
      console.warn('权限不足：只有组长可以执行此操作');
      return;
    }
    
    switch(action) {
      case 'newQuote':
        window.location.href = '/finance/project-records';
        break;
      case 'recordPayment':
        window.location.href = '/finance/reconciliation';
        break;
      case 'generateReport':
        window.location.href = '/finance/reports';
        break;
      case 'quotationApproval':
        this.router.navigate(['/finance/quotation-approval']);
        break;
    }
  }

  // 格式化金额显示
  formatAmount(amount: number): string {
    return new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY' }).format(amount);
  }

  // 加载工时统计数据
  loadWorkHourData(): void {
    this.workHourService.getDashboardData().subscribe(data => {
      this.workHourDashboard.set(data);
    });

    this.workHourService.getMonthlyStats().subscribe(stats => {
      this.monthlyStats.set(stats);
    });
  }

  // 切换工时模块显示
  toggleWorkHourModule(): void {
    this.showWorkHourModule.set(!this.showWorkHourModule());
  }

  // 获取绩效等级颜色
  getPerformanceLevelColor(level: string): string {
    const colors: Record<string, string> = {
      'S': '#ff6b6b',
      'A': '#4ecdc4', 
      'B': '#45b7d1',
      'C': '#96ceb4'
    };
    return colors[level] || '#ccc';
  }

  // 获取绩效等级人数
  getPerformanceLevelCount(level: string): number {
    const dashboard = this.workHourDashboard();
    if (!dashboard) return 0;
    
    const distribution = dashboard.performanceDistribution as Record<string, number>;
    return distribution[level] || 0;
  }

  // 获取绩效等级描述
  getPerformanceLevelDescription(level: string): string {
    const descriptions: Record<string, string> = {
      'S': '卓越表现',
      'A': '优秀表现',
      'B': '良好表现', 
      'C': '待提升'
    };
    return descriptions[level] || '未知';
  }

  // 格式化工时显示
  formatWorkHours(hours: number): string {
    const days = Math.floor(hours / 8);
    const remainingHours = hours % 8;
    
    if (days > 0 && remainingHours > 0) {
      return `${days}天${remainingHours}小时`;
    } else if (days > 0) {
      return `${days}天`;
    } else {
      return `${remainingHours}小时`;
    }
  }
}
