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

// 定义质量整改任务接口
interface RectificationTask {
  id: string;
  projectName: string;
  designerName: string;
  issueDescription: string;
  priority: 'high' | 'medium' | 'low';
  status: 'pending' | 'processing' | 'review' | 'completed';
  suggestedDeadline: Date;
  sopComplianceScore: number | null;
  managerComment: string | null;
  relatedSOP: string;
}

// 定义视频教程接口
interface VideoTutorial {
  id: string;
  title: string;
  description: string;
  thumbnailUrl: string;
  duration: string;
  category: string;
  views: number;
  relatedSOP: string;
  isHovered: boolean;
  date: string;
}

// 定义实践作业接口
interface PracticeAssignment {
  id: string;
  title: string;
  description: string;
  relatedSOP: string;
  deadline: Date;
  status: 'pending' | 'submitted' | 'reviewed';
  score: number | null;
  designerName: string;
  points: number;
  progress: number;
  difficulty: 'easy' | 'medium' | 'hard';
  type: string;
}

@Component({
  selector: 'app-quality-management',
  templateUrl: './quality-management.html',
  styleUrl: './quality-management.scss',
  standalone: true,
  imports: [FormsModule, CommonModule]
})
export class QualityManagementComponent implements OnInit {
  // 活动标签页
  activeTab: 'modeling' | 'rendering' | 'postProduction' = 'modeling';
  
  // 搜索和筛选条件
  searchTerm: string = '';
  filterStatus: string = 'all';
  
  // 质量整改任务列表
  rectificationTasks: RectificationTask[] = [];
  
  // 视频教程列表
  videoTutorials: VideoTutorial[] = [];
  
  // 实践作业列表
  practiceAssignments: PracticeAssignment[] = [];
  
  constructor(private router: Router) {}
  
  ngOnInit() {
    // 初始化模拟数据
    this.initializeMockData();
  }
  
  // 初始化模拟数据
  initializeMockData(): void {
    // 初始化质量整改任务
    this.rectificationTasks = [
      {
        id: 'task-1',
        projectName: '现代风格客厅效果图',
        designerName: '张三',
        issueDescription: '渲染真实度不足，光影效果不自然',
        priority: 'high',
        status: 'review',
        suggestedDeadline: new Date('2023-12-15'),
        sopComplianceScore: 82,
        managerComment: null,
        relatedSOP: '渲染阶段'
      },
      {
        id: 'task-2',
        projectName: '新中式卧室设计',
        designerName: '李四',
        issueDescription: '材质贴图不符合要求，颜色偏差较大',
        priority: 'medium',
        status: 'processing',
        suggestedDeadline: new Date('2023-12-18'),
        sopComplianceScore: null,
        managerComment: null,
        relatedSOP: '建模阶段'
      },
      {
        id: 'task-3',
        projectName: '北欧风格厨房',
        designerName: '王五',
        issueDescription: '后期处理细节不到位，色彩不够明亮',
        priority: 'low',
        status: 'pending',
        suggestedDeadline: new Date('2023-12-20'),
        sopComplianceScore: null,
        managerComment: null,
        relatedSOP: '后期阶段'
      },
      {
        id: 'task-4',
        projectName: '工业风办公室',
        designerName: '赵六',
        issueDescription: '户型匹配度误差超过2%，需要重新建模',
        priority: 'high',
        status: 'completed',
        suggestedDeadline: new Date('2023-12-10'),
        sopComplianceScore: 95,
        managerComment: '整改效果良好，符合SOP标准',
        relatedSOP: '建模阶段'
      }
    ];
    
    // 初始化视频教程
    this.videoTutorials = [
      {
        id: 'video-1',
        title: '渲染真实度提升技巧',
        description: '学习如何调整灯光和材质参数，提升效果图的真实感',
        thumbnailUrl: 'https://img.alicdn.com/imgextra/i3/O1CN01V9V6wF1u0l7zIeVYB_!!6000000006001-2-tps-1200-675.jpg',
        duration: '15:30',
        category: '渲染技巧',
        views: 1256,
        relatedSOP: '渲染阶段',
        isHovered: false,
        date: '2023-12-01'
      },
      {
        id: 'video-2',
        title: '宋式风格建模规范',
        description: '详细讲解宋式风格的建模要点和注意事项',
        thumbnailUrl: 'https://img.alicdn.com/imgextra/i1/O1CN01y8z30s1L7c8w9X83G_!!6000000001323-2-tps-1200-675.jpg',
        duration: '22:15',
        category: '建模技巧',
        views: 892,
        relatedSOP: '建模阶段',
        isHovered: false,
        date: '2023-11-28'
      },
      {
        id: 'video-3',
        title: '色彩校正与后期处理',
        description: '掌握专业的后期处理流程，提升效果图的视觉效果',
        thumbnailUrl: 'https://img.alicdn.com/imgextra/i4/O1CN012bQ5Z11j1D5P7XQr1_!!6000000004666-2-tps-1200-675.jpg',
        duration: '18:45',
        category: '后期处理',
        views: 1053,
        relatedSOP: '后期阶段',
        isHovered: false,
        date: '2023-12-05'
      }
    ];
    
    // 初始化实践作业
    this.practiceAssignments = [
      {
        id: 'assignment-1',
        title: '现代风格客厅渲染练习',
        description: '根据提供的3D模型，完成现代风格客厅的渲染，要求真实度达到90%以上',
        relatedSOP: '渲染阶段',
        deadline: new Date('2023-12-25'),
        status: 'submitted',
        score: null,
        designerName: '张三',
        points: 85,
        progress: 100,
        difficulty: 'medium',
        type: '渲染练习'
      },
      {
        id: 'assignment-2',
        title: '新中式卧室建模练习',
        description: '根据户型图，完成新中式卧室的建模，要求户型匹配度误差≤2%',
        relatedSOP: '建模阶段',
        deadline: new Date('2024-01-05'),
        status: 'pending',
        score: null,
        designerName: '李四',
        points: 75,
        progress: 30,
        difficulty: 'hard',
        type: '建模练习'
      },
      {
        id: 'assignment-3',
        title: '北欧风格厨房后期处理',
        description: '对提供的渲染图进行后期处理，重点优化色彩和细节',
        relatedSOP: '后期阶段',
        deadline: new Date('2023-12-30'),
        status: 'reviewed',
        score: 92,
        designerName: '王五',
        points: 90,
        progress: 100,
        difficulty: 'easy',
        type: '后期处理'
      }
    ];
  }
  
  // 获取筛选后的任务列表
  get filteredTasks(): RectificationTask[] {
    return this.rectificationTasks.filter(task => {
      const matchesSearch = this.searchTerm === '' || 
        task.projectName.toLowerCase().includes(this.searchTerm.toLowerCase()) ||
        task.designerName.toLowerCase().includes(this.searchTerm.toLowerCase());
      
      const matchesStatus = this.filterStatus === 'all' || task.status === this.filterStatus;
      
      return matchesSearch && matchesStatus;
    });
  }
  
  // 获取状态文本
  getStatusText(status: string): string {
    const statusMap: { [key: string]: string } = {
      'pending': '待处理',
      'processing': '处理中',
      'review': '待审核',
      'completed': '已完成'
    };
    return statusMap[status] || status;
  }
  
  // 获取优先级文本
  getPriorityText(priority: string): string {
    const priorityMap: { [key: string]: string } = {
      'high': '高',
      'medium': '中',
      'low': '低'
    };
    return priorityMap[priority] || priority;
  }
  
  // 获取作业状态文本
  getAssignmentStatusText(status: string): string {
    const statusMap: { [key: string]: string } = {
      'pending': '待提交',
      'submitted': '已提交',
      'reviewed': '已评审'
    };
    return statusMap[status] || status;
  }
  
  // 导出SOP为PDF
  exportSOP(): void {
    // 模拟导出PDF功能
    alert(`已导出${this.getPhaseName(this.activeTab)}的SOP标准为PDF文件`);
    // 实际项目中，这里应该调用PDF生成库或API
  }
  
  // 获取阶段名称
  getPhaseName(phase: string): string {
    const phaseMap: { [key: string]: string } = {
      'modeling': '建模阶段',
      'rendering': '渲染阶段',
      'postProduction': '后期阶段'
    };
    return phaseMap[phase] || phase;
  }
  
  // 查看任务详情
  viewTaskDetails(taskId: string): void {
    // 模拟查看任务详情
    console.log(`查看任务详情: ${taskId}`);
    // 实际项目中，这里应该跳转到任务详情页面或打开任务详情模态框
  }
  
  // 批准任务
  approveTask(taskId: string): void {
    const task = this.rectificationTasks.find(t => t.id === taskId);
    if (task) {
      task.status = 'completed';
      // 自动同步至项目评审板块
      this.syncToProjectReview(taskId);
      alert(`已批准任务: ${task.projectName}`);
    }
  }
  
  // 拒绝任务
  rejectTask(taskId: string): void {
    const task = this.rectificationTasks.find(t => t.id === taskId);
    if (task) {
      task.status = 'pending';
      // 可以添加拒绝原因输入框
      const reason = prompt('请输入拒绝原因:');
      if (reason) {
        task.managerComment = reason;
      }
      alert(`已拒绝任务: ${task.projectName}`);
    }
  }
  
  // 同步至项目评审板块
  syncToProjectReview(taskId: string): void {
    const task = this.rectificationTasks.find(t => t.id === taskId);
    if (task) {
      // 模拟同步数据到项目评审板块
      console.log(`同步任务${taskId}至项目评审板块`);
      // 实际项目中，这里应该调用API同步数据
    }
  }
  
  // 播放视频
  playVideo(video: VideoTutorial): void {
    // 模拟播放视频
    alert(`正在播放视频: ${video.title}`);
    // 实际项目中，这里应该打开视频播放器或跳转到视频播放页面
  }
  
  // 评审作业
  reviewAssignment(assignmentId: string): void {
    const assignment = this.practiceAssignments.find(a => a.id === assignmentId);
    if (assignment) {
      // 模拟评审作业
      if (assignment.status === 'submitted') {
        const score = prompt('请输入评分 (0-100):');
        if (score && !isNaN(Number(score)) && Number(score) >= 0 && Number(score) <= 100) {
          assignment.score = Number(score);
          assignment.status = 'reviewed';
          // 同步成绩到team-management板块的能力看板
          this.syncScoreToTeamManagement(assignmentId, Number(score));
          alert(`已完成作业评审，评分: ${score}`);
        }
      }
    }
  }
  
  // 同步成绩到team-management板块
  syncScoreToTeamManagement(assignmentId: string, score: number): void {
    const assignment = this.practiceAssignments.find(a => a.id === assignmentId);
    if (assignment) {
      // 模拟同步成绩数据
      console.log(`同步作业${assignmentId}的成绩${score}至team-management板块`);
      // 实际项目中，这里应该调用API同步数据
    }
  }
  
  // 跳转到团队管理页面
  navigateToTeamManagement(): void {
    this.router.navigate(['/team-leader/team-management']);
  }
  
  // 跳转到项目评审页面
  navigateToProjectReview(): void {
    // 统一入口：返回到组长看板
    this.router.navigate(['/team-leader/dashboard']);
  }

  // 打开作业详情
  openAssignment(assignment: PracticeAssignment): void {
    console.log('打开作业详情:', assignment);
    // 这里可以实现打开作业详情的逻辑，比如导航到详情页面或打开模态框
  }
}
