import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { ProjectService } from '../../../services/project.service';
import {
  Project,
  RenderProgress,
  ModelCheckItem,
  CustomerFeedback,
  DesignerChange,
  Settlement,
  ProjectStage
} from '../../../models/project.model';

interface ExceptionHistory {
  id: string;
  type: 'failed' | 'stuck' | 'quality' | 'other';
  description: string;
  submitTime: Date;
  status: '待处理' | '处理中' | '已解决';
  response?: string;
}

interface ProjectMember {
  id: string;
  name: string;
  role: string;
  avatar: string;
  skillMatch: number;
  progress: number;
  contribution: number;
}

interface ProjectFile {
  id: string;
  name: string;
  type: string;
  size: string;
  date: string;
  url: string;
}

interface TimelineEvent {
  id: string;
  time: string;
  title: string;
  action: string;
  description: string;
}

@Component({
  selector: 'app-project-detail',
  imports: [CommonModule, FormsModule],
  templateUrl: './project-detail.html',
  styleUrls: ['./project-detail.scss', './debug-styles.scss']
})
export class ProjectDetail implements OnInit, OnDestroy {
  // 项目基本数据
  projectId: string = '';
  project: Project | undefined;
  renderProgress: RenderProgress | undefined;
  modelCheckItems: ModelCheckItem[] = [];
  feedbacks: CustomerFeedback[] = [];
  designerChanges: DesignerChange[] = [];
  settlements: Settlement[] = [];
  requirementChecklist: string[] = [];
  reminderMessage: string = '';
  isLoadingRenderProgress: boolean = false;
  errorLoadingRenderProgress: boolean = false;
  feedbackTimeoutCountdown: number = 0;
  private countdownInterval: any;
  projects: {id: string, name: string, status: string}[] = [];
  showDropdown: boolean = false;
  currentStage: string = '';
  
  // 渲染异常反馈相关属性
  exceptionType: 'failed' | 'stuck' | 'quality' | 'other' = 'failed';
  exceptionDescription: string = '';
  exceptionScreenshotUrl: string | null = null;
  exceptionHistories: ExceptionHistory[] = [];
  isSubmittingFeedback: boolean = false;
  selectedScreenshot: File | null = null;
  screenshotPreview: string | null = null;
  showExceptionForm: boolean = false;
  
  // 标签页相关
  activeTab: 'progress' | 'members' | 'files' = 'progress';
  tabs = [
    { id: 'progress', name: '项目进度' },
    { id: 'members', name: '项目成员' },
    { id: 'files', name: '项目文件' }
  ];

  // 项目成员数据
  projectMembers: ProjectMember[] = [];
  
  // 项目文件数据
  projectFiles: ProjectFile[] = [];
  
  // 团队协作时间轴
  timelineEvents: TimelineEvent[] = [];

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

  // 切换标签页
  switchTab(tabId: 'progress' | 'members' | 'files') {
    this.activeTab = tabId;
  }

  // 类型安全的标签页检查方法
  isActiveTab(tabId: 'progress' | 'members' | 'files'): boolean {
    return this.activeTab === tabId;
  }

  // 根据事件类型获取作者名称
  getEventAuthor(action: string): string {
    // 根据不同的action类型返回对应的作者名称
    switch(action) {
      case '完成':
      case '更新':
      case '优化':
        return '李设计师';
      case '收到':
        return '李客服';
      case '提交':
        return '赵建模师';
      default:
        return '王组长';
    }
  }

  // 切换项目
  switchProject(projectId: string): void {
    this.projectId = projectId;
    this.loadProjectData();
    this.loadProjectMembers();
    this.loadProjectFiles();
    this.loadTimelineEvents();
    // 更新URL但不触发组件重载
    this.router.navigate([], { relativeTo: this.route, queryParamsHandling: 'merge', queryParams: { id: projectId } });
  }

  // 返回工作台
  backToWorkbench(): void {
    this.router.navigate(['/designer/dashboard']);
  }
  
  // 检查阶段是否已完成
  isStageCompleted(stage: ProjectStage): boolean {
    if (!this.project) return false;
    
    // 定义阶段顺序
    const stageOrder = [
      '订单创建', '需求沟通', '方案确认', '建模', '软装', 
      '渲染', '后期', '尾款结算', '客户评价', '投诉处理'
    ];
    
    // 获取当前阶段和检查阶段的索引
    const currentStageIndex = stageOrder.indexOf(this.project.currentStage);
    const checkStageIndex = stageOrder.indexOf(stage);
    
    // 如果检查阶段在当前阶段之前，则已完成
    return checkStageIndex < currentStageIndex;
  }
  
  // 查看阶段详情
  viewStageDetails(stage: ProjectStage): void {
    // 这里可以实现查看特定阶段详情的功能
    alert(`查看${stage}阶段详情`);
    // 在实际应用中，这里可以：
    // 1. 显示该阶段的详细信息弹窗
    // 2. 滚动到页面上该阶段的相关内容
    // 3. 加载该阶段的历史记录和完成情况
  }

  ngOnInit(): void {
    this.route.paramMap.subscribe(params => {
      this.projectId = params.get('id') || '';
      this.loadProjectData();
      this.loadExceptionHistories();
      this.loadProjectMembers();
      this.loadProjectFiles();
      this.loadTimelineEvents();
    });
    
    // 添加点击事件监听器，当点击页面其他位置时关闭下拉菜单
    document.addEventListener('click', this.closeDropdownOnClickOutside);
  }

  // 在组件销毁时移除事件监听器和清理资源
  ngOnDestroy(): void {
    if (this.countdownInterval) {
      clearInterval(this.countdownInterval);
    }
    document.removeEventListener('click', this.closeDropdownOnClickOutside);
  }

  // 点击页面其他位置时关闭下拉菜单
  private closeDropdownOnClickOutside = (event: MouseEvent): void => {
    const targetElement = event.target as HTMLElement;
    const projectSwitcher = targetElement.closest('.project-switcher');
    
    if (!projectSwitcher && this.showDropdown) {
      this.showDropdown = false;
    }
  };

  loadProjectData(): void {
    if (this.projectId) {
      this.loadProjectDetails();
      this.loadRenderProgress();
      this.loadModelCheckItems();
      this.loadCustomerFeedbacks();
      this.loadDesignerChanges();
      this.loadSettlements();
      this.loadRequirementChecklist();
    }
    
    // 初始化项目列表数据（模拟）
    this.projects = [
      { id: '1', name: '现代风格客厅设计', status: '进行中' },
      { id: '2', name: '北欧风卧室装修', status: '已完成' },
      { id: '3', name: '新中式书房改造', status: '进行中' },
      { id: '4', name: '工业风餐厅设计', status: '待处理' }
    ];
  }
  
  // 加载项目成员数据
  loadProjectMembers(): void {
    // 模拟API请求获取项目成员数据
    setTimeout(() => {
      this.projectMembers = [
        {
          id: '1',
          name: '李设计师',
          role: '主设计师',
          avatar: '李',
          skillMatch: 95,
          progress: 65,
          contribution: 75
        },
        {
          id: '2',
          name: '陈设计师',
          role: '助理设计师',
          avatar: '陈',
          skillMatch: 88,
          progress: 80,
          contribution: 60
        },
        {
          id: '3',
          name: '王组长',
          role: '项目组长',
          avatar: '王',
          skillMatch: 92,
          progress: 70,
          contribution: 70
        },
        {
          id: '4',
          name: '赵建模师',
          role: '3D建模师',
          avatar: '赵',
          skillMatch: 90,
          progress: 90,
          contribution: 85
        }
      ];
    }, 600);
  }
  
  // 加载项目文件数据
  loadProjectFiles(): void {
    // 模拟API请求获取项目文件数据
    setTimeout(() => {
      this.projectFiles = [
        {
          id: '1',
          name: '客厅设计方案V2.0.pdf',
          type: 'pdf',
          size: '2.5MB',
          date: '2024-02-10',
          url: '#'
        },
        {
          id: '2',
          name: '材质库集合.rar',
          type: 'rar',
          size: '45.8MB',
          date: '2024-02-08',
          url: '#'
        },
        {
          id: '3',
          name: '客厅渲染预览1.jpg',
          type: 'jpg',
          size: '3.2MB',
          date: '2024-02-14',
          url: '#'
        },
        {
          id: '4',
          name: '3D模型文件.max',
          type: 'max',
          size: '87.5MB',
          date: '2024-02-12',
          url: '#'
        },
        {
          id: '5',
          name: '客户需求文档.docx',
          type: 'docx',
          size: '1.2MB',
          date: '2024-01-15',
          url: '#'
        },
        {
          id: '6',
          name: '客厅渲染预览2.jpg',
          type: 'jpg',
          size: '3.8MB',
          date: '2024-02-15',
          url: '#'
        }
      ];
    }, 700);
  }
  
  // 加载团队协作时间轴数据
  loadTimelineEvents(): void {
    // 模拟API请求获取时间轴数据
    setTimeout(() => {
      this.timelineEvents = [
        {
          id: '1',
          time: '2024-02-15 14:30',
          title: '渲染完成',
          action: '完成',
          description: '客厅主视角渲染已完成，等待客户确认'
        },
        {
          id: '2',
          time: '2024-02-14 10:15',
          title: '材质调整',
          action: '更新',
          description: '根据客户反馈调整了沙发和窗帘材质'
        },
        {
          id: '3',
          time: '2024-02-12 16:45',
          title: '模型优化',
          action: '优化',
          description: '优化了模型面数，提高渲染效率'
        },
        {
          id: '4',
          time: '2024-02-10 09:30',
          title: '客户反馈',
          action: '收到',
          description: '收到客户关于颜色和储物空间的反馈意见'
        },
        {
          id: '5',
          time: '2024-02-08 15:20',
          title: '模型提交',
          action: '提交',
          description: '完成3D模型搭建并提交审核'
        }
      ];
    }, 800);
  }
  
  // 加载历史反馈记录
  loadExceptionHistories(): void {
    this.projectService.getExceptionHistories(this.projectId).subscribe(histories => {
      this.exceptionHistories = histories;
    });
  }

  loadProjectDetails(): void {
    this.projectService.getProjectById(this.projectId).subscribe(project => {
      this.project = project;
      // 设置当前阶段
      if (project) {
        this.currentStage = project.currentStage || '';
      }
      // 检查技能匹配度
      this.checkSkillMismatch();
    });
  }
  
  // 整理项目详情
  organizeProject(): void {
    // 模拟整理项目逻辑
    alert('项目详情已整理');
  }
  
  // 检查当前阶段是否显示特定卡片
  shouldShowCard(cardType: string): boolean {
    // 根据项目当前阶段决定是否显示特定卡片
    switch (cardType) {
      case 'modelCheck':
        return ['建模阶段', '渲染阶段', '深化设计'].includes(this.currentStage);
      case 'renderProgress':
        return ['渲染阶段'].includes(this.currentStage);
      case 'exceptionForm':
        return ['渲染阶段', '后期处理'].includes(this.currentStage);
      case 'designerChanges':
        return true; // 所有阶段都显示
      case 'settlement':
        return true; // 所有阶段都显示
      default:
        return true;
    }
  }

  loadRenderProgress(): void {
    this.isLoadingRenderProgress = true;
    this.errorLoadingRenderProgress = false;
    
    // 模拟API加载过程
    setTimeout(() => {
      this.projectService.getRenderProgress(this.projectId).subscribe(progress => {
        this.renderProgress = progress;
        this.isLoadingRenderProgress = false;
        
        // 模拟API加载失败的情况
        if (!progress) {
          this.errorLoadingRenderProgress = true;
          // 通知技术组长
          this.notifyTeamLeader('render-failed');
        } else {
          // 检查是否需要显示超时预警
          this.checkRenderTimeout();
        }
      });
    }, 1000);
  }

  loadModelCheckItems(): void {
    this.projectService.getModelCheckItems().subscribe(items => {
      this.modelCheckItems = items;
    });
  }

  loadCustomerFeedbacks(): void {
    this.projectService.getCustomerFeedbacks().subscribe(feedbacks => {
      this.feedbacks = feedbacks.filter(f => f.projectId === this.projectId);
      // 为反馈添加分类标签
      this.tagCustomerFeedbacks();
      // 检查是否有需要处理的反馈并启动倒计时
      this.checkFeedbackTimeout();
    });
  }

  loadDesignerChanges(): void {
    // 在实际应用中，这里应该从服务中获取设计师变更记录
    // 这里使用模拟数据
    this.designerChanges = [
      {
        id: 'dc1',
        projectId: this.projectId,
        oldDesignerId: 'designer2',
        oldDesignerName: '设计师B',
        newDesignerId: 'designer1',
        newDesignerName: '设计师A',
        changeTime: new Date('2025-09-05'),
        acceptanceTime: new Date('2025-09-05'),
        historicalAchievements: ['完成初步建模', '确定色彩方案'],
        completedWorkload: 30
      }
    ];
  }

  loadSettlements(): void {
    this.projectService.getSettlements().subscribe(settlements => {
      this.settlements = settlements.filter(s => s.projectId === this.projectId);
    });
  }

  loadRequirementChecklist(): void {
    this.projectService.generateRequirementChecklist(this.projectId).subscribe(checklist => {
      this.requirementChecklist = checklist;
    });
  }

  updateModelCheckItem(itemId: string, isPassed: boolean): void {
    this.projectService.updateModelCheckItem(itemId, isPassed).subscribe(() => {
      this.loadModelCheckItems(); // 重新加载检查项
    });
  }

  updateFeedbackStatus(feedbackId: string, status: '处理中' | '已解决'): void {
    this.projectService.updateFeedbackStatus(feedbackId, status).subscribe(() => {
      this.loadCustomerFeedbacks(); // 重新加载反馈
      // 清除倒计时
      if (this.countdownInterval) {
        clearInterval(this.countdownInterval);
        this.feedbackTimeoutCountdown = 0;
      }
    });
  }

  updateProjectStage(stage: ProjectStage): void {
    if (this.project) {
      this.projectService.updateProjectStage(this.projectId, stage).subscribe(() => {
        this.loadProjectDetails(); // 重新加载项目详情
      });
    }
  }

  generateReminderMessage(): void {
    this.projectService.generateReminderMessage('stagnation').subscribe(message => {
      this.reminderMessage = message;
      
      // 3秒后自动清除提醒
      setTimeout(() => {
        this.reminderMessage = '';
      }, 3000);
    });
  }

  retryLoadRenderProgress(): void {
    this.loadRenderProgress();
  }

  // 检查是否所有模型检查项都已通过
  areAllModelChecksPassed(): boolean {
    return this.modelCheckItems.every(item => item.isPassed);
  }

  // 获取技能匹配度警告
  getSkillMismatchWarning(): string | null {
    if (!this.project) return null;
    
    // 模拟技能匹配度检查
    const designerSkills = ['现代风格', '硬装'];
    const requiredSkills = this.project.skillsRequired;
    
    const mismatchedSkills = requiredSkills.filter(skill => !designerSkills.includes(skill));
    
    if (mismatchedSkills.length > 0) {
      return `警告：您不擅长${mismatchedSkills.join('、')}，建议联系组长协调`;
    }
    
    return null;
  }

  // 检查渲染是否超时
  checkRenderTimeout(): void {
    if (!this.renderProgress || !this.project) return;
    
    // 模拟交付前3小时预警
    const deliveryTime = new Date(this.project.deadline);
    const currentTime = new Date();
    const timeDifference = deliveryTime.getTime() - currentTime.getTime();
    const hoursRemaining = Math.floor(timeDifference / (1000 * 60 * 60));
    
    if (hoursRemaining <= 3 && hoursRemaining > 0) {
      // 弹窗预警
      alert('渲染进度预警：交付前3小时，请关注渲染进度');
    }
    
    if (hoursRemaining <= 1 && hoursRemaining > 0) {
      // 更严重的预警
      alert('渲染进度严重预警：交付前1小时，渲染可能无法按时完成！');
    }
  }

  // 为客户反馈添加分类标签
  tagCustomerFeedbacks(): void {
    this.feedbacks.forEach(feedback => {
      // 添加分类标签
      if (feedback.content.includes('色彩') || feedback.problemLocation?.includes('色彩')) {
        (feedback as any).tag = '色彩问题';
      } else if (feedback.content.includes('家具') || feedback.problemLocation?.includes('家具')) {
        (feedback as any).tag = '家具款式问题';
      } else if (feedback.content.includes('光线') || feedback.content.includes('照明')) {
        (feedback as any).tag = '光线问题';
      } else {
        (feedback as any).tag = '其他问题';
      }
    });
  }
  
  // 获取反馈标签的辅助方法
  getFeedbackTag(feedback: CustomerFeedback): string {
    return (feedback as any).tag || '';
  }

  // 检查反馈超时
  checkFeedbackTimeout(): void {
    const pendingFeedbacks = this.feedbacks.filter(f => f.status === '待处理');
    if (pendingFeedbacks.length > 0) {
      // 启动1小时倒计时
      this.feedbackTimeoutCountdown = 3600; // 3600秒 = 1小时
      this.startCountdown();
    }
  }

  // 启动倒计时
  startCountdown(): void {
    this.countdownInterval = setInterval(() => {
      if (this.feedbackTimeoutCountdown > 0) {
        this.feedbackTimeoutCountdown--;
      } else {
        clearInterval(this.countdownInterval);
        // 超时提醒
        alert('客户反馈已超过1小时未响应，请立即处理！');
        this.notifyTeamLeader('feedback-overdue');
      }
    }, 1000);
  }

  // 通知技术组长
  notifyTeamLeader(type: 'render-failed' | 'feedback-overdue' | 'skill-mismatch'): void {
    // 实际应用中应调用消息服务通知组长
    console.log(`通知技术组长：${type} - 项目ID: ${this.projectId}`);
  }

  // 检查技能匹配度并提示
  checkSkillMismatch(): void {
    const warning = this.getSkillMismatchWarning();
    if (warning) {
      // 显示技能不匹配警告
      if (confirm(`${warning}\n是否联系技术组长协调支持？`)) {
        this.notifyTeamLeader('skill-mismatch');
      }
    }
  }

  // 发起设计师变更
  initiateDesignerChange(reason: string): void {
    // 实际应用中应调用API发起变更
    console.log(`发起设计师变更，原因：${reason}`);
    alert('已发起设计师变更申请，请等待新设计师承接');
  }

  // 确认承接变更项目
  acceptDesignerChange(changeId: string): void {
    // 实际应用中应调用API确认承接
    console.log(`确认承接设计师变更：${changeId}`);
    alert('已确认承接项目，系统已记录时间戳和责任人');
  }

  // 格式化倒计时显示
  formatCountdown(seconds: number): string {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const remainingSeconds = seconds % 60;
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
  }



  // 提交异常反馈
  submitExceptionFeedback(): void {
    if (!this.exceptionDescription.trim() || this.isSubmittingFeedback) {
      alert('请填写异常类型和描述');
      return;
    }

    this.isSubmittingFeedback = true;
    
    // 模拟提交反馈到服务器
    setTimeout(() => {
      const newException: ExceptionHistory = {
        id: `exception-${Date.now()}`,
        type: this.exceptionType,
        description: this.exceptionDescription,
        submitTime: new Date(),
        status: '待处理'
      };

      // 添加到历史记录中
      this.exceptionHistories.unshift(newException);
      
      // 通知客服和技术支持
      this.notifyTechnicalSupport(newException);
      
      // 清空表单
      this.exceptionDescription = '';
      this.clearExceptionScreenshot();
      this.showExceptionForm = false;
      
      // 显示成功消息
      alert('异常反馈已提交，技术支持将尽快处理');
      
      this.isSubmittingFeedback = false;
    }, 1000);
  }

  // 上传异常截图
  uploadExceptionScreenshot(event: Event): void {
    const input = event.target as HTMLInputElement;
    if (input.files && input.files[0]) {
      const file = input.files[0];
      // 在实际应用中，这里应该上传文件到服务器
      // 这里我们使用FileReader来生成一个预览URL
      const reader = new FileReader();
      reader.onload = (e) => {
        this.exceptionScreenshotUrl = e.target?.result as string;
      };
      reader.readAsDataURL(file);
    }
  }

  // 清除异常截图
  clearExceptionScreenshot(): void {
    this.exceptionScreenshotUrl = null;
    const input = document.getElementById('screenshot-upload') as HTMLInputElement;
    if (input) {
      input.value = '';
    }
  }

  // 联系组长
  contactTeamLeader() {
    alert(`已联系${this.project?.assigneeName || '项目组长'}`);
  }

  // 处理渲染超时预警
  handleRenderTimeout() {
    alert('已发送渲染超时预警通知');
  }

  // 通知技术支持
  notifyTechnicalSupport(exception: ExceptionHistory): void {
    // 实际应用中应调用消息服务通知技术支持和客服
    console.log(`通知技术支持和客服：渲染异常 - 项目ID: ${this.projectId}`);
    console.log(`异常类型: ${this.getExceptionTypeText(exception.type)}, 描述: ${exception.description}`);
  }

  // 获取异常类型文本
  getExceptionTypeText(type: string): string {
    const typeMap: Record<string, string> = {
      'failed': '渲染失败',
      'stuck': '渲染卡顿',
      'quality': '渲染质量问题',
      'other': '其他问题'
    };
    return typeMap[type] || type;
  }

  // 格式化日期
  formatDate(date: Date | string): string {
    const d = typeof date === 'string' ? new Date(date) : date;
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const hours = String(d.getHours()).padStart(2, '0');
    const minutes = String(d.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  }
}
