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

/**
 * 项目数据服务
 * 负责组长端项目数据的增删查改操作
 */
@Injectable({
  providedIn: 'root'
})
export class ProjectDataService {
  private cid: string = '';
  private Parse: any = null;
  
  constructor() {
    this.cid = localStorage.getItem('company') || '';
    console.log('🏢 ProjectDataService初始化，当前公司ID:', this.cid || '（未设置）');
    this.initParse();
  }
  
  /**
   * 延迟初始化Parse
   */
  private async initParse(): Promise<void> {
    try {
      const { FmodeParse } = await import('fmode-ng/parse');
      this.Parse = FmodeParse.with("nova");
      console.log('✅ ProjectDataService: FmodeParse 初始化成功');
    } catch (error) {
      console.error('❌ ProjectDataService: FmodeParse 初始化失败:', error);
    }
  }
  
  /**
   * 确保Parse已初始化
   */
  private async ensureParse(): Promise<any> {
    if (!this.Parse) {
      await this.initParse();
    }
    return this.Parse;
  }
  
  /**
   * 获取所有项目列表
   * @param filters 筛选条件
   * @returns 项目列表
   */
  async getProjects(filters?: {
    status?: string;
    assignee?: string;
    currentStage?: string;
    searchTerm?: string;
  }): Promise<any[]> {
    const Parse = await this.ensureParse();
    if (!Parse) return [];
    
    try {
      const query = new Parse.Query('Project');
      query.equalTo('company', this.cid);
      query.notEqualTo('isDeleted', true);
      
      // 应用筛选条件
      if (filters?.status && filters.status !== 'all') {
        query.equalTo('status', filters.status);
      }
      
      if (filters?.assignee && filters.assignee !== 'all') {
        query.equalTo('assignee', filters.assignee);
      }
      
      if (filters?.currentStage && filters.currentStage !== 'all') {
        query.equalTo('currentStage', filters.currentStage);
      }
      
      // 关键词搜索
      if (filters?.searchTerm && filters.searchTerm.length >= 2) {
        const searchQuery = new Parse.Query('Project');
        searchQuery.contains('title', filters.searchTerm);
        
        const customerQuery = new Parse.Query('ContactInfo');
        customerQuery.contains('name', filters.searchTerm);
        const customerProjects = new Parse.Query('Project');
        customerProjects.matchesQuery('customer', customerQuery);
        
        const orQuery = Parse.Query.or(searchQuery, customerProjects);
        query._addCondition('$and', [orQuery]);
      }
      
      // 关联查询
      query.include('customer', 'assignee', 'company');
      query.descending('updatedAt');
      query.limit(1000);
      
      const projects = await query.find();
      
      console.log(`✅ 成功获取 ${projects.length} 个项目`);
      
      return projects.map((p: any) => this.transformProject(p));
    } catch (error) {
      console.error('❌ 获取项目列表失败:', error);
      return [];
    }
  }
  
  /**
   * 根据ID获取单个项目
   * @param projectId 项目ID
   * @returns 项目详情
   */
  async getProjectById(projectId: string): Promise<any> {
    const Parse = await this.ensureParse();
    if (!Parse) return null;
    
    try {
      const query = new Parse.Query('Project');
      query.include('customer', 'assignee', 'company');
      const project = await query.get(projectId);
      
      return this.transformProject(project);
    } catch (error) {
      console.error('❌ 获取项目详情失败:', error);
      return null;
    }
  }
  
  /**
   * 创建新项目
   * @param projectData 项目数据
   * @returns 创建的项目
   */
  async createProject(projectData: {
    title: string;
    customer: string;
    assignee?: string;
    status?: string;
    currentStage?: string;
    deadline?: Date;
    data?: any;
  }): Promise<any> {
    const Parse = await this.ensureParse();
    if (!Parse) return null;
    
    try {
      const Project = Parse.Object.extend('Project');
      const project = new Project();
      
      project.set('title', projectData.title);
      project.set('company', this.cid);
      
      // 设置客户（Pointer）
      const ContactInfo = Parse.Object.extend('ContactInfo');
      const customer = new ContactInfo();
      customer.id = projectData.customer;
      project.set('customer', customer);
      
      // 设置负责人（如果有）
      if (projectData.assignee) {
        const Profile = Parse.Object.extend('Profile');
        const assignee = new Profile();
        assignee.id = projectData.assignee;
        project.set('assignee', assignee);
      }
      
      project.set('status', projectData.status || '待分配');
      project.set('currentStage', projectData.currentStage || '订单分配');
      
      if (projectData.deadline) {
        project.set('deadline', projectData.deadline);
      }
      
      if (projectData.data) {
        project.set('data', projectData.data);
      }
      
      const saved = await project.save();
      console.log('✅ 项目创建成功:', saved.id);
      
      return this.transformProject(saved);
    } catch (error) {
      console.error('❌ 创建项目失败:', error);
      throw error;
    }
  }
  
  /**
   * 更新项目
   * @param projectId 项目ID
   * @param updates 更新数据
   * @returns 更新后的项目
   */
  async updateProject(projectId: string, updates: {
    title?: string;
    assignee?: string;
    status?: string;
    currentStage?: string;
    deadline?: Date;
    data?: any;
  }): Promise<any> {
    const Parse = await this.ensureParse();
    if (!Parse) return null;
    
    try {
      const query = new Parse.Query('Project');
      const project = await query.get(projectId);
      
      if (updates.title !== undefined) {
        project.set('title', updates.title);
      }
      
      if (updates.assignee !== undefined) {
        if (updates.assignee) {
          const Profile = Parse.Object.extend('Profile');
          const assignee = new Profile();
          assignee.id = updates.assignee;
          project.set('assignee', assignee);
        } else {
          project.unset('assignee');
        }
      }
      
      if (updates.status !== undefined) {
        project.set('status', updates.status);
      }
      
      if (updates.currentStage !== undefined) {
        project.set('currentStage', updates.currentStage);
      }
      
      if (updates.deadline !== undefined) {
        project.set('deadline', updates.deadline);
      }
      
      if (updates.data !== undefined) {
        const currentData = project.get('data') || {};
        project.set('data', { ...currentData, ...updates.data });
      }
      
      const saved = await project.save();
      console.log('✅ 项目更新成功:', saved.id);
      
      return this.transformProject(saved);
    } catch (error) {
      console.error('❌ 更新项目失败:', error);
      throw error;
    }
  }
  
  /**
   * 分配项目给设计师
   * @param projectId 项目ID
   * @param designerId 设计师ID
   * @returns 更新后的项目
   */
  async assignProject(projectId: string, designerId: string): Promise<any> {
    return this.updateProject(projectId, {
      assignee: designerId,
      status: '进行中',
      currentStage: '方案深化'
    });
  }
  
  /**
   * 删除项目（软删除）
   * @param projectId 项目ID
   * @returns 是否成功
   */
  async deleteProject(projectId: string): Promise<boolean> {
    const Parse = await this.ensureParse();
    if (!Parse) return false;
    
    try {
      const query = new Parse.Query('Project');
      const project = await query.get(projectId);
      
      project.set('isDeleted', true);
      await project.save();
      
      console.log('✅ 项目删除成功:', projectId);
      return true;
    } catch (error) {
      console.error('❌ 删除项目失败:', error);
      return false;
    }
  }
  
  /**
   * 获取项目的空间产品列表
   * @param projectId 项目ID
   * @returns 空间产品列表
   */
  async getProjectProducts(projectId: string): Promise<any[]> {
    const Parse = await this.ensureParse();
    if (!Parse) return [];
    
    try {
      const query = new Parse.Query('Product');
      query.equalTo('project', projectId);
      query.notEqualTo('isDeleted', true);
      query.include('profile');
      query.ascending('order');
      
      const products = await query.find();
      
      return products.map((p: any) => ({
        id: p.id,
        productName: p.get('productName'),
        productType: p.get('productType'),
        stage: p.get('stage'),
        status: p.get('status'),
        reviewStatus: p.get('reviewStatus'),
        profile: p.get('profile') ? {
          id: p.get('profile').id,
          name: p.get('profile').get('name')
        } : null,
        space: p.get('space') || {},
        quotation: p.get('quotation') || {},
        requirements: p.get('requirements') || {},
        estimatedBudget: p.get('estimatedBudget'),
        estimatedDuration: p.get('estimatedDuration'),
        order: p.get('order'),
        createdAt: p.get('createdAt'),
        updatedAt: p.get('updatedAt')
      }));
    } catch (error) {
      console.error('❌ 获取项目空间产品失败:', error);
      return [];
    }
  }
  
  /**
   * 获取项目的文件列表
   * @param projectId 项目ID
   * @param category 文件分类
   * @returns 文件列表
   */
  async getProjectFiles(projectId: string, category?: string): Promise<any[]> {
    const Parse = await this.ensureParse();
    if (!Parse) return [];
    
    try {
      const query = new Parse.Query('ProjectFile');
      query.equalTo('project', projectId);
      query.notEqualTo('isDeleted', true);
      
      if (category) {
        query.equalTo('category', category);
      }
      
      query.include('attach', 'uploadedBy', 'product');
      query.descending('createdAt');
      
      const files = await query.find();
      
      return files.map((f: any) => ({
        id: f.id,
        attach: f.get('attach') ? {
          id: f.get('attach').id,
          name: f.get('attach').get('name'),
          url: f.get('attach').get('url'),
          size: f.get('attach').get('size'),
          mime: f.get('attach').get('mime')
        } : null,
        uploadedBy: f.get('uploadedBy') ? {
          id: f.get('uploadedBy').id,
          name: f.get('uploadedBy').get('name')
        } : null,
        product: f.get('product') ? {
          id: f.get('product').id,
          productName: f.get('product').get('productName')
        } : null,
        stage: f.get('stage'),
        category: f.get('category'),
        data: f.get('data') || {},
        analysis: f.get('analysis') || {},
        createdAt: f.get('createdAt')
      }));
    } catch (error) {
      console.error('❌ 获取项目文件失败:', error);
      return [];
    }
  }
  
  /**
   * 转换Parse项目对象为前端格式
   */
  private transformProject(project: any): any {
    const deadline = project.get('deadline');
    const createdAt = project.get('createdAt');
    const updatedAt = project.get('updatedAt');
    
    // 计算紧急度
    let urgency: 'high' | 'medium' | 'low' = 'low';
    let isOverdue = false;
    let overdueDays = 0;
    let dueSoon = false;
    
    if (deadline) {
      const now = new Date();
      const deadlineTime = deadline instanceof Date ? deadline.getTime() : new Date(deadline).getTime();
      const diffDays = Math.ceil((deadlineTime - now.getTime()) / (1000 * 60 * 60 * 24));
      
      if (diffDays < 0) {
        isOverdue = true;
        overdueDays = Math.abs(diffDays);
        urgency = 'high';
      } else if (diffDays <= 3) {
        urgency = 'high';
        dueSoon = true;
      } else if (diffDays <= 7) {
        urgency = 'medium';
        dueSoon = true;
      }
    }
    
    // 获取客户信息
    const customer = project.get('customer');
    const customerData = customer ? customer.get('data') || {} : {};
    
    // 获取设计师信息
    const assignee = project.get('assignee');
    const assigneeData = assignee ? assignee.get('data') || {} : {};
    
    // 获取项目数据
    const projectData = project.get('data') || {};
    
    return {
      id: project.id,
      name: project.get('title'),
      title: project.get('title'),
      type: projectData.type || 'soft',
      memberType: customerData.memberType || 'normal',
      designerName: assignee ? assignee.get('name') : '',
      designerId: assignee ? assignee.id : null,
      customerName: customer ? customer.get('name') : '',
      customerId: customer ? customer.id : null,
      status: project.get('status'),
      currentStage: project.get('currentStage'),
      deadline: deadline ? (deadline instanceof Date ? deadline : new Date(deadline)) : null,
      expectedEndDate: deadline ? (deadline instanceof Date ? deadline : new Date(deadline)) : null,
      createdAt: createdAt ? (createdAt instanceof Date ? createdAt : new Date(createdAt)) : null,
      updatedAt: updatedAt ? (updatedAt instanceof Date ? updatedAt : new Date(updatedAt)) : null,
      isOverdue,
      overdueDays,
      dueSoon,
      urgency,
      data: projectData,
      // 兼容前端字段
      phases: this.generatePhases(project.get('currentStage')),
      qualityRating: projectData.qualityRating || 'pending',
      lastCustomerFeedback: projectData.lastCustomerFeedback || ''
    };
  }
  
  /**
   * 生成项目阶段进度
   */
  private generatePhases(currentStage: string): any[] {
    const stages = ['订单分配', '方案深化', '交付执行', '售后归档'];
    const currentIndex = stages.indexOf(currentStage);
    
    return stages.map((stage, index) => ({
      name: stage,
      percentage: 25,
      startPercentage: index * 25,
      isCompleted: index < currentIndex,
      isCurrent: index === currentIndex
    }));
  }
}
