import { Injectable } from '@angular/core';
import { FmodeParse } from 'fmode-ng/parse';

const Parse = FmodeParse.with('nova');

export interface Project {
  id: string;
  name: string; // productName
  type: string; // productType
  area?: number; // space.area
  priority: number; // space.priority
  status: string; // Product.status
  complexity: string; // space.complexity
  metadata?: any; // space metadata
  estimatedBudget?: number; // quotation.price
  estimatedDuration?: number; // space metadata
  order: number;
  projectId: string;
  designerId?: string; // profile pointer
  quotation?: any; // Product.quotation
  requirements?: any; // Product.requirements
  reviews?: any; // Product.reviews
}

export interface ProductProgress {
  productId: string;
  stage: string;
  progress: number;
  status: string;
  timeline?: any[];
  blockers?: string[];
  estimatedCompletion?: Date;
  actualCompletion?: Date;
}

export interface ProductRequirement {
  productId: string;
  productName: string;
  productType: string;
  colorRequirement: any;
  spaceStructureRequirement: any;
  materialRequirement: any;
  lightingRequirement: any;
  specificRequirements: any;
  referenceImages?: string[];
  referenceFiles?: any[];
}

@Injectable({
  providedIn: 'root'
})
export class ProductSpaceService {

  constructor() {}

  /**
   * 创建产品空间（即创建Product）
   */
  async createProductSpace(projectId: string, spaceData: Partial<Project>): Promise<Project> {
    try {
      const Product = Parse.Object.extend('Product');
      const product = new Product();

      // 获取项目
      const projectQuery = new Parse.Query('Project');
      const project = await projectQuery.get(projectId);

      // 设置产品字段
      product.set('project', project);
      product.set('productName', spaceData.name || '');
      product.set('productType', spaceData.type || 'other');
      product.set('status', spaceData.status || 'not_started');

      // 设置空间信息
      product.set('space', {
        spaceName: spaceData.name || '',
        area: spaceData.area || 0,
        dimensions: { length: 0, width: 0, height: 0 },
        features: [],
        constraints: [],
        priority: spaceData.priority || 5,
        complexity: spaceData.complexity || 'medium'
      });

      // 设置报价信息
      if (spaceData.estimatedBudget) {
        product.set('quotation', {
          price: spaceData.estimatedBudget,
          currency: 'CNY',
          breakdown: {},
          status: 'draft',
          validUntil: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)
        });
      }

      // 设置需求信息
      product.set('requirements', {
        colorRequirement: spaceData.requirements?.colorRequirement || {},
        spaceStructureRequirement: spaceData.requirements?.spaceStructureRequirement || {},
        materialRequirement: spaceData.requirements?.materialRequirement || {},
        lightingRequirement: spaceData.requirements?.lightingRequirement || {},
        specificRequirements: spaceData.requirements?.specificRequirements || [],
        constraints: {}
      });

      // 设置设计师
      if (spaceData.designerId) {
        const designerQuery = new Parse.Query('Profile');
        const designer = await designerQuery.get(spaceData.designerId);
        product.set('profile', designer);
      }

      const savedProduct = await product.save();
      return this.parseProductData(savedProduct);

    } catch (error) {
      console.error('创建产品空间失败:', error);
      throw error;
    }
  }

  /**
   * 获取项目产品空间列表
   */
  async getProjectProductSpaces(projectId: string): Promise<Project[]> {
    try {
      const query = new Parse.Query('Product');
      query.equalTo('project', {
        __type: 'Pointer',
        className: 'Project',
        objectId: projectId
      });
      query.include('profile');
      query.ascending('createdAt');

      const results = await query.find();
      return results.map(product => this.parseProductData(product));

    } catch (error) {
      console.error('获取项目产品空间失败:', error);
      return [];
    }
  }

  /**
   * 更新产品空间信息
   */
  async updateProductSpace(productId: string, updateData: Partial<Project>): Promise<Project> {
    try {
      const query = new Parse.Query('Product');
      const product = await query.get(productId);

      // 更新产品基本信息
      if (updateData.name !== undefined) product.set('productName', updateData.name);
      if (updateData.type !== undefined) product.set('productType', updateData.type);
      if (updateData.status !== undefined) product.set('status', updateData.status);

      // 更新空间信息
      if (updateData.area !== undefined || updateData.priority !== undefined || updateData.complexity !== undefined) {
        const space = product.get('space') || {};
        if (updateData.area !== undefined) space.area = updateData.area;
        if (updateData.priority !== undefined) space.priority = updateData.priority;
        if (updateData.complexity !== undefined) space.complexity = updateData.complexity;
        product.set('space', space);
      }

      // 更新报价信息
      if (updateData.estimatedBudget !== undefined) {
        const quotation = product.get('quotation') || {};
        quotation.price = updateData.estimatedBudget;
        product.set('quotation', quotation);
      }

      // 更新需求信息
      if (updateData.requirements !== undefined) {
        const requirements = product.get('requirements') || {};
        Object.assign(requirements, updateData.requirements);
        product.set('requirements', requirements);
      }

      // 更新设计师
      if (updateData.designerId !== undefined) {
        if (updateData.designerId) {
          const designerQuery = new Parse.Query('Profile');
          const designer = await designerQuery.get(updateData.designerId);
          product.set('profile', designer);
        } else {
          product.unset('profile');
        }
      }

      const savedProduct = await product.save();
      return this.parseProductData(savedProduct);

    } catch (error) {
      console.error('更新产品空间失败:', error);
      throw error;
    }
  }

  /**
   * 删除产品空间
   */
  async deleteProductSpace(productId: string): Promise<void> {
    try {
      const query = new Parse.Query('Product');
      const product = await query.get(productId);
      await product.destroy();

    } catch (error) {
      console.error('删除产品空间失败:', error);
      throw error;
    }
  }

  /**
   * 更新产品进度
   */
  async updateProductProgress(progressData: ProductProgress): Promise<void> {
    try {
      // 在Product的data字段中存储进度信息
      const query = new Parse.Query('Product');
      const product = await query.get(progressData.productId);

      const data = product.get('data') || {};
      if (!data.progress) data.progress = [];

      // 查找现有进度记录
      let progressRecord = data.progress.find((p: any) => p.stage === progressData.stage);

      if (!progressRecord) {
        // 创建新进度记录
        progressRecord = {
          stage: progressData.stage,
          progress: 0,
          status: 'not_started',
          timeline: [],
          blockers: []
        };
        data.progress.push(progressRecord);
      }

      // 更新进度数据
      progressRecord.progress = progressData.progress;
      progressRecord.status = progressData.status;
      progressRecord.timeline = progressData.timeline || [];
      progressRecord.blockers = progressData.blockers || [];
      progressRecord.estimatedCompletion = progressData.estimatedCompletion;
      progressRecord.actualCompletion = progressData.actualCompletion;

      product.set('data', data);
      await product.save();

    } catch (error) {
      console.error('更新产品进度失败:', error);
      throw error;
    }
  }

  /**
   * 获取产品进度
   */
  async getProductProgress(productId: string, stage?: string): Promise<ProductProgress[]> {
    try {
      const query = new Parse.Query('Product');
      const product = await query.get(productId);

      const data = product.get('data') || {};
      const progressData = data.progress || [];

      let result = progressData;
      if (stage) {
        result = progressData.filter((p: any) => p.stage === stage);
      }

      return result.map((p: any) => ({
        productId: productId,
        stage: p.stage,
        progress: p.progress,
        status: p.status,
        timeline: p.timeline,
        blockers: p.blockers,
        estimatedCompletion: p.estimatedCompletion,
        actualCompletion: p.actualCompletion
      }));

    } catch (error) {
      console.error('获取产品进度失败:', error);
      return [];
    }
  }

  /**
   * 创建产品依赖关系
   */
  async createProductDependency(
    projectId: string,
    fromProductId: string,
    toProductId: string,
    dependencyType: string,
    description: string
  ): Promise<void> {
    try {
      // 在项目的data字段中存储产品依赖关系
      const projectQuery = new Parse.Query('Project');
      const project = await projectQuery.get(projectId);

      const data = project.get('data') || {};
      if (!data.productDependencies) data.productDependencies = [];

      const dependency = {
        id: `dep_${Date.now()}`,
        fromProductId: fromProductId,
        toProductId: toProductId,
        type: dependencyType,
        description: description,
        status: 'pending',
        confidence: 0.8,
        createdAt: new Date()
      };

      data.productDependencies.push(dependency);
      project.set('data', data);
      await project.save();

    } catch (error) {
      console.error('创建产品依赖失败:', error);
      throw error;
    }
  }

  /**
   * 获取产品依赖关系
   */
  async getProductDependencies(projectId: string): Promise<any[]> {
    try {
      const projectQuery = new Parse.Query('Project');
      const project = await projectQuery.get(projectId);

      const data = project.get('data') || {};
      return data.productDependencies || [];

    } catch (error) {
      console.error('获取产品依赖失败:', error);
      return [];
    }
  }

  /**
   * 保存产品需求
   */
  async saveProductRequirements(
    _projectId: string,
    productId: string,
    requirements: ProductRequirement
  ): Promise<void> {
    try {
      const query = new Parse.Query('Product');
      const product = await query.get(productId);

      // 更新产品的需求信息
      product.set('requirements', {
        colorRequirement: requirements.colorRequirement,
        spaceStructureRequirement: requirements.spaceStructureRequirement,
        materialRequirement: requirements.materialRequirement,
        lightingRequirement: requirements.lightingRequirement,
        specificRequirements: requirements.specificRequirements,
        constraints: {}
      });

      await product.save();

    } catch (error) {
      console.error('保存产品需求失败:', error);
      throw error;
    }
  }

  /**
   * 获取产品需求
   */
  async getProductRequirements(projectId: string, productId?: string): Promise<ProductRequirement[]> {
    try {
      let query = new Parse.Query('Product');
      query.equalTo('project', {
        __type: 'Pointer',
        className: 'Project',
        objectId: projectId
      });

      if (productId) {
        query.equalTo('objectId', productId);
      }

      const results = await query.find();
      return results.map(product => ({
        productId: product.id || '',
        productName: product.get('productName'),
        productType: product.get('productType'),
        colorRequirement: product.get('requirements')?.colorRequirement || {},
        spaceStructureRequirement: product.get('requirements')?.spaceStructureRequirement || {},
        materialRequirement: product.get('requirements')?.materialRequirement || {},
        lightingRequirement: product.get('requirements')?.lightingRequirement || {},
        specificRequirements: product.get('requirements')?.specificRequirements || [],
        referenceImages: product.get('requirements')?.referenceImages || [],
        referenceFiles: product.get('requirements')?.referenceFiles || []
      }));

    } catch (error) {
      console.error('获取产品需求失败:', error);
      return [];
    }
  }

  /**
   * 计算产品完成进度
   */
  calculateProductProgress(_productId: string, _allStages: string[]): number {
    // 这里需要从缓存或数据库中获取各阶段进度
    // 暂时返回模拟数据
    return Math.floor(Math.random() * 100);
  }

  /**
   * 获取产品类型图标
   */
  getProductIcon(productType: string): string {
    const iconMap: Record<string, string> = {
      'living_room': 'living-room',
      'bedroom': 'bedroom',
      'kitchen': 'kitchen',
      'bathroom': 'bathroom',
      'dining_room': 'dining-room',
      'study': 'study',
      'balcony': 'balcony',
      'corridor': 'corridor',
      'storage': 'storage',
      'entrance': 'entrance',
      'other': 'room'
    };

    return iconMap[productType] || 'room';
  }

  /**
   * 获取产品类型名称
   */
  getProductTypeName(productType: string): string {
    const nameMap: Record<string, string> = {
      'living_room': '客厅',
      'bedroom': '卧室',
      'kitchen': '厨房',
      'bathroom': '卫生间',
      'dining_room': '餐厅',
      'study': '书房',
      'balcony': '阳台',
      'corridor': '走廊',
      'storage': '储物间',
      'entrance': '玄关',
      'other': '其他'
    };

    return nameMap[productType] || '其他';
  }

  /**
   * 解析产品数据
   */
  private parseProductData(product: any): Project {
    const space = product.get('space') || {};
    const quotation = product.get('quotation') || {};
    const profile = product.get('profile');

    return {
      id: product.id,
      name: product.get('productName'),
      type: product.get('productType'),
      area: space.area,
      priority: space.priority || 5,
      status: product.get('status'),
      complexity: space.complexity || 'medium',
      metadata: space.metadata || {},
      estimatedBudget: quotation.price,
      estimatedDuration: space.estimatedDuration,
      order: 0, // 使用创建时间排序
      projectId: product.get('project')?.objectId,
      designerId: profile?.id,
      quotation: quotation,
      requirements: product.get('requirements'),
      reviews: product.get('reviews')
    };
  }
}