import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Router, RouterModule } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { ProjectService } from '../../../services/project.service';

// 项目阶段定义
interface ProjectStage {
  id: string;
  name: string;
  order: number;
}

interface ProjectPhase {
  name: string;
  percentage: number;
  startPercentage: number;
  isCompleted: boolean;
  isCurrent: boolean;
}

interface Project {
  id: string;
  name: string;
  type: 'soft' | 'hard';
  designerName: string;
  status: string;
  expectedEndDate: Date;
  isOverdue: boolean;
  overdueDays: number;
  urgency: 'high' | 'medium' | 'low';
  phases: ProjectPhase[];
  currentStage: string; // 新增：当前项目阶段
}

interface TodoTask {
  id: string;
  title: string;
  description: string;
  deadline: Date;
  priority: 'high' | 'medium' | 'low';
  type: 'review' | 'assign' | 'performance';
  targetId: string;
}

@Component({
  selector: 'app-dashboard',
  imports: [CommonModule, FormsModule, RouterModule],
  templateUrl: './dashboard.html',
  styleUrl: './dashboard.scss'
})

export class Dashboard implements OnInit {
  projects: Project[] = [];
  filteredProjects: Project[] = [];
  todoTasks: TodoTask[] = [];
  overdueProjects: Project[] = [];
  showAlert: boolean = false;
  selectedProjectId: string = '';
  
  // 定义10个项目阶段
  projectStages: ProjectStage[] = [
    { id: 'pendingApproval', name: '待确认', order: 1 },
    { id: 'pendingAssignment', name: '待分配', order: 2 },
    { id: 'requirement', name: '需求沟通', order: 3 },
    { id: 'planning', name: '方案规划', order: 4 },
    { id: 'modeling', name: '建模阶段', order: 5 },
    { id: 'rendering', name: '渲染阶段', order: 6 },
    { id: 'postProduction', name: '后期处理', order: 7 },
    { id: 'review', name: '方案评审', order: 8 },
    { id: 'revision', name: '方案修改', order: 9 },
    { id: 'delivery', name: '交付完成', order: 10 }
  ];

  constructor(private projectService: ProjectService, private router: Router) {}

  ngOnInit(): void {
    this.loadProjects();
    this.loadTodoTasks();
  }

  loadProjects(): void {
    // 模拟数据加载 - 增强数据结构，添加currentStage
    this.projects = [
      {
        id: 'proj-001',
        name: '现代风格客厅设计',
        type: 'soft',
        designerName: '张三',
        status: '进行中',
        expectedEndDate: new Date(2023, 9, 15),
        isOverdue: true,
        overdueDays: 2,
        urgency: 'high',
        currentStage: 'rendering',
        phases: [
          { name: '建模', percentage: 15, startPercentage: 0, isCompleted: true, isCurrent: false },
          { name: '渲染', percentage: 20, startPercentage: 15, isCompleted: false, isCurrent: true },
          { name: '后期', percentage: 15, startPercentage: 35, isCompleted: false, isCurrent: false },
          { name: '交付', percentage: 50, startPercentage: 50, isCompleted: false, isCurrent: false }
        ]
      },
      {
        id: 'proj-002',
        name: '北欧风格卧室设计',
        type: 'soft',
        designerName: '李四',
        status: '进行中',
        expectedEndDate: new Date(2023, 9, 20),
        isOverdue: false,
        overdueDays: 0,
        urgency: 'medium',
        currentStage: 'postProduction',
        phases: [
          { name: '建模', percentage: 15, startPercentage: 0, isCompleted: true, isCurrent: false },
          { name: '渲染', percentage: 20, startPercentage: 15, isCompleted: true, isCurrent: false },
          { name: '后期', percentage: 15, startPercentage: 35, isCompleted: false, isCurrent: true },
          { name: '交付', percentage: 50, startPercentage: 50, isCompleted: false, isCurrent: false }
        ]
      },
      {
        id: 'proj-003',
        name: '新中式餐厅设计',
        type: 'hard',
        designerName: '王五',
        status: '进行中',
        expectedEndDate: new Date(2023, 9, 25),
        isOverdue: false,
        overdueDays: 0,
        urgency: 'low',
        currentStage: 'modeling',
        phases: [
          { name: '建模', percentage: 15, startPercentage: 0, isCompleted: false, isCurrent: true },
          { name: '渲染', percentage: 20, startPercentage: 15, isCompleted: false, isCurrent: false },
          { name: '后期', percentage: 15, startPercentage: 35, isCompleted: false, isCurrent: false },
          { name: '交付', percentage: 50, startPercentage: 50, isCompleted: false, isCurrent: false }
        ]
      },
      {
        id: 'proj-004',
        name: '工业风办公室设计',
        type: 'hard',
        designerName: '赵六',
        status: '进行中',
        expectedEndDate: new Date(2023, 9, 10),
        isOverdue: true,
        overdueDays: 7,
        urgency: 'high',
        currentStage: 'review',
        phases: [
          { name: '建模', percentage: 15, startPercentage: 0, isCompleted: true, isCurrent: false },
          { name: '渲染', percentage: 20, startPercentage: 15, isCompleted: true, isCurrent: false },
          { name: '后期', percentage: 15, startPercentage: 35, isCompleted: false, isCurrent: false },
          { name: '交付', percentage: 50, startPercentage: 50, isCompleted: false, isCurrent: false }
        ]
      },
      // 添加更多不同阶段的项目
      {
        id: 'proj-005',
        name: '现代简约厨房设计',
        type: 'soft',
        designerName: '',
        status: '待分配',
        expectedEndDate: new Date(2023, 10, 5),
        isOverdue: false,
        overdueDays: 0,
        urgency: 'medium',
        currentStage: 'pendingAssignment',
        phases: []
      },
      {
        id: 'proj-006',
        name: '日式风格书房设计',
        type: 'hard',
        designerName: '',
        status: '待确认',
        expectedEndDate: new Date(2023, 10, 10),
        isOverdue: false,
        overdueDays: 0,
        urgency: 'low',
        currentStage: 'pendingApproval',
        phases: []
      },
      {
        id: 'proj-007',
        name: '轻奢风格浴室设计',
        type: 'soft',
        designerName: '钱七',
        status: '已完成',
        expectedEndDate: new Date(2023, 9, 5),
        isOverdue: false,
        overdueDays: 0,
        urgency: 'medium',
        currentStage: 'delivery',
        phases: []
      }
    ];

    // ===== 追加生成示例数据：保证总量达到100条 =====
    const stageIds = this.projectStages.map(s => s.id);
    const designers = ['张三','李四','王五','赵六','钱七','孙八','周九','吴十','郑一','冯二','陈三','褚四'];
    const statusMap: Record<string, string> = {
      pendingApproval: '待确认',
      pendingAssignment: '待分配',
      requirement: '进行中',
      planning: '进行中',
      modeling: '进行中',
      rendering: '进行中',
      postProduction: '进行中',
      review: '进行中',
      revision: '进行中',
      delivery: '已完成'
    };

    for (let i = 8; i <= 100; i++) {
      const stageIndex = (i - 1) % stageIds.length;
      const currentStage = stageIds[stageIndex];
      const type: 'soft' | 'hard' = i % 2 === 0 ? 'soft' : 'hard';
      const urgency: 'high' | 'medium' | 'low' = i % 5 === 0 ? 'high' : (i % 3 === 0 ? 'medium' : 'low');
      const isOverdue = ['planning','modeling','rendering','postProduction','review','revision','delivery'].includes(currentStage) ? i % 7 === 0 : false;
      const overdueDays = isOverdue ? (i % 10) + 1 : 0;
      const hasDesigner = !['pendingApproval', 'pendingAssignment'].includes(currentStage);
      const designerName = hasDesigner ? designers[i % designers.length] : '';
      const status = statusMap[currentStage] || '进行中';
      const expectedEndDate = new Date();
      const daysOffset = isOverdue ? - (overdueDays + (i % 5)) : ((i % 20) + 3);
      expectedEndDate.setDate(expectedEndDate.getDate() + daysOffset);

      this.projects.push({
        id: `proj-${String(i).padStart(3, '0')}`,
        name: `${type === 'soft' ? '软装' : '硬装'}示例项目 ${i}`,
        type,
        designerName,
        status,
        expectedEndDate,
        isOverdue,
        overdueDays,
        urgency,
        currentStage,
        phases: []
      });
    }
    // ===== 示例数据生成结束 =====

    // 筛选超期项目
    this.overdueProjects = this.projects.filter(project => project.isOverdue);
    this.filteredProjects = [...this.projects];

    // 显示超期提醒
    if (this.overdueProjects.length > 0) {
      this.showAlert = true;
    }
  }

  loadTodoTasks(): void {
    // 模拟待办任务数据
    this.todoTasks = [
      {
        id: 'todo-001',
        title: '待评审效果图',
        description: '现代风格客厅设计项目需要进行效果图评审',
        deadline: new Date(2023, 9, 18, 15, 0),
        priority: 'high',
        type: 'review',
        targetId: 'proj-001'
      },
      {
        id: 'todo-002',
        title: '待分配项目',
        description: '新中式厨房设计项目需要分配给合适的设计师',
        deadline: new Date(2023, 9, 19, 10, 0),
        priority: 'high',
        type: 'assign',
        targetId: 'proj-new'
      },
      {
        id: 'todo-003',
        title: '待确认绩效',
        description: '9月份团队绩效需要进行审核确认',
        deadline: new Date(2023, 9, 22, 18, 0),
        priority: 'medium',
        type: 'performance',
        targetId: 'sep-2023'
      },
      {
        id: 'todo-004',
        title: '待处理客户反馈',
        description: '北欧风格卧室设计项目有客户反馈需要处理',
        deadline: new Date(2023, 9, 20, 14, 0),
        priority: 'medium',
        type: 'review',
        targetId: 'proj-002'
      },
      {
        id: 'todo-005',
        title: '团队会议',
        description: '每周团队进度沟通会议',
        deadline: new Date(2023, 9, 18, 10, 0),
        priority: 'low',
        type: 'performance',
        targetId: 'weekly-meeting'
      }
    ];

    // 按优先级排序：紧急且重要 > 重要不紧急 > 紧急不重要
    this.todoTasks.sort((a, b) => {
      const priorityOrder = {
        'high': 3,
        'medium': 2,
        'low': 1
      };
      return priorityOrder[b.priority] - priorityOrder[a.priority];
    });
  }

  // 筛选项目类型
  filterProjects(event: Event): void {
    const target = event.target as HTMLSelectElement;
    const filterValue = target.value;
    
    if (filterValue === 'all') {
      this.filteredProjects = [...this.projects];
    } else {
      this.filteredProjects = this.projects.filter(project => project.type === filterValue);
    }
  }

  // 筛选紧急程度
  filterByUrgency(event: Event): void {
    const target = event.target as HTMLSelectElement;
    const filterValue = target.value;
    
    if (filterValue === 'all') {
      this.filteredProjects = [...this.projects];
    } else {
      this.filteredProjects = this.projects.filter(project => project.urgency === filterValue);
    }
  }

  // 筛选项目状态
  filterByStatus(status: string): void {
    if (status === 'all') {
      this.filteredProjects = [...this.projects];
    } else if (status === 'overdue') {
      this.filteredProjects = this.overdueProjects;
    } else if (status === 'pendingApproval') {
      this.filteredProjects = this.projects.filter(project => project.currentStage === 'pendingApproval');
    } else if (status === 'pendingAssignment') {
      this.filteredProjects = this.projects.filter(project => project.currentStage === 'pendingAssignment');
    } else if (status === 'progress') {
      this.filteredProjects = this.projects.filter(project => 
        ['requirement', 'planning', 'modeling', 'rendering', 'postProduction', 'review', 'revision'].includes(project.currentStage)
      );
    } else if (status === 'completed') {
      this.filteredProjects = this.projects.filter(project => project.currentStage === 'delivery');
    }
  }
  
  // 处理状态筛选下拉框变化
  onStatusChange(event: Event): void {
    const target = event.target as HTMLSelectElement;
    if (target && target.value) {
      this.filterByStatus(target.value);
    }
  }

  // 选择单个项目
  selectProject(): void {
    if (this.selectedProjectId) {
      this.router.navigate(['/team-leader/project-review', this.selectedProjectId]);
    }
  }

  // 获取特定阶段的项目
  getProjectsByStage(stageId: string): Project[] {
    return this.filteredProjects.filter(project => project.currentStage === stageId);
  }

  // 获取特定阶段的项目数量
  getProjectCountByStage(stageId: string): number {
    return this.getProjectsByStage(stageId).length;
  }

  // 获取紧急程度标签
  getUrgencyLabel(urgency: string): string {
    const labels = {
      high: '紧急',
      medium: '一般',
      low: '普通'
    };
    return labels[urgency as keyof typeof labels] || urgency;
  }

  // 查看项目详情
  viewProjectDetails(projectId: string): void {
    this.router.navigate(['/team-leader/project-review', projectId]);
  }

  // 快速分配项目
  quickAssignProject(projectId: string): void {
    this.router.navigate(['/team-leader/project-review', projectId, 'assign']);
  }

  // 导航到待办任务
  navigateToTask(task: TodoTask): void {
    switch (task.type) {
      case 'review':
        this.router.navigate(['team-leader/quality-management', task.targetId]);
        break;
      case 'assign':
        this.router.navigate(['team-leader/project-review']);
        break;
      case 'performance':
        this.router.navigate(['team-leader/team-management']);
        break;
    }
  }

  // 获取优先级标签
  getPriorityLabel(priority: 'high' | 'medium' | 'low'): string {
    const labels: Record<'high' | 'medium' | 'low', string> = {
      'high': '紧急且重要',
      'medium': '重要不紧急',
      'low': '紧急不重要'
    };
    return labels[priority];
  }

  // 导航到团队管理
  navigateToTeamManagement(): void {
    this.router.navigate(['/team-leader/team-management']);
  }

  // 导航到项目评审
  navigateToProjectReview(): void {
    this.router.navigate(['/team-leader/project-review']);
  }

  // 导航到质量管理
  navigateToQualityManagement(): void {
    this.router.navigate(['/team-leader/quality-management']);
  }

  // 打开工作量预估工具（已迁移）
  openWorkloadEstimator(): void {
    this.router.navigate(['/team-leader/project-review']);
    alert('工作量预估工具已迁移至项目详情页，您可以在建模阶段之前使用该工具进行工作量计算。');
  }

  // 查看所有超期项目
  viewAllOverdueProjects(): void {
    this.filterByStatus('overdue');
    this.closeAlert();
  }

  // 关闭提醒
  closeAlert(): void {
    this.showAlert = false;
  }

  // 获取待确认项目数量
  get pendingApprovalProjects() {
    return this.projects.filter(project => project.currentStage === 'pendingApproval');
  }

  // 获取待分配项目数量
  get pendingAssignmentProjects() {
    return this.projects.filter(project => project.currentStage === 'pendingAssignment');
  }
}
