import { Component, OnInit, Input, inject, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { FmodeObject, FmodeParse } from 'fmode-ng/parse';
import { ProjectFileService } from '../../../services/project-file.service';
import { ProductSpaceService, Project } from '../../../services/product-space.service';

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

/**
 * 交付执行阶段组件 - Product表统一空间管理
 *
 * 功能：
 * 1. 按产品+工序上传交付物（从order阶段quotation动态加载）
 * 2. 质量自查清单
 * 3. 组长审核与问题反馈
 * 4. 发起交付流程
 */
@Component({
  selector: 'app-stage-delivery',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './stage-delivery.component.html',
  styleUrls: ['./stage-delivery.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class StageDeliveryComponent implements OnInit {
  @Input() project: FmodeObject | null = null;
  @Input() customer: FmodeObject | null = null;
  @Input() currentUser: FmodeObject | null = null;
  @Input() canEdit: boolean = false;

  // 路由参数
  cid: string = '';
  projectId: string = '';

  // Product-based 空间管理
  projectProducts: Project[] = [];
  isMultiProductProject: boolean = false;
  activeProductId: string = '';
  selectedProductIds: string[] = [];

  // 交付视图切换
  deliveryView: string = 'spaces'; // spaces | processes | timeline

  // 用户角色
  role: string = '';
  isDesigner: boolean = false;
  isTeamLeader: boolean = false;

  // 交付物列表（按空间+工序组织）
  deliverables: Array<{
    id: string;
    spaceId: string;
    spaceName: string;
    processType: string; // modeling | softDecor | rendering | postProcess
    processName: string;
    files: Array<{
      id: string;
      url: string;
      name: string;
      type: string; // image | video | document
      uploadTime: Date;
      uploadBy: {
        id: string;
        name: string;
      };
      size?: number;
      metadata?: any;
    }>;
    status: string; // draft | submitted | approved | rejected
    qualityCheck?: {
      checked: boolean;
      items: Array<{
        label: string;
        passed: boolean;
        notes?: string;
      }>;
    };
    review?: {
      reviewedBy: {
        id: string;
        name: string;
      };
      reviewTime: Date;
      result: string; // approved | rejected
      comments: string;
      issues: Array<{
        id: string;
        description: string;
        priority: string; // high | medium | low
        status: string; // open | resolved
        resolvedBy?: string;
        resolvedTime?: Date;
      }>;
    };
    dependencies?: string[]; // 依赖的其他交付物
    timeline?: {
      startDate?: Date;
      dueDate?: Date;
      completedDate?: Date;
      estimatedHours?: number;
      actualHours?: number;
    };
    batchId?: string; // 批次ID，用于批量操作
  }> = [];

  // 当前选中的空间和工序
  selectedSpaceId: string = '';
  selectedProcessType: string = '';

  // 跨空间协调
  crossSpaceDependencies: Array<{
    id: string;
    fromSpaceId: string;
    toSpaceId: string;
    fromProcess: string;
    toProcess: string;
    description: string;
    status: string; // pending | completed | blocked
  }> = [];

  // 批次管理
  deliveryBatches: Array<{
    id: string;
    name: string;
    description: string;
    deliverableIds: string[];
    status: string;
    createdAt: Date;
    dueDate?: Date;
  }> = [];

  // 质量自查清单模板
  qualityCheckTemplates = {
    modeling: [
      { label: '模型尺寸准确', passed: false },
      { label: '材质贴图完整', passed: false },
      { label: '灯光设置合理', passed: false },
      { label: '相机视角正确', passed: false }
    ],
    softDecor: [
      { label: '软装搭配协调', passed: false },
      { label: '色彩方案一致', passed: false },
      { label: '家具摆放合理', passed: false },
      { label: '细节装饰完整', passed: false }
    ],
    rendering: [
      { label: '渲染质量达标', passed: false },
      { label: '光影效果自然', passed: false },
      { label: '材质质感真实', passed: false },
      { label: '画面构图优美', passed: false }
    ],
    postProcess: [
      { label: '后期处理精细', passed: false },
      { label: '色调统一协调', passed: false },
      { label: '瑕疵修复完整', passed: false },
      { label: '输出格式正确', passed: false }
    ]
  };

  // 加载状态
  loading: boolean = true;
  uploading: boolean = false;
  saving: boolean = false;

  constructor(
    private route: ActivatedRoute,
    private projectFileService: ProjectFileService,
    private productSpaceService: ProductSpaceService,
    private cdr: ChangeDetectorRef
  ) {}

  async ngOnInit() {
    // 尝试从父组件获取数据（如果通过@Input传入）
    // 否则从路由参数加载
    if (!this.project || !this.customer || !this.currentUser) {
      this.cid = this.route.parent?.snapshot.paramMap.get('cid') || '';
      this.projectId = this.route.parent?.snapshot.paramMap.get('projectId') || '';
    }

    await this.loadData();
  }

  /**
   * 加载数据
   */
  async loadData() {
    try {
      this.loading = true;

      // 如果没有传入project，从路由参数加载
      if (!this.project && this.projectId) {
        const query = new Parse.Query('Project');
        query.include('customer', 'assignee');
        this.project = await query.get(this.projectId);
        this.customer = this.project.get('customer');
      }

      // 如果没有传入currentUser，加载当前用户
      if (!this.currentUser && this.cid) {
        const { WxworkSDK } = await import('fmode-ng/core');
        const wxwork = new WxworkSDK({ cid: this.cid, appId: 'crm' });
        this.currentUser = await wxwork.getCurrentUser();
      }

      // 设置用户角色和权限
      this.role = this.currentUser?.get('roleName') || '';
      this.isDesigner = this.role === '组员';
      this.isTeamLeader = this.role === '组长';
      this.canEdit = ['组员', '组长', '管理员'].includes(this.role);

      // 加载项目空间数据
      if (this.project) {
        await this.loadProjectSpaces();
        await this.loadDeliverablesData();
        await this.loadCrossSpaceDependencies();
        await this.loadDeliveryBatches();
      }

      this.cdr.markForCheck();

    } catch (err) {
      console.error('加载失败:', err);
    } finally {
      this.loading = false;
    }
  }

  /**
   * 加载项目空间数据
   */
  async loadProjectSpaces(): Promise<void> {
    if (!this.project) return;

    try {
      if(this.project?.id){  
        this.projectProducts = await this.productSpaceService.getProjectProductSpaces(this.project.id);
      }
      this.isMultiProductProject = this.projectProducts.length > 1;

      // 如果有产品，默认选中第一个
      if (this.projectProducts.length > 0 && !this.activeProductId) {
        this.activeProductId = this.projectProducts[0].id;
      }

    } catch (error) {
      console.error('加载项目空间失败:', error);
    }
  }

  /**
   * 加载交付物数据
   */
  async loadDeliverablesData(): Promise<void> {
    if (!this.project) return;

    try {
      // 加载项目文件（交付物）
      const projectFiles = await this.projectFileService.getProjectFiles(this.projectId, {
        fileType: 'deliverable'
      });

      // 从项目数据加载交付物结构
      const data = this.project.get('data') || {};
      let savedDeliverables = data.deliverables || [];

      // 如果没有保存的交付物，初始化结构
      if (savedDeliverables.length === 0) {
        savedDeliverables = this.initializeDeliverables();
      }

      // 合并文件数据
      for (const deliverable of savedDeliverables) {
        const deliverableFiles = projectFiles.filter((file: FmodeObject) =>
          file.get('data')?.deliverableId === deliverable.id
        );

        deliverable.files = deliverableFiles.map((file: FmodeObject) => ({
          id: file.id,
          url: file.get('fileUrl'),
          name: file.get('fileName'),
          type: this.getFileType(file.get('fileName')),
          uploadTime: file.get('uploadedAt') || file.get('data')?.uploadedAt || file.createdAt,
          uploadBy: {
            id: file.get('uploadedBy')?.id,
            name: file.get('uploadedBy')?.get('name')
          },
          size: file.get('fileSize'),
          metadata: file.get('data')?.metadata
        }));
      }

      this.deliverables = savedDeliverables;

    } catch (error) {
      console.error('加载交付物数据失败:', error);
    }
  }

  /**
   * 加载跨空间依赖
   */
  async loadCrossSpaceDependencies(): Promise<void> {
    if (!this.project) return;

    try {
      if(this.project?.id){
        let dependencies
        dependencies = await this.productSpaceService.getProductDependencies(this.project.id);
        
        this.crossSpaceDependencies = dependencies.map((dep: any) => ({
          id: dep.id,
          fromSpaceId: dep.fromSpace?.objectId,
          toSpaceId: dep.toSpace?.objectId,
          fromProcess: dep.fromProcess || '',
          toProcess: dep.toProcess || '',
          description: dep.description,
          status: dep.status
        }));
      }

    } catch (error) {
      console.error('加载跨空间依赖失败:', error);
    }
  }

  /**
   * 加载交付批次
   */
  async loadDeliveryBatches(): Promise<void> {
    if (!this.project) return;

    try {
      const data = this.project.get('data') || {};
      this.deliveryBatches = data.deliveryBatches || [];

    } catch (error) {
      console.error('加载交付批次失败:', error);
    }
  }

  /**
   * 初始化交付物结构
   */
  initializeDeliverables() {
    const data = this.project?.get('data') || {};
    const quotation = data.quotation;
    const deliverables: any[] = [];

    const processTypeMap: any = {
      'modeling': '建模',
      'softDecor': '软装',
      'rendering': '渲染',
      'postProcess': '后期'
    };

    if (quotation && quotation.spaces) {
      // 从报价单初始化
      for (const space of quotation.spaces) {
        for (const [processKey, processData] of Object.entries(space.processes || {})) {
          if ((processData as any).enabled) {
            deliverables.push(this.createDeliverable(
              space.id || space.name,
              space.name,
              processKey,
              processTypeMap[processKey]
            ));
          }
        }
      }
    } else {
      // 从项目空间初始化
      for (const space of this.projectProducts) {
        // 为每个空间创建基础工序交付物
        const defaultProcesses = ['modeling', 'softDecor', 'rendering', 'postProcess'];
        for (const processType of defaultProcesses) {
          deliverables.push(this.createDeliverable(
            space.id,
            space.name || this.productSpaceService.getProductTypeName(space.type),
            processType,
            processTypeMap[processType]
          ));
        }
      }
    }

    return deliverables;
  }

  /**
   * 创建交付物对象
   */
  private createDeliverable(spaceId: string, spaceName: string, processType: string, processName: string): any {
    return {
      id: `${spaceId}_${processType}_${Date.now()}`,
      spaceId,
      spaceName,
      processType,
      processName,
      files: [],
      status: 'draft',
      qualityCheck: {
        checked: false,
        items: this.qualityCheckTemplates[processType as keyof typeof this.qualityCheckTemplates]?.map(item => ({ ...item })) || []
      },
      timeline: {
        estimatedHours: this.getEstimatedHours(processType)
      }
    };
  }

  /**
   * 获取预估工时
   */
  private getEstimatedHours(processType: string): number {
    const hoursMap: Record<string, number> = {
      'modeling': 8,
      'softDecor': 6,
      'rendering': 4,
      'postProcess': 2
    };
    return hoursMap[processType] || 4;
  }

  /**
   * 获取文件类型
   */
  private getFileType(fileName: string): string {
    const extension = fileName.split('.').pop()?.toLowerCase();
    if (['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(extension || '')) {
      return 'image';
    } else if (['mp4', 'mov', 'avi', 'mkv'].includes(extension || '')) {
      return 'video';
    } else {
      return 'document';
    }
  }

  // ===== 多空间交付管理方法 =====

  /**
   * 切换交付视图
   */
  onDeliveryViewChange(event: any): void {
    this.deliveryView = event.detail.value;
    this.cdr.markForCheck();
  }

  /**
   * 选择空间
   */
  selectSpace(spaceId: string): void {
    this.activeProductId = spaceId;
    this.cdr.markForCheck();
  }

  /**
   * 切换空间选择状态
   */
  toggleSpaceSelection(spaceId: string): void {
    const index = this.selectedProductIds.indexOf(spaceId);
    if (index > -1) {
      this.selectedProductIds.splice(index, 1);
    } else {
      this.selectedProductIds.push(spaceId);
    }
    this.cdr.markForCheck();
  }

  /**
   * 获取指定空间和工序的交付物
   */
  getDeliverable(spaceId: string, processType: string): any {
    return this.deliverables.find(
      d => d.spaceId === spaceId && d.processType === processType
    );
  }

  /**
   * 获取空间的交付物
   */
  getSpaceDeliverables(spaceId?: string): any[] {
    if (!spaceId) return this.deliverables;
    return this.deliverables.filter(d => d.spaceId === spaceId);
  }

  /**
   * 获取工序的交付物
   */
  getProcessDeliverables(processType: string): any[] {
    return this.deliverables.filter(d => d.processType === processType);
  }

  /**
   * 上传交付物文件
   */
  async uploadFile(event: any, spaceId: string, processType: string) {
    const files = event.target.files;
    if (!files || files.length === 0) return;

    const deliverable = this.getDeliverable(spaceId, processType);
    if (!deliverable || !this.project || !this.currentUser) return;

    try {
      this.uploading = true;

      for (let i = 0; i < files.length; i++) {
        const file = files[i];

        // 验证文件大小 (50MB)
        if (file.size > 50 * 1024 * 1024) {
          console.warn(`文件 ${file.name} 超过50MB限制，跳过`);
          continue;
        }

        // 统一使用服务方法：上传并创建记录，返回 ProjectFile
        const savedProjectFile = await this.projectFileService.uploadProjectFileWithRecord(
          file,
          this.projectId,
          'deliverable',
          spaceId,
          processType,
          {
            deliverableId: deliverable.id,
            processType,
            uploadSource: 'delivery'
          }
        );

        // 添加到交付物文件列表，使用 ProjectFile 的真实ID以支持删除
        deliverable.files.push({
          id: savedProjectFile.id,
          url: savedProjectFile.get('fileUrl'),
          name: savedProjectFile.get('fileName'),
          type: this.getFileType(savedProjectFile.get('fileName') || ''),
          uploadTime: savedProjectFile.get('uploadedAt') || new Date(),
          uploadBy: {
            id: savedProjectFile.get('uploadedBy')?.id,
            name: savedProjectFile.get('uploadedBy')?.get('name')
          },
          size: savedProjectFile.get('fileSize'),
          metadata: savedProjectFile.get('data')?.metadata
        });
      }

      this.cdr.markForCheck();

    } catch (err) {
      console.error('上传失败:', err);
    } finally {
      this.uploading = false;
    }
  }

  /**
   * 删除文件
   */
  async deleteFile(spaceId: string, processType: string, fileId: string) {
    try {
      // 从数据库删除（参数为 ProjectFile 记录ID）
      await this.projectFileService.deleteProjectFile(fileId);

      const deliverable = this.getDeliverable(spaceId, processType);
      if (deliverable) {
        deliverable.files = deliverable.files.filter((file: any) => file.id !== fileId);
        this.cdr.markForCheck();
      }
    } catch (error) {
      console.error('删除文件失败:', error);
    }
  }

  /**
   * 进行质量自查
   */
  performQualityCheck(spaceId: string, processType: string) {
    const deliverable = this.getDeliverable(spaceId, processType);
    if (!deliverable) return;

    const template = this.qualityCheckTemplates[processType as keyof typeof this.qualityCheckTemplates];
    if (!deliverable.qualityCheck) {
      deliverable.qualityCheck = {
        checked: false,
        items: template.map(item => ({ ...item }))
      };
    }
  }

  /**
   * 提交交付物给组长审核
   */
  async submitForReview(spaceId: string, processType: string) {
    const deliverable = this.getDeliverable(spaceId, processType);
    if (!deliverable) return;

    if (deliverable.files.length === 0) {
      alert('请先上传交付物文件');
      return;
    }

    if (!deliverable.qualityCheck?.checked) {
      alert('请先完成质量自查');
      return;
    }

    try {
      this.saving = true;

      deliverable.status = 'submitted';
      await this.saveDraft();

      alert('已提交审核');

    } catch (err) {
      console.error('提交失败:', err);
      alert('提交失败');
    } finally {
      this.saving = false;
    }
  }

  /**
   * 组长审核（通过/驳回）
   */
  async reviewDeliverable(spaceId: string, processType: string, result: 'approved' | 'rejected', comments: string) {
    if (!this.isTeamLeader && !this.canEdit) {
      alert('您没有审核权限');
      return;
    }

    const deliverable = this.getDeliverable(spaceId, processType);
    if (!deliverable) return;

    try {
      this.saving = true;

      deliverable.status = result;
      deliverable.review = {
        reviewedBy: {
          id: this.currentUser!.id,
          name: this.currentUser!.get('name')
        },
        reviewTime: new Date(),
        result,
        comments,
        issues: []
      };

      await this.saveDraft();

      alert(result === 'approved' ? '审核通过' : '已驳回，请修改后重新提交');

    } catch (err) {
      console.error('审核失败:', err);
      alert('审核失败');
    } finally {
      this.saving = false;
    }
  }

  /**
   * 创建问题反馈
   */
  async createIssue(spaceId: string, processType: string, issue: any) {
    const deliverable = this.getDeliverable(spaceId, processType);
    if (!deliverable || !deliverable.review) return;

    deliverable.review.issues.push(issue);
    await this.saveDraft();
  }

  /**
   * 发起交付流程
   */
  async initiateDelivery() {
    if (!this.project || !this.canEdit) return;

    // 验证所有交付物都已通过审核
    const allApproved = this.deliverables.every(d => d.status === 'approved');
    if (!allApproved) {
      alert('请确保所有交付物都已通过审核');
      return;
    }

    try {
      this.saving = true;

      // 更新项目状态
      this.project.set('currentStage', '尾款结算');
      this.project.set('status', '待结算');

      await this.project.save();

      alert('交付完成，进入售后归档阶段');

    } catch (err) {
      console.error('操作失败:', err);
      alert('操作失败');
    } finally {
      this.saving = false;
    }
  }

  /**
   * 保存草稿
   */
  async saveDraft() {
    if (!this.project || !this.canEdit) return;

    try {
      this.saving = true;

      const data = this.project.get('data') || {};
      data.deliverables = this.deliverables;
      data.deliveryBatches = this.deliveryBatches;

      this.project.set('data', data);
      await this.project.save();

    } catch (err) {
      console.error('保存失败:', err);
    } finally {
      this.saving = false;
      this.cdr.markForCheck();
    }
  }

  // ===== 批次管理方法 =====

  /**
   * 创建交付批次
   */
  async createDeliveryBatch(name: string, description: string): Promise<void> {
    const batch = {
      id: `batch_${Date.now()}`,
      name,
      description,
      deliverableIds: [...this.selectedProductIds],
      status: 'draft',
      createdAt: new Date()
    };

    this.deliveryBatches.push(batch);
    this.selectedProductIds = [];
    this.cdr.markForCheck();
  }

  /**
   * 批量提交交付物
   */
  async batchSubmitDeliverables(batchId: string): Promise<void> {
    const batch = this.deliveryBatches.find(b => b.id === batchId);
    if (!batch) return;

    try {
      for (const deliverableId of batch.deliverableIds) {
        const deliverable = this.deliverables.find(d => d.id === deliverableId);
        if (deliverable && deliverable.status === 'draft') {
          await this.submitForReview(deliverable.spaceId, deliverable.processType);
        }
      }

      batch.status = 'submitted';
      this.cdr.markForCheck();

    } catch (error) {
      console.error('批量提交失败:', error);
    }
  }

  /**
   * 获取已批准的交付物数量
   */
  getApprovedCount(): number {
    return this.deliverables.filter(d => d.status === 'approved').length;
  }

  /**
   * 检查质检是否全部通过
   */
  isQualityCheckAllPassed(deliverable: any): boolean {
    return deliverable.qualityCheck?.items?.every((i: any) => i.passed) || false;
  }

  /**
   * 获取工序颜色
   */
  getProcessColor(processType: string): string {
    const colorMap: any = {
      'modeling': 'primary',
      'softDecor': 'secondary',
      'rendering': 'tertiary',
      'postProcess': 'success'
    };
    return colorMap[processType] || 'medium';
  }

  /**
   * 获取状态颜色
   */
  getStatusColor(status: string): string {
    const colorMap: any = {
      'draft': 'medium',
      'submitted': 'warning',
      'approved': 'success',
      'rejected': 'danger'
    };
    return colorMap[status] || 'medium';
  }

  /**
   * 获取状态文本
   */
  getStatusText(status: string): string {
    const textMap: any = {
      'draft': '草稿',
      'submitted': '待审核',
      'approved': '已通过',
      'rejected': '已驳回'
    };
    return textMap[status] || status;
  }

  /**
   * 按空间分组交付物
   */
  get deliverablesBySpace(): Array<{ spaceName: string; items: any[] }> {
    const grouped = new Map<string, any[]>();

    for (const deliverable of this.deliverables) {
      if (!grouped.has(deliverable.spaceName)) {
        grouped.set(deliverable.spaceName, []);
      }
      grouped.get(deliverable.spaceName)!.push(deliverable);
    }

    return Array.from(grouped.entries()).map(([spaceName, items]) => ({
      spaceName,
      items
    }));
  }

  /**
   * 计算完成进度
   */
  get completionProgress(): number {
    if (this.deliverables.length === 0) return 0;
    const approvedCount = this.deliverables.filter(d => d.status === 'approved').length;
    return Math.round((approvedCount / this.deliverables.length) * 100);
  }

  // ===== 工具方法 =====

  /**
   * 获取空间图标
   */
  getSpaceIcon(spaceType: string): string {
    return this.productSpaceService.getProductIcon(spaceType);
  }

  /**
   * 获取空间类型名称
   */
  getSpaceTypeName(spaceType: string): string {
    return this.productSpaceService.getProductTypeName(spaceType);
  }

  /**
   * 获取空间显示名称
   */
  getSpaceDisplayName(space: Project): string {
    return space.name || this.getSpaceTypeName(space.type);
  }

  /**
   * 获取当前空间的交付物
   */
  getCurrentSpaceDeliverables(): any[] {
    if (!this.activeProductId) return this.deliverables;
    return this.deliverables.filter(d => d.spaceId === this.activeProductId);
  }

  /**
   * 过滤交付物
   */
  getFilteredDeliverables(): any[] {
    let filtered = this.deliverables;

    if (this.deliveryView === 'spaces' && this.activeProductId) {
      filtered = filtered.filter(d => d.spaceId === this.activeProductId);
    }

    if (this.deliveryView === 'processes' && this.selectedProcessType) {
      filtered = filtered.filter(d => d.processType === this.selectedProcessType);
    }

    return filtered;
  }

  /**
   * 格式化文件大小
   */
  formatFileSize(bytes: number): string {
    return this.projectFileService.formatFileSize(bytes);
  }

  /**
   * 计算空间完成进度
   */
  getSpaceProgress(spaceId: string): number {
    const spaceDeliverables = this.getSpaceDeliverables(spaceId);
    if (spaceDeliverables.length === 0) return 0;
    const approvedCount = spaceDeliverables.filter(d => d.status === 'approved').length;
    return Math.round((approvedCount / spaceDeliverables.length) * 100);
  }

  /**
   * 计算工序完成进度
   */
  getProcessProgress(processType: string): number {
    const processDeliverables = this.getProcessDeliverables(processType);
    if (processDeliverables.length === 0) return 0;
    const approvedCount = processDeliverables.filter(d => d.status === 'approved').length;
    return Math.round((approvedCount / processDeliverables.length) * 100);
  }

  /**
   * 获取待处理问题数量
   */
  getOpenIssuesCount(): number {
    return this.deliverables.reduce((total, d) => {
      return total + (d.review?.issues?.filter(issue => issue.status === 'open').length || 0);
    }, 0);
  }

  /**
   * 检查跨空间依赖
   */
  checkCrossSpaceDependencies(deliverableId: string): string[] {
    const dependencies: string[] = [];

    for (const dep of this.crossSpaceDependencies) {
      // 这里可以根据实际业务逻辑检查依赖关系
      if (dep.status === 'pending') {
        dependencies.push(dep.description);
      }
    }

    return dependencies;
  }

  /**
   * 获取交付优先级
   */
  getDeliverablePriority(deliverable: any): 'high' | 'medium' | 'low' {
    // 根据依赖关系和工序重要性计算优先级
    const hasDependencies = this.checkCrossSpaceDependencies(deliverable.id).length > 0;

    if (hasDependencies) return 'high';
    if (deliverable.processType === 'modeling') return 'high';
    if (deliverable.processType === 'softDecor') return 'medium';
    return 'low';
  }

  /**
   * 获取预计完成时间
   */
  getEstimatedCompletionDate(deliverable: any): Date | null {
    if (!deliverable.timeline?.estimatedHours) return null;

    const startDate = deliverable.timeline.startDate || new Date();
    const workingDays = Math.ceil(deliverable.timeline.estimatedHours / 8); // 假设每天8小时
    const completionDate = new Date(startDate);
    completionDate.setDate(completionDate.getDate() + workingDays);

    return completionDate;
  }
}
