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

// 定义接口
interface TestForm {
  description: string;
}

interface TechnicalEvaluationItem {
  name: string;
  value: number;
  status: 'high' | 'medium' | 'low';
}

interface ReferenceImage {
  url: string;
  hint: string;
}

interface TestResult {
  overallStatus: 'pass' | 'warning' | 'fail';
  technicalEvaluation: TechnicalEvaluationItem[];
  requirementMatch: string;
  modificationSuggestions: string[];
  referenceImages: ReferenceImage[];
}

interface AssignmentForm {
  projectId: string;
  assignmentType: 'customer-service' | 'system-recommend';
  specifiedDesignerId: string;
}

interface Designer {
  id: string;
  name: string;
  skills: string;
  workload: number;
  completionRate: number;
  satisfactionRate: number;
  matchScore?: number;
}

interface DesignerWorkloadStatus {
  status: 'idle' | 'medium' | 'busy';
  message: string;
}

interface Project {
  id: string;
  name: string;
  type: string;
  complexity: string;
  deadline: string;
}

interface AssignmentResult {
  message: string;
  projectName: string;
  designerName: string;
  assignTime: Date;
}

// 工作量预估相关接口
interface WorkloadEstimationForm {
  area: number;
  complexity: 'low' | 'medium' | 'high';
  deliveryRequirements: 'standard' | 'premium' | 'vip';
}

interface WorkloadEstimationResult {
  totalHours: number;
  breakdown: {
    modeling: number;
    rendering: number;
    postProduction: number;
  };
  suggestions: string[];
}

@Component({
  selector: 'app-project-review',
  templateUrl: './project-review.html',
  styleUrls: ['./project-review.scss'],
  standalone: true,
  imports: [FormsModule, CommonModule]
})
export class ProjectReviewComponent implements OnInit {
  // 表单数据
  testForm: TestForm = {
    description: ''
  };
  
  assignmentForm: AssignmentForm = {
    projectId: '',
    assignmentType: 'customer-service',
    specifiedDesignerId: ''
  };
  
  // 工作量预估表单
  workloadEstimationForm: WorkloadEstimationForm = {
    area: 0,
    complexity: 'medium',
    deliveryRequirements: 'standard'
  };
  
  // 状态数据
  selectedImage: string | null = null;
  testResult: TestResult | null = null;
  designerWorkloadStatus: DesignerWorkloadStatus | null = null;
  assignmentResult: AssignmentResult | null = null;
  workloadEstimationResult: WorkloadEstimationResult | null = null;
  showWorkloadEstimator: boolean = false;
  
  // 模拟数据
  availableProjects: Project[] = [];
  designers: Designer[] = [];
  alternativeDesigners: Designer[] = [];
  recommendedDesigners: Designer[] = [];
  
  constructor(private route: ActivatedRoute, private router: Router) {}
  
  ngOnInit(): void {
    this.loadMockData();
  }
  
  // 加载模拟数据
  loadMockData(): void {
    // 模拟项目数据
    this.availableProjects = [
      { id: '1', name: '现代风格80㎡软装设计', type: '软装', complexity: '中等', deadline: '2024-11-15' },
      { id: '2', name: '新中式客厅效果图', type: '硬装', complexity: '高', deadline: '2024-11-20' },
      { id: '3', name: '北欧风格卧室改造', type: '软装', complexity: '低', deadline: '2024-11-10' },
      { id: '4', name: '宋式风格别墅客厅', type: '硬装', complexity: '高', deadline: '2024-12-05' }
    ];
    
    // 模拟设计师数据
    this.designers = [
      { id: '101', name: '张三', skills: '现代风格、北欧风格', workload: 90, completionRate: 95, satisfactionRate: 92 },
      { id: '102', name: '李四', skills: '新中式、宋式风格', workload: 45, completionRate: 90, satisfactionRate: 88 },
      { id: '103', name: '王五', skills: '北欧风格、日式风格', workload: 60, completionRate: 85, satisfactionRate: 90 },
      { id: '104', name: '赵六', skills: '现代风格、轻奢风格', workload: 30, completionRate: 88, satisfactionRate: 94 }
    ];
  }
  
  // 文件选择处理
  onFileSelected(event: Event): void {
    const input = event.target as HTMLInputElement;
    if (input.files && input.files[0]) {
      const reader = new FileReader();
      reader.onload = (e) => {
        this.selectedImage = e.target?.result as string;
      };
      reader.readAsDataURL(input.files[0]);
    }
  }
  
  // 移除图片
  removeImage(): void {
    this.selectedImage = null;
  }
  
  // 运行可行性测试
  runFeasibilityTest(): void {
    // 模拟测试过程
    // 在实际应用中，这里应该调用后端API进行真实的可行性测试
    
    // 模拟加载效果
    setTimeout(() => {
      // 生成模拟测试结果
      const technicalEvaluation: TechnicalEvaluationItem[] = [
        { name: '氛围匹配度', value: Math.floor(Math.random() * 30) + 70, status: 'high' },
        { name: '美感达标率', value: Math.floor(Math.random() * 40) + 60, status: 'medium' },
        { name: '渲染真实度', value: Math.floor(Math.random() * 30) + 70, status: 'high' }
      ];
      
      // 根据技术评估计算总体状态
      const avgScore = technicalEvaluation.reduce((sum, item) => sum + item.value, 0) / technicalEvaluation.length;
      let overallStatus: 'pass' | 'warning' | 'fail';
      if (avgScore >= 80) {
        overallStatus = 'pass';
      } else if (avgScore >= 60) {
        overallStatus = 'warning';
      } else {
        overallStatus = 'fail';
      }
      
      // 模拟参考图片（使用国内CDN）
      const referenceImages: ReferenceImage[] = [
        { url: 'https://img.alicdn.com/imgextra/i3/1111111111/O1CN01abcdefg_1234567890.jpg_220x220xz.jpg', hint: '宋式风格软装布局参考' },
        { url: 'https://img.alicdn.com/imgextra/i4/2222222222/O1CN01hijklmn_1234567890.jpg_220x220xz.jpg', hint: '暖色调灯光效果参考' },
        { url: 'https://img.alicdn.com/imgextra/i5/3333333333/O1CN01opqrstu_1234567890.jpg_220x220xz.jpg', hint: '客厅空间划分参考' }
      ];
      
      // 模拟修改建议
      const modificationSuggestions = [
        '调整灯光色温，使其更符合暖色调要求',
        '增加一些宋式风格的装饰元素',
        '优化空间层次感，增强视觉深度'
      ];
      
      this.testResult = {
        overallStatus,
        technicalEvaluation,
        requirementMatch: '整体符合客户需求，但在风格细节和色彩匹配上还有优化空间',
        modificationSuggestions,
        referenceImages
      };
    }, 1500);
  }
  
  // 获取状态标签
  getStatusLabel(status: string): string {
    switch (status) {
      case 'high':
        return '优秀';
      case 'medium':
        return '一般';
      case 'low':
        return '较差';
      default:
        return '';
    }
  }
  
  // 提交至质量管理
  submitToQualityManagement(): void {
    // 在实际应用中，这里应该调用API将测试结果提交到质量管理模块
    alert('测试结果已提交至质量管理模块！');
    // 跳转到质量管理页面
    this.router.navigate(['team-leader/quality-management']);
  }
  
  // 分配类型变更处理
  onAssignmentTypeChange(): void {
    this.assignmentForm.specifiedDesignerId = '';
    this.designerWorkloadStatus = null;
    this.alternativeDesigners = [];
    this.recommendedDesigners = [];
    
    // 如果选择系统推荐，自动获取推荐设计师
    if (this.assignmentForm.assignmentType === 'system-recommend' && this.assignmentForm.projectId) {
      this.getRecommendedDesigners();
    }
  }
  
  // 检查设计师工作量
  checkDesignerWorkload(): void {
    if (!this.assignmentForm.specifiedDesignerId) {
      this.designerWorkloadStatus = null;
      return;
    }
    
    const designer = this.designers.find(d => d.id === this.assignmentForm.specifiedDesignerId);
    if (designer) {
      let status: 'idle' | 'medium' | 'busy';
      let message: string;
      
      if (designer.workload <= 50) {
        status = 'idle';
        message = `${designer.name} 当前工作量充足（${designer.workload}%）`;
      } else if (designer.workload <= 80) {
        status = 'medium';
        message = `${designer.name} 当前工作量适中（${designer.workload}%）`;
      } else {
        status = 'busy';
        message = `${designer.name} 当前工作量较高（${designer.workload}%）`;
        // 生成备选设计师
        this.generateAlternativeDesigners();
      }
      
      this.designerWorkloadStatus = { status, message };
    }
  }
  
  // 生成备选设计师
  generateAlternativeDesigners(): void {
    // 筛选工作量≤60%的设计师
    this.alternativeDesigners = this.designers
      .filter(d => d.id !== this.assignmentForm.specifiedDesignerId && d.workload <= 60)
      .slice(0, 3);
  }
  
  // 选择备选设计师
  selectAlternativeDesigner(designerId: string): void {
    this.assignmentForm.specifiedDesignerId = designerId;
    this.checkDesignerWorkload();
  }
  
  // 获取推荐设计师
  getRecommendedDesigners(): void {
    // 在实际应用中，这里应该根据项目需求和设计师能力进行智能推荐
    // 这里使用模拟数据生成推荐
    if (!this.assignmentForm.projectId) {
      this.recommendedDesigners = [];
      return;
    }
    
    const selectedProject = this.availableProjects.find(p => p.id === this.assignmentForm.projectId);
    if (!selectedProject) {
      return;
    }
    
    // 根据项目类型和复杂度生成推荐分数
    this.recommendedDesigners = this.designers
      .map(designer => {
        let matchScore = 50; // 基础分数
        
        // 根据项目类型调整匹配分数
        if (selectedProject.type === '软装' && designer.skills.includes('现代风格')) {
          matchScore += 20;
        } else if (selectedProject.type === '硬装' && designer.skills.includes('中式')) {
          matchScore += 25;
        }
        
        // 根据工作量调整匹配分数
        if (designer.workload <= 30) {
          matchScore += 20;
        } else if (designer.workload <= 60) {
          matchScore += 10;
        }
        
        // 根据完成率和满意度调整分数
        matchScore += (designer.completionRate - 80) / 5;
        matchScore += (designer.satisfactionRate - 85) / 5;
        
        return { ...designer, matchScore: Math.min(Math.max(Math.round(matchScore), 0), 100) };
      })
      .filter(designer => designer.workload <= 60) // 只推荐工作量≤60%的设计师
      .sort((a, b) => b.matchScore! - a.matchScore!)
      .slice(0, 3);
  }
  
  // 确认推荐设计师分配
  confirmAssignment(designerId: string): void {
    this.assignmentForm.specifiedDesignerId = designerId;
  }
  
  // 检查是否可以执行分配
  canExecuteAssignment(): boolean {
    if (!this.assignmentForm.projectId || !this.assignmentForm.specifiedDesignerId) {
      return false;
    }
    
    // 如果是客服指定分配，需要检查工作量状态是否为idle或medium
    if (this.assignmentForm.assignmentType === 'customer-service' && 
        this.designerWorkloadStatus && 
        this.designerWorkloadStatus.status === 'busy') {
      return false;
    }
    
    return true;
  }
  
  // 执行分配
  executeAssignment(): void {
    if (!this.canExecuteAssignment()) {
      return;
    }
    
    const selectedProject = this.availableProjects.find(p => p.id === this.assignmentForm.projectId);
    const selectedDesigner = this.designers.find(d => d.id === this.assignmentForm.specifiedDesignerId);
    
    if (selectedProject && selectedDesigner) {
      // 模拟分配过程
      setTimeout(() => {
        this.assignmentResult = {
          message: `项目已成功分配给设计师 ${selectedDesigner.name}`,
          projectName: selectedProject.name,
          designerName: selectedDesigner.name,
          assignTime: new Date()
        };
        
        // 在实际应用中，这里应该调用API更新项目分配状态
        // 并同步到dashboard和设计师工作台
        
        // 显示成功消息后，重置表单
        setTimeout(() => {
          this.resetAssignmentForm();
        }, 3000);
      }, 1000);
    }
  }
  
  // 重置分配表单
  resetAssignmentForm(): void {
    this.assignmentForm = {
      projectId: '',
      assignmentType: 'customer-service',
      specifiedDesignerId: ''
    };
    this.designerWorkloadStatus = null;
    this.alternativeDesigners = [];
    this.recommendedDesigners = [];
    this.assignmentResult = null;
  }
  
  // 项目选择变更处理
  onProjectChange(): void {
    if (this.assignmentForm.assignmentType === 'system-recommend') {
      this.getRecommendedDesigners();
    }
  }
  
  // 计算工作量预估
  calculateWorkloadEstimation(): void {
    // 重置之前的结果
    this.workloadEstimationResult = null;
    
    // 验证表单数据
    if (!this.workloadEstimationForm.area || this.workloadEstimationForm.area <= 0) {
      alert('请输入有效的面积');
      return;
    }
    
    // 模拟计算过程
    // 在实际应用中，这里应该根据具体的业务规则和算法进行计算
    
    // 根据面积、复杂度和交付要求计算总工时
    const areaMultiplier = this.workloadEstimationForm.area / 100;
    const complexityMultiplier = this.getComplexityMultiplier();
    const deliveryMultiplier = this.getDeliveryMultiplier();
    
    // 基础工时计算
    const baseHours = 20; // 基础工时
    const totalHours = Math.round(baseHours * areaMultiplier * complexityMultiplier * deliveryMultiplier);
    
    // 各阶段工时分配
    const modelingHours = Math.round(totalHours * 0.4);
    const renderingHours = Math.round(totalHours * 0.35);
    const postProductionHours = Math.round(totalHours * 0.25);
    
    // 生成建议
    const suggestions = this.generateWorkloadSuggestions(totalHours, modelingHours);
    
    // 存储计算结果
    this.workloadEstimationResult = {
      totalHours,
      breakdown: {
        modeling: modelingHours,
        rendering: renderingHours,
        postProduction: postProductionHours
      },
      suggestions
    };
  }
  
  // 获取复杂度乘数
  private getComplexityMultiplier(): number {
    switch (this.workloadEstimationForm.complexity) {
      case 'low':
        return 0.8;
      case 'medium':
        return 1.0;
      case 'high':
        return 1.5;
      default:
        return 1.0;
    }
  }
  
  // 获取交付要求乘数
  private getDeliveryMultiplier(): number {
    switch (this.workloadEstimationForm.deliveryRequirements) {
      case 'standard':
        return 1.0;
      case 'premium':
        return 1.2;
      case 'vip':
        return 1.5;
      default:
        return 1.0;
    }
  }
  
  // 生成工作量建议
  private generateWorkloadSuggestions(totalHours: number, modelingHours: number): string[] {
    const suggestions = [];
    
    if (totalHours > 100) {
      suggestions.push('项目工时较长，建议安排资深设计师或增加设计人员');
    }
    
    if (modelingHours > 50) {
      suggestions.push('建模阶段工时较多，建议在建模前进行详细的需求确认');
    }
    
    if (this.workloadEstimationForm.complexity === 'high' && this.workloadEstimationForm.deliveryRequirements === 'vip') {
      suggestions.push('复杂度高且交付要求高，建议增加项目检查点和评审次数');
    }
    
    if (suggestions.length === 0) {
      suggestions.push('项目工作量估算合理，可以按照正常流程进行');
    }
    
    return suggestions;
  }
  
  // 格式化工时显示
  formatWorkloadHours(hours: number): string {
    if (hours < 8) {
      return `${hours}小时`;
    }
    const days = Math.floor(hours / 8);
    const remainingHours = hours % 8;
    if (remainingHours === 0) {
      return `${days}天`;
    }
    return `${days}天${remainingHours}小时`;
  }
  
  // 重置工作量预估表单
  resetWorkloadEstimationForm(): void {
    this.workloadEstimationForm = {
      area: 0,
      complexity: 'medium',
      deliveryRequirements: 'standard'
    };
    this.workloadEstimationResult = null;
  }
  
  // 切换工作量预估工具显示状态
  toggleWorkloadEstimator(): void {
    this.showWorkloadEstimator = !this.showWorkloadEstimator;
    if (this.showWorkloadEstimator) {
      // 如果打开，重置表单
      this.resetWorkloadEstimationForm();
    }
  }
}
