import { Injectable } from '@angular/core';

interface DesignerTags {
  expertise: {
    styles: string[];      // 擅长风格
    skills: string[];      // 专业技能
    spaceTypes: string[];  // 擅长空间
  };
  capacity: {
    weeklyProjects: number;    // 单周可处理项目量
    maxConcurrent: number;     // 最大并发数
    avgDaysPerProject: number; // 平均完成天数
  };
  emergency: {
    willing: boolean;    // 是否接受紧急单
    premium: number;     // 加急溢价（%）
    maxPerWeek: number;  // 每周最多紧急单数
  };
  history: {
    totalProjects: number;  // 历史总项目数
    completionRate: number; // 完成率（%）
    avgRating: number;      // 平均评分
    onTimeRate: number;     // 按时交付率（%）
    excellentCount: number; // 优秀作品数
  };
  portfolio: string[]; // 代表作（ProjectFile objectId数组）
}

@Injectable({
  providedIn: 'root'
})
export class DesignerService {
  private cid: string = '';
  private Parse: any = null;
  
  constructor() {
    this.cid = localStorage.getItem('company') || '';
    this.initParse();
  }
  
  /**
   * 延迟初始化Parse
   */
  private async initParse(): Promise<void> {
    try {
      const { FmodeParse } = await import('fmode-ng/parse');
      this.Parse = FmodeParse.with("nova");
    } catch (error) {
      console.error('DesignerService: FmodeParse 初始化失败:', error);
    }
  }
  
  /**
   * 确保Parse已初始化
   */
  private async ensureParse(): Promise<any> {
    if (!this.Parse) {
      await this.initParse();
    }
    return this.Parse;
  }
  
  /**
   * 获取所有设计师（组员角色）
   */
  async getDesigners(): Promise<any[]> {
    const Parse = await this.ensureParse();
    if (!Parse) return [];
    
    try {
      // 查询所有组员（设计师角色）
      const query = new Parse.Query('Profile');
      query.equalTo('company', this.cid);
      query.equalTo('roleName', '组员'); // 只查询组员
      query.notEqualTo('isDeleted', true);
      query.include('department'); // 关联部门
      query.include('user'); // 🔧 关联用户信息，尝试获取名字
      query.limit(1000);
      
      const profiles = await query.find();
      
      return profiles.map((p: any, index: number) => {
        const data = p.get('data') || {};
        const tags = data.tags || this.getDefaultTags();
        
        // 🔧 尝试多种方式获取名字（优先级从高到低）
        let name = p.get('name'); // 1. 优先使用 Profile.name
        
        if (!name) {
          // 2. 尝试从 user 获取
          const user = p.get('user');
          if (user) {
            name = user.get ? user.get('name') : user.name;
            if (!name && user.get) {
              name = user.get('nickname') || user.get('realName');
            }
          }
        }
        
        if (!name) {
          // 3. 使用手机号作为备用显示
          const mobile = p.get('mobile');
          if (mobile) {
            name = `设计师-${mobile.slice(-4)}`; // 显示为 "设计师-1234"
          }
        }
        
        if (!name) {
          // 4. 最后使用 ID 后4位
          name = `设计师-${p.id.slice(-4)}`;
        }
        
        return {
          id: p.id,
          name: name,
          mobile: p.get('mobile') || '',
          department: p.get('department')?.get?.('name') || '未分组',
          departmentId: p.get('department')?.id || '',
          roleName: p.get('roleName'),
          tags,
          data,
          profile: p
        };
      });
    } catch (error) {
      console.error('❌ 获取设计师列表失败:', error);
      return [];
    }
  }
  
  /**
   * 更新设计师tags
   * @param designerId 设计师ID
   * @param tags tags数据
   */
  async updateDesignerTags(designerId: string, tags: Partial<DesignerTags>): Promise<boolean> {
    const Parse = await this.ensureParse();
    if (!Parse) return false;
    
    try {
      const query = new Parse.Query('Profile');
      const profile = await query.get(designerId);
      
      const currentData = profile.get('data') || {};
      const currentTags = currentData.tags || this.getDefaultTags();
      
      // 深度合并tags
      const updatedTags = {
        ...currentTags,
        ...tags,
        expertise: { ...currentTags.expertise, ...tags.expertise },
        capacity: { ...currentTags.capacity, ...tags.capacity },
        emergency: { ...currentTags.emergency, ...tags.emergency },
        history: { ...currentTags.history, ...tags.history }
      };
      
      profile.set('data', {
        ...currentData,
        tags: updatedTags
      });
      
      await profile.save();
      
      return true;
    } catch (error) {
      console.error('更新设计师tags失败:', error);
      return false;
    }
  }
  
  /**
   * 查询设计师当前负载
   */
  async getDesignerWorkload(designerId: string): Promise<{
    projects: any[];
    weightedTotal: number;
    overdueCount: number;
    loadRate: number;
  }> {
    const Parse = await this.ensureParse();
    if (!Parse) {
      return { projects: [], weightedTotal: 0, overdueCount: 0, loadRate: 0 };
    }
    
    try {
      // 查询设计师负责的所有进行中项目
      const query = new Parse.Query('Project');
      const designerPointer = Parse.Object.extend('Profile').createWithoutData(designerId);
      query.equalTo('assignee', designerPointer);
      query.equalTo('company', this.cid);
      query.containedIn('status', ['进行中', '待分配']);
      query.notEqualTo('isDeleted', true);
      query.select('title', 'deadline', 'status', 'data');
      query.limit(1000);
      
      const projects = await query.find();
      
      // 计算加权总量
      let weightedTotal = 0;
      let overdueCount = 0;
      const now = new Date();
      
      projects.forEach((proj: any) => {
        const weight = this.calculateProjectWeight(proj);
        weightedTotal += weight;
        
        const deadline = proj.get('deadline');
        if (deadline && deadline < now) {
          overdueCount++;
        }
      });
      
      // 获取设计师单周处理量
      const designers = await this.getDesigners();
      const designer = designers.find(d => d.id === designerId);
      const weeklyCapacity = designer?.tags?.capacity?.weeklyProjects || 3;
      
      // 计算负载率
      const loadRate = weeklyCapacity > 0 ? (weightedTotal / weeklyCapacity * 100) : 0;
      
      return {
        projects: projects.map((p: any) => p.toJSON()),
        weightedTotal,
        overdueCount,
        loadRate
      };
    } catch (error) {
      console.error('❌ 获取设计师负载失败:', error);
      return { projects: [], weightedTotal: 0, overdueCount: 0, loadRate: 0 };
    }
  }
  
  /**
   * 计算项目加权值
   */
  calculateProjectWeight(project: any): number {
    const data = project.get?.('data') || project.data || {};
    
    // 1. 项目类型系数
    const projectType = data.projectType || 'soft';
    const typeWeight = projectType === 'hard' ? 2.0 : 1.0;
    
    // 2. 剩余工期系数
    const deadlineRaw = project.get?.('deadline') || project.deadline;
    const deadline = deadlineRaw instanceof Date ? deadlineRaw : (deadlineRaw ? new Date(deadlineRaw) : null);
    const now = new Date();
    const daysLeft = deadline ? Math.ceil((deadline.getTime() - now.getTime()) / (1000 * 60 * 60 * 24)) : 30;
    
    let timeWeight = 0.8;
    if (daysLeft < 0) timeWeight = 1.5;      // 超期
    else if (daysLeft <= 3) timeWeight = 1.3; // 临期
    else if (daysLeft <= 7) timeWeight = 1.0;
    else timeWeight = 0.8;
    
    // 3. 紧急度系数
    const urgency = data.urgency || 'low';
    const urgencyWeight = urgency === 'high' ? 1.2 : urgency === 'medium' ? 1.0 : 0.8;
    
    return typeWeight * timeWeight * urgencyWeight;
  }
  
  /**
   * 获取所有项目
   */
  async getProjects(): Promise<any[]> {
    const Parse = await this.ensureParse();
    if (!Parse) {
      console.error('❌ Parse未初始化，无法查询项目');
      return [];
    }
    
    if (!this.cid) {
      console.error('❌ 未找到公司ID（localStorage的company字段为空），无法查询项目');
      return [];
    }
    
    try {
      const query = new Parse.Query('Project');
      query.equalTo('company', this.cid);
      query.notEqualTo('isDeleted', true);
      query.include('assignee', 'contact');
      query.descending('updatedAt');
      query.limit(1000);
      
      const projects = await query.find();
      
      return projects.map((p: any) => this.transformProject(p));
    } catch (error) {
      console.error('❌ 获取项目列表失败:', error);
      return [];
    }
  }
  
  /**
   * 转换Project为前端格式
   */
  private transformProject(project: any): any {
    const data = project.get('data') || {};
    const deadlineRaw = project.get('deadline');
    const deadline = deadlineRaw instanceof Date ? deadlineRaw : (deadlineRaw ? new Date(deadlineRaw) : new Date());
    const now = new Date();
    const daysLeft = Math.ceil((deadline.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
    
    const assignee = project.get('assignee');
    const contact = project.get('contact');
    
    // 根据currentStage确定阶段
    const currentStage = project.get('currentStage') || 'pendingAssignment';
    
    // 构建phases数组（模拟百分比进度）
    const phasesList = [
      { name: '需求沟通', percentage: 0, startPercentage: 0, isCompleted: false, isCurrent: false },
      { name: '方案规划', percentage: 0, startPercentage: 20, isCompleted: false, isCurrent: false },
      { name: '建模阶段', percentage: 0, startPercentage: 40, isCompleted: false, isCurrent: false },
      { name: '渲染阶段', percentage: 0, startPercentage: 60, isCompleted: false, isCurrent: false },
      { name: '交付完成', percentage: 0, startPercentage: 80, isCompleted: false, isCurrent: false }
    ];
    
    const stageMap: Record<string, number> = {
      'pendingApproval': 0,
      'pendingAssignment': 0,
      'requirement': 1,
      'planning': 2,
      'modeling': 3,
      'rendering': 4,
      'postProduction': 4,
      'review': 4,
      'revision': 4,
      'delivery': 5
    };
    
    const currentPhaseIndex = stageMap[currentStage] || 0;
    phasesList.forEach((phase, index) => {
      if (index < currentPhaseIndex) {
        phase.isCompleted = true;
        phase.percentage = 20;
      } else if (index === currentPhaseIndex) {
        phase.isCurrent = true;
        phase.percentage = 10;
      }
    });
    
    return {
      id: project.id,
      name: project.get('title') || '未命名项目',
      type: data.projectType || 'soft',
      memberType: data.memberType || 'normal',
      designerName: assignee?.get('name') || '未分配',
      designerId: assignee?.id || '',
      customerName: contact?.get('name') || '未知客户',
      status: project.get('status') || '待分配',
      currentStage,
      deadline,
      createdAt: project.get('createdAt'),
      isOverdue: daysLeft < 0,
      overdueDays: daysLeft < 0 ? Math.abs(daysLeft) : 0,
      dueSoon: daysLeft >= 0 && daysLeft <= 3,
      urgency: data.urgency || 'low',
      weight: this.calculateProjectWeight(project),
      phases: phasesList,
      qualityRating: data.qualityRating || 'pending',
      lastCustomerFeedback: data.lastCustomerFeedback || '',
      data,
      project
    };
  }
  
  /**
   * 默认标签（新员工）
   */
  private getDefaultTags(): DesignerTags {
    return {
      expertise: {
        styles: [],
        skills: [],
        spaceTypes: []
      },
      capacity: {
        weeklyProjects: 2,
        maxConcurrent: 3,
        avgDaysPerProject: 10
      },
      emergency: {
        willing: false,
        premium: 0,
        maxPerWeek: 0
      },
      history: {
        totalProjects: 0,
        completionRate: 0,
        avgRating: 0,
        onTimeRate: 0,
        excellentCount: 0
      },
      portfolio: []
    };
  }
  
  /**
   * 智能匹配算法
   */
  async getRecommendedDesigners(
    project: any,
    allDesigners?: any[]
  ): Promise<Array<{
    designer: any;
    matchScore: number;
    reason: string;
    loadRate: number;
    currentProjects: number;
  }>> {
    if (!allDesigners) {
      allDesigners = await this.getDesigners();
    }
    
    const projectStyle = project.data?.style || project.data?.requirement?.style || '';
    const isEmergency = project.urgency === 'high';
    
    const recommendations = [];
    
    for (const designer of allDesigners) {
      // 1. 风格匹配分（30分）
      let styleScore = 0;
      const styles = designer.tags.expertise.styles || [];
      if (projectStyle && styles.includes(projectStyle)) {
        styleScore = 30;
      } else if (styles.length > 0) {
        styleScore = 10; // 有标签但不完全匹配
      }
      
      // 2. 负载适配分（30分）
      const workload = await this.getDesignerWorkload(designer.id);
      let loadScore = 0;
      if (workload.loadRate < 60) loadScore = 30;
      else if (workload.loadRate < 80) loadScore = 20;
      else if (workload.loadRate < 100) loadScore = 10;
      else loadScore = 0;
      
      // 3. 历史表现分（25分）
      const history = designer.tags.history;
      const performanceScore = (
        (history.completionRate || 0) * 0.4 +
        (history.onTimeRate || 0) * 0.3 +
        ((history.avgRating || 0) / 5 * 100) * 0.3
      ) * 0.25;
      
      // 4. 紧急适配分（15分，仅紧急项目）
      let emergencyScore = 0;
      if (isEmergency) {
        if (designer.tags.emergency.willing) {
          emergencyScore = 15;
        }
      }
      
      const matchScore = styleScore + loadScore + performanceScore + emergencyScore;
      
      // 生成推荐理由
      const reason = [];
      if (styleScore >= 20) reason.push('风格匹配度高');
      if (loadScore >= 25) reason.push('负载空闲');
      else if (loadScore >= 15) reason.push('负载适中');
      if (performanceScore >= 20) reason.push('历史表现优秀');
      if (emergencyScore > 0) reason.push('愿意接急单');
      
      if (matchScore >= 40) {
        recommendations.push({
          designer,
          matchScore: Math.round(matchScore),
          reason: reason.join('、') || '基础匹配',
          loadRate: workload.loadRate,
          currentProjects: workload.projects.length
        });
      }
    }
    
    return recommendations
      .sort((a, b) => b.matchScore - a.matchScore)
      .slice(0, 5);
  }
  
  /**
   * 分配项目给设计师
   */
  async assignProject(projectId: string, designerId: string): Promise<boolean> {
    const Parse = await this.ensureParse();
    if (!Parse) return false;
    
    try {
      const project = Parse.Object.extend('Project').createWithoutData(projectId);
      const designer = Parse.Object.extend('Profile').createWithoutData(designerId);
      
      project.set('assignee', designer);
      project.set('status', '进行中');
      
      await project.save();
      return true;
    } catch (error) {
      console.error('项目分配失败:', error);
      return false;
    }
  }
}

