import { Component, OnInit, Input, ViewChild, ElementRef, 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';
import {
  QUOTATION_PRICE_TABLE,
  STYLE_LEVELS,
  SPACE_TYPES,
  BUSINESS_TYPES,
  HOME_DEFAULT_ROOMS,
  ADJUSTMENT_RULES,
  getBasePrice,
  calculateFinalPrice,
  getDefaultProcesses
} from '../../../config/quotation-rules';
import { QuotationEditorComponent } from '../../../components/quotation-editor.component';
import { TeamAssignComponent } from '../../../components/team-assign/team-assign.component';

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

/**
 * 订单分配阶段组件 - 支持多空间项目管理
 *
 * 功能：
 * 1. 智能识别多空间项目类型
 * 2. 按空间维度组织报价和管理
 * 3. 家装/工装项目类型选择
 * 4. 快速场景选择，自动生成多空间报价表
 * 5. 项目组（Department）→ 组员（Profile）两级设计师分配
 * 6. 提交审批
 */
@Component({
  selector: 'app-stage-order',
  standalone: true,
  imports: [CommonModule, FormsModule, QuotationEditorComponent, TeamAssignComponent],
  templateUrl: './stage-order.component.html',
  styleUrls: ['./stage-order.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class StageOrderComponent implements OnInit {
  @Input() project: FmodeObject | null = null;
  @Input() customer: FmodeObject | null = null;
  @Input() currentUser: FmodeObject | null = null;
  @Input() canEdit: boolean = false;

  onProjectTypeChange(){

  }
  // 项目基本信息
  projectInfo = {
    title: '',
    projectType: '', // 家装 | 工装
    renderType: '', // 静态单张 | 360全景
    deadline: '',
    description: '',
    priceLevel: '一级', // 一级(老客户) | 二级(中端组) | 三级(高端组)
    spaceType: 'single' // single | multi
  };

  // 空间管理
  projectSpaces: Project[] = [];
  isMultiSpaceProject: boolean = false;
  activeSpaceId: string = '';

  // 空间类型映射
  spaceTypeMap:any = {
    'living_room': '客厅',
    'bedroom': '卧室',
    'kitchen': '厨房',
    'bathroom': '卫生间',
    'dining_room': '餐厅',
    'study': '书房',
    'balcony': '阳台',
    'corridor': '走廊',
    'storage': '储物间',
    'entrance': '玄关',
    'other': '其他'
  };

  // 场景选择（家装）
  homeScenes = {
    spaceType: '', // 平层 | 跃层 | 挑空
    styleLevel: '', // 基础风格组 | 中级风格组 | 高级风格组 | 顶级风格组
    rooms: [] as Array<{
      name: string;
      spaceType: string;
      selected: boolean;
      basePrice: number;
      adjustments: {
        extraFunction: number; // 功能区加价
        complexity: number; // 造型复杂度加价
        design: boolean; // 是否需要设计服务（×2）
      };
    }>
  };

  // 场景选择（工装）
  commercialScenes = {
    businessType: '', // 办公空间 | 商业空间 | 娱乐空间 | 酒店餐厅 | 公共空间
    spaces: [] as Array<{
      name: string;
      type: string; // 门厅空间 | 封闭空间
      selected: boolean;
      basePrice: number;
      adjustments: {
        extraFunction: number;
        complexity: number;
        design: boolean;
        panoramic: boolean; // 是否全景渲染（×2）
      };
    }>
  };

  // 报价明细（最终生成）- 支持多空间
  quotation = {
    spaces: [] as Array<{
      name: string;
      spaceId?: string;
      processes: {
        modeling: { enabled: boolean; price: number; unit: string; quantity: number };
        softDecor: { enabled: boolean; price: number; unit: string; quantity: number };
        rendering: { enabled: boolean; price: number; unit: string; quantity: number };
        postProcess: { enabled: boolean; price: number; unit: string; quantity: number };
      };
      subtotal: number;
    }>,
    total: 0,
    spaceBreakdown: [] as Array<{
      spaceName: string;
      spaceId: string;
      amount: number;
      percentage: number;
    }>
  };

  // 工序类型定义
  processTypes = [
    { key: 'modeling', name: '建模', color: 'primary' },
    { key: 'softDecor', name: '软装', color: 'secondary' },
    { key: 'rendering', name: '渲染', color: 'tertiary' },
    { key: 'postProcess', name: '后期', color: 'success' }
  ];

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

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

  // 从配置导入报价表和规则
  priceTable = QUOTATION_PRICE_TABLE;
  styleLevels = STYLE_LEVELS;
  spaceTypes = SPACE_TYPES;
  businessTypes = BUSINESS_TYPES;
  homeDefaultRooms = HOME_DEFAULT_ROOMS;
  adjustmentRules = ADJUSTMENT_RULES;

  // 文件上传相关
  @ViewChild('fileInput') fileInput!: ElementRef<HTMLInputElement>;
  @ViewChild('dropZone') dropZone!: ElementRef<HTMLDivElement>;

  isUploading: boolean = false;
  uploadProgress: number = 0;
  projectFiles: Array<any|{
    id: string;
    name: string;
    url: string;
    type: string;
    size: number;
    fileType: string;
    uploadedBy: string;
    uploadedAt: Date;
    spaceId?: string;
  }> = [];

  // 企业微信拖拽相关
  dragOver: boolean = false;
  wxFileDropSupported: boolean = false;

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

  // 检查企业微信拖拽支持
  private checkWxWorkSupport(): void {
    // 检查是否在企业微信环境中
    if (typeof window !== 'undefined' && (window as any).wx) {
      this.wxFileDropSupported = true;
      console.log('✅ 企业微信环境，支持文件拖拽');

      // 监听企业微信文件拖拽事件
      this.initWxWorkFileDrop();
    }
  }

  // 初始化企业微信文件拖拽
  private initWxWorkFileDrop(): void {
    if (!this.wxFileDropSupported) return;

    // 监听企业微信的文件拖拽事件
    document.addEventListener('dragover', (e) => {
      if (this.isWxWorkFileDrop(e)) {
        e.preventDefault();
        this.dragOver = true;
      }
    });

    document.addEventListener('dragleave', (e) => {
      if (this.isWxWorkFileDrop(e)) {
        e.preventDefault();
        this.dragOver = false;
      }
    });

    document.addEventListener('drop', (e) => {
      if (this.isWxWorkFileDrop(e)) {
        e.preventDefault();
        this.dragOver = false;
        this.handleWxWorkFileDrop(e);
      }
    });
  }

  // 判断是否为企业微信文件拖拽
  private isWxWorkFileDrop(event: DragEvent): boolean {
    if (!this.wxFileDropSupported) return false;

    // 检查拖拽的数据是否包含企业微信文件信息
    const dataTransfer = event.dataTransfer;
    if (dataTransfer && dataTransfer.types) {
      return dataTransfer.types.includes('Files') ||
             dataTransfer.types.includes('application/x-wx-work-file');
    }

    return false;
  }

  // 处理企业微信文件拖拽
  private async handleWxWorkFileDrop(event: DragEvent): Promise<void> {
    if (!this.project) return;

    const files = Array.from(event.dataTransfer?.files || []);
    if (files.length === 0) return;

    console.log('🎯 接收到企业微信拖拽文件:', files.map(f => f.name));

    // 上传到当前选中的空间，如果没有选中则上传到项目根目录
    const spaceId = this.activeSpaceId || '';
    await this.uploadFiles(files, '企业微信拖拽', spaceId);
  }

  async ngOnInit() {
    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;

      // 使用FmodeParse加载项目、客户、当前用户
      if (!this.project && this.projectId) {
        const query = new Parse.Query('Project');
        query.include('customer', 'assignee', 'department');
        this.project = await query.get(this.projectId);
        this.customer = this.project.get('customer');
      }

      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();

        const role = this.currentUser?.get('roleName') || '';
        this.canEdit = ['客服', '组员', '组长', '管理员'].includes(role);
      }

      // 加载项目信息
      if (this.project) {
        this.projectInfo.title = this.project.get('title') || '';
        this.projectInfo.projectType = this.project.get('projectType') || '';
        this.projectInfo.renderType = this.project.get('renderType') || '';
        this.projectInfo.deadline = this.project.get('deadline') || '';
        this.projectInfo.description = this.project.get('description') || '';

        const data = this.project.get('data') || {};
        if (data.quotation) {
          this.quotation = data.quotation;
          // 检查是否为多空间项目
          this.isMultiSpaceProject = this.quotation.spaces.length > 1;
          this.projectInfo.spaceType = this.isMultiSpaceProject ? 'multi' : 'single';
        }

        if (data.priceLevel) {
          this.projectInfo.priceLevel = data.priceLevel;
        }

        if (data.spaceType) {
          this.projectInfo.spaceType = data.spaceType;
        }

        // 加载项目空间
        await this.loadProjectSpaces();

        // 加载场景选择数据
        if (data.homeScenes) {
          this.homeScenes = data.homeScenes;
        }
        if (data.commercialScenes) {
          this.commercialScenes = data.commercialScenes;
        }

        // 团队分配由 TeamAssign 组件管理
      }

      // 加载项目文件
      await this.loadProjectFiles();

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

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

    try {
      this.loadingSpaces = true;

      // 从ProjectSpace表加载空间数据
      this.projectSpaces = await this.productSpaceService.getProjectProductSpaces(this.project.id || '');

      // 如果没有空间数据，但从项目数据中有报价信息，则转换创建默认空间
      if (this.projectSpaces.length === 0) {
        const data = this.project.get('data') || {};
        if (data.quotation?.spaces) {
          await this.createSpacesFromQuotation(data.quotation.spaces);
        }
      }

      // 设置默认选中第一个空间
      if (this.projectSpaces.length > 0 && !this.activeSpaceId) {
        this.activeSpaceId = this.projectSpaces[0].id;
      }

    } catch (error) {
      console.error('加载项目空间失败:', error);
    } finally {
      this.loadingSpaces = false;
      this.cdr.markForCheck();
    }
  }

  /**
   * 从报价数据创建空间记录
   */
  private async createSpacesFromQuotation(quotationSpaces: any[]): Promise<void> {
    for (const spaceData of quotationSpaces) {
      try {
        const space: Partial<Project> = {
          name: spaceData.name,
          type: this.inferSpaceType(spaceData.name),
          priority: 5,
          status: 'not_started',
          complexity: 'medium',
          estimatedBudget: this.calculateSpaceRate(spaceData),
          order: quotationSpaces.indexOf(spaceData)
        };

        await this.productSpaceService.createProductSpace(this.project!.id || '', space);
      } catch (error) {
        console.error(`创建空间 ${spaceData.name} 失败:`, error);
      }
    }

    // 重新加载空间列表
    await this.loadProjectSpaces();
  }

  /**
   * 推断空间类型
   */
  private inferSpaceType(spaceName: string): string {
    const lowerName = spaceName.toLowerCase();
    for (const [type, name] of Object.entries(this.spaceTypeMap)) {
      if (typeof name == "string" && lowerName.includes(name)) {
        return type;
      }
    }
    return 'other';
  }

  /**
   * 计算空间预算
   */
  private calculateSpaceRate(spaceData: any): number {
    let total = 0;
    for (const process of Object.values(spaceData.processes || {})) {
      const proc = process as any;
      if (proc.enabled) {
        total += proc.price * proc.quantity;
      }
    }
    return total;
  }

  /**
   * 切换空间类型
   */
  onSpaceTypeChange() {
    this.quotation.spaces = [];
    this.quotation.total = 0;

    if (this.projectInfo.projectType === '家装') {
      this.homeScenes = {
        spaceType: '',
        styleLevel: '',
        rooms: []
      };
      this.commercialScenes = { businessType: '', spaces: [] };
    } else if (this.projectInfo.projectType === '工装') {
      this.commercialScenes = {
        businessType: '',
        spaces: []
      };
      this.homeScenes = { spaceType: '', styleLevel: '', rooms: [] };
    }
  }

  /**
   * 项目空间模式改变（单空间/多空间）
   */
  async onProjectSpaceModeChange() {
    this.isMultiSpaceProject = this.projectInfo.spaceType === 'multi';

    if (!this.isMultiSpaceProject) {
      // 单空间模式：重置为第一个空间
      if (this.projectSpaces.length > 0) {
        this.activeSpaceId = this.projectSpaces[0].id;
      }
      this.quotation.spaces = this.quotation.spaces.slice(0, 1);
      this.calculateTotal();
    } else {
      // 多空间模式：恢复所有空间
      await this.regenerateQuotationFromSpaces();
    }
  }

  /**
   * 添加新空间
   */
  async addSpace() {
    const spaceName = prompt('请输入空间名称:');
    if (!spaceName) return;

    try {
      const spaceData: Partial<Project> = {
        name: spaceName,
        type: 'other',
        priority: 5,
        status: 'not_started',
        complexity: 'medium',
        order: this.projectSpaces.length
      };

      const createdSpace = await this.productSpaceService.createProductSpace(this.projectId!, spaceData);
      this.projectSpaces.push(createdSpace);

      // 如果是第一个空间，设置为当前空间
      if (this.projectSpaces.length === 1) {
        this.activeSpaceId = createdSpace.id;
      }

      // 重新生成报价
      await this.regenerateQuotationFromSpaces();

      alert('空间添加成功');
    } catch (error) {
      console.error('添加空间失败:', error);
      alert('添加失败，请重试');
    }
  }

  /**
   * 编辑空间
   */
  async editSpace(spaceId: string) {
    const space = this.projectSpaces.find(s => s.id === spaceId);
    if (!space) return;

    const newName = prompt('修改空间名称:', space.name);
    if (!newName || newName === space.name) return;

    try {
      await this.productSpaceService.updateProductSpace(spaceId, { name: newName });
      space.name = newName;

      // 更新报价中的空间名称
      const quotationSpace = this.quotation.spaces.find(s => s.spaceId === spaceId);
      if (quotationSpace) {
        quotationSpace.name = newName;
      }

      // 保存到项目数据
      await this.saveDraft();

      alert('空间更新成功');
    } catch (error) {
      console.error('更新空间失败:', error);
      alert('更新失败，请重试');
    }
  }

  /**
   * 删除空间
   */
  async deleteSpace(spaceId: string) {
    if (!confirm('确定要删除这个空间吗？相关数据将被清除。')) return;

    try {
      await this.productSpaceService.deleteProductSpace(spaceId);

      // 从本地列表中移除
      this.projectSpaces = this.projectSpaces.filter(s => s.id !== spaceId);

      // 如果删除的是当前空间，切换到第一个空间
      if (this.activeSpaceId === spaceId && this.projectSpaces.length > 0) {
        this.activeSpaceId = this.projectSpaces[0].id;
      }

      // 重新生成报价
      await this.regenerateQuotationFromSpaces();

      alert('空间删除成功');
    } catch (error) {
      console.error('删除空间失败:', error);
      alert('删除失败，请重试');
    }
  }

  /**
   * 从空间重新生成报价
   */
  private async regenerateQuotationFromSpaces(): Promise<void> {
    this.quotation.spaces = [];

    // 为每个空间生成报价
    for (const space of this.projectSpaces) {
      if (this.projectInfo.projectType === '家装') {
        const roomData = this.homeScenes.rooms.find(r => r.name === space.name);
        if (roomData) {
          const finalPrice = calculateFinalPrice(
            roomData.basePrice,
            '家装',
            roomData.adjustments
          );

          const processes = getDefaultProcesses('家装', finalPrice);

          this.quotation.spaces.push({
            name: space.name,
            spaceId: space.id,
            processes: processes as any,
            subtotal: finalPrice + processes.postProcess.price
          });
        }
      } else if (this.projectInfo.projectType === '工装') {
        const spaceData = this.commercialScenes.spaces.find(s => s.name === space.name);
        if (spaceData) {
          const finalPrice = calculateFinalPrice(
            spaceData.basePrice,
            '工装',
            spaceData.adjustments
          );

          const processes = getDefaultProcesses('工装', finalPrice);

          this.quotation.spaces.push({
            name: space.name,
            spaceId: space.id,
            processes: processes as any,
            subtotal: finalPrice + processes.postProcess.price
          });
        }
      }
    }

    this.calculateTotal();
    this.updateSpaceBreakdown();
  }

  /**
   * 更新空间占比
   */
  private updateSpaceBreakdown(): void {
    this.quotation.spaceBreakdown = this.quotation.spaces.map(space => ({
      spaceName: space.name,
      spaceId: space.spaceId || '',
      amount: space.subtotal,
      percentage: this.quotation.total > 0 ? Math.round((space.subtotal / this.quotation.total) * 100) : 0
    }));
  }

  // 注意：报价生成和管理功能已移至 quotation-editor 组件
// 以下方法保留用于兼容性和数据处理

  /**
   * 计算报价总额（兼容性方法）
   */
  calculateTotal() {
    let total = 0;
    for (const space of this.quotation.spaces) {
      for (const processKey of Object.keys(space.processes)) {
        const process = space.processes[processKey as keyof typeof space.processes];
        if (process.enabled) {
          total += process.price * process.quantity;
        }
      }
    }
    this.quotation.total = total;
  }


  /**
   * 获取空间进度
   */
  getSpaceProgress(spaceId: string): number {
    if (!spaceId || !this.isMultiSpaceProject) return 0;
    return this.productSpaceService.calculateProductProgress(spaceId, this.processTypes.map(p => p.key));
  }

  /**
   * 获取空间状态
   */
  getSpaceStatus(space: Project): string {
    if (!space) return 'unknown';
    return space.status;
  }

  /**
   * 获取空间状态颜色
   */
  getSpaceStatusColor(status: string): string {
    const colorMap: Record<string, string> = {
      'not_started': 'medium',
      'in_progress': 'warning',
      'awaiting_review': 'info',
      'completed': 'success',
      'blocked': 'danger',
      'delayed': 'danger'
    };
    return colorMap[status] || 'medium';
  }

  /**
   * 获取空间状态文本
   */
  getSpaceStatusText(status: string): string {
    const textMap: Record<string, string> = {
      'not_started': '未开始',
      'in_progress': '进行中',
      'awaiting_review': '待审核',
      'completed': '已完成',
      'blocked': '已阻塞',
      'delayed': '已延期'
    };
    return textMap[status] || status;
  }

  /**
   * 选择项目组（Department）
   */
  // 团队分配相关逻辑已迁移至 TeamAssignComponent

  /**
   * 报价数据变化回调
   */
  onQuotationChange(updatedQuotation: any) {
    this.quotation = updatedQuotation;
    this.updateSpaceBreakdown();
  }

  /**
   * 报价总额变化回调
   */
  onTotalChange(total: number) {
    this.quotation.total = total;
    this.updateSpaceBreakdown();
  }

  /**
   * 报价加载状态变化回调
   */
  onQuotationLoadingChange(loading: boolean) {
    // 可以在这里处理加载状态，比如显示loading indicator
  }

  /**
   * 产品列表变化回调
   */
  onProductsChange(products: any[]) {
    // 可以在这里处理产品列表变化
    console.log('产品列表已更新:', products.length, '个产品');
  }

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

    try {
      this.saving = true;

      this.project.set('title', this.projectInfo.title);
      this.project.set('projectType', this.projectInfo.projectType);
      this.project.set('renderType', this.projectInfo.renderType);
      this.project.set('deadline', this.projectInfo.deadline);
      this.project.set('description', this.projectInfo.description);
      this.project.set('spaceType', this.projectInfo.spaceType);

      const data = this.project.get('data') || {};
      data.quotation = this.quotation;
      data.priceLevel = this.projectInfo.priceLevel;
      data.homeScenes = this.homeScenes;
      data.commercialScenes = this.commercialScenes;
      this.project.set('data', data);

      // 团队分配由 TeamAssign 组件负责，不在此保存 department/assignee

      await this.project.save();

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

  /**
   * 提交订单分配
   */
  async submitForOrder() {
    if (!this.project || !this.canEdit) return;

    // 基础验证
    if (!this.projectInfo.title.trim()) {
      alert('请填写项目名称');
      return;
    }
    if (!this.projectInfo.projectType) {
      alert('请选择项目类型');
      return;
    }
    if (!this.projectInfo.deadline) {
      alert('请选择交付期限');
      return;
    }
    if (this.quotation.total === 0) {
      alert('请配置报价明细');
      return;
    }

    try {
      this.saving = true;

      // 校验是否已在 TeamAssign 中分配至少一位组员
      const query = new Parse.Query('ProjectTeam');
      query.equalTo('project', this.project.toPointer());
      query.include('profile');
      query.notEqualTo('isDeleted', true);
      const assignedTeams = await query.find();
      if (assignedTeams.length === 0) {
        alert('请在“设计师分配”中分配至少一位组员');
        this.saving = false;
        return;
      }

      await this.saveDraft();

      // 推进阶段
      this.project.set('currentStage', '确认需求');

      // 记录审批历史（包含团队快照）
      const data = this.project.get('data') || {};
      const approvalHistory = data.approvalHistory || [];

      const teamSnapshot = assignedTeams.map(team => {
        const profile = team.get('profile');
        const spaces = team.get('data')?.spaces || [];
        return {
          id: profile?.id,
          name: profile?.get('name'),
          spaces
        };
      });

      approvalHistory.push({
        stage: '订单分配',
        submitter: {
          id: this.currentUser!.id,
          name: this.currentUser!.get('name'),
          role: this.currentUser!.get('roleName')
        },
        submitTime: new Date(),
        status: 'confirm',
        quotationTotal: this.quotation.total,
        teams: teamSnapshot
      });

      data.approvalHistory = approvalHistory;
      this.project.set('data', data);

      await this.project.save();

      alert('提交成功，等待组长审批');

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

  /**
   * 加载项目文件
   */
  private async loadProjectFiles(): Promise<void> {
    if (!this.project) return;

    try {
      const query = new Parse.Query('ProjectFile');
      query.equalTo('project', this.project.toPointer());
      query.include('uploadedBy');
      query.include('attach');
      query.descending('uploadedAt');
      query.limit(50);

      const files = await query.find();

      this.projectFiles = files.map((file: FmodeObject) => {
        const attach = file.get('attach');
        return {
          id: file.id || '',
          name: attach?.get('name') || attach?.get('originalName') || file.get('name') || file.get('originalName') || '',
          url: attach?.get('url') || file.get('url') || '',
          type: attach?.get('type') || file.get('type') || '',
          size: attach?.get('size') || file.get('size') || 0,
          uploadedBy: file.get('uploadedBy')?.get('name') || '未知用户',
          uploadedAt: file.get('uploadedAt') || file.createdAt
        };
      });

      console.log(`✅ 加载了 ${this.projectFiles.length} 个项目文件`);
    } catch (error) {
      console.error('❌ 加载项目文件失败:', error);
    }
  }

  /**
   * 触发文件选择
   */
  triggerFileSelect(): void {
    if (!this.canEdit || !this.project) return;
    this.fileInput.nativeElement.click();
  }

  /**
   * 处理文件选择
   */
  async onFileSelect(event: Event): Promise<void> {
    const target = event.target as HTMLInputElement;
    const files = Array.from(target.files || []);

    if (files.length > 0) {
      // 上传到当前选中的空间，如果没有选中则上传到项目根目录
      const spaceId = this.activeSpaceId || '';
      await this.uploadFiles(files, '手动选择', spaceId);
    }

    // 清空input值，允许重复选择同一文件
    target.value = '';
  }

  /**
   * 上传文件到 ProjectFile 表
   */
  private async uploadFiles(
    files: File[],
    source: string,
    spaceId?: string
  ): Promise<void> {
    if (!this.project || !this.currentUser) {
      console.error('❌ 缺少必要信息，无法上传文件');
      return;
    }

    this.isUploading = true;
    this.uploadProgress = 0;

    try {
      const results = [];

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

        // 更新进度
        this.uploadProgress = ((i + 1) / files.length) * 100;

        try {
          // 使用 ProjectFileService 上传文件
          const uploadedFile = await this.projectFileService.uploadProjectFile(
            file,
            this.projectId,
            'order',
            spaceId,
            undefined,
            {
              source,
              uploadTime: new Date(),
              uploader: this.currentUser.get('name')
            },
            (progress) => {
              const fileProgress = (i / files.length) * 100 + (progress / files.length);
              this.uploadProgress = fileProgress;
            }
          );

          // 创建 Attachment 记录并设置元数据
          const attachment = new Parse.Object('Attachment');
          attachment.set('name', file.name);
          attachment.set('originalName', file.name);
          attachment.set('url', uploadedFile.url);
          attachment.set('key', uploadedFile.key);
          attachment.set('type', file.type || (uploadedFile?.metadata ? uploadedFile.metadata['mime'] : '') || '');
          attachment.set('size', file.size);
          attachment.set('md5', uploadedFile.md5);
          attachment.set('metadata', uploadedFile.metadata || {});
          attachment.set('source', source);
          attachment.set('user', this.currentUser.toPointer());
          const companyPtr = this.project?.get('company');
          if (companyPtr) {
            attachment.set('company', companyPtr.toPointer ? companyPtr.toPointer() : companyPtr);
          }
          const savedAttachment = await attachment.save();

          // 保存文件信息到 ProjectFile 表，指向 attach
          const projectFile = new Parse.Object('ProjectFile');
          projectFile.set('project', this.project.toPointer());
          projectFile.set('attach', savedAttachment.toPointer ? savedAttachment.toPointer() : savedAttachment);
          projectFile.set('uploadedBy', this.currentUser.toPointer());
          projectFile.set('uploadedAt', new Date());
          projectFile.set('source', source); // 标记来源：企业微信拖拽或手动选择
          // 兼容字段：保留 key（若旧代码需要）
          projectFile.set('key', uploadedFile.key);

          const savedFile = await projectFile.save();

          // 添加到本地列表（从 attach 读取展示字段）
          this.projectFiles.unshift({
            id: savedFile.id || '',
            name: savedAttachment.get('name'),
            url: savedAttachment.get('url') || '',
            type: savedAttachment.get('type') || '',
            size: savedAttachment.get('size') || 0,
            uploadedBy: this.currentUser.get('name'),
            uploadedAt: new Date()
          });

          results.push({
            success: true,
            file: uploadedFile,
            name: file.name
          });

          console.log('✅ 文件上传成功:', file.name, uploadedFile.key);

        } catch (error) {
          console.error('❌ 文件上传失败:', file.name, error);
          results.push({
            success: false,
            error: error instanceof Error ? error.message : '上传失败',
            name: file.name
          });
        }
      }

      // 显示上传结果
      const successCount = results.filter(r => r.success).length;
      const failCount = results.filter(r => !r.success).length;

      if (failCount === 0) {
        console.log(`🎉 所有 ${successCount} 个文件上传成功`);
      } else {
        console.warn(`⚠️ ${successCount} 个文件成功，${failCount} 个文件失败`);
      }

    } catch (error) {
      console.error('❌ 批量上传过程中发生错误:', error);
    } finally {
      this.isUploading = false;
      this.uploadProgress = 0;
    }
  }

  /**
   * 处理拖拽事件
   */
  onDragOver(event: DragEvent): void {
    event.preventDefault();
    event.stopPropagation();
    this.dragOver = true;
  }

  onDragLeave(event: DragEvent): void {
    event.preventDefault();
    event.stopPropagation();
    this.dragOver = false;
  }

  async onDrop(event: DragEvent): Promise<void> {
    event.preventDefault();
    event.stopPropagation();
    this.dragOver = false;

    if (!this.canEdit || !this.project) return;

    const files = Array.from(event.dataTransfer?.files || []);
    if (files.length > 0) {
      console.log('🎯 接收到拖拽文件:', files.map(f => f.name));
      // 上传到当前选中的空间，如果没有选中则上传到项目根目录
      const spaceId = this.activeSpaceId || '';
      await this.uploadFiles(files, '拖拽上传', spaceId);
    }
  }

  /**
   * 删除项目文件
   */
  async deleteProjectFile(fileId: string): Promise<void> {
    if (!this.canEdit) return;

    try {
      await this.projectFileService.deleteProjectFile(fileId);

      // 从本地列表中移除
      this.projectFiles = this.projectFiles.filter(f => f.id !== fileId);

      console.log('✅ 文件删除成功:', fileId);
    } catch (error) {
      console.error('❌ 文件删除失败:', error);
      alert('删除失败，请稍后重试');
    }
  }

  /**
   * 格式化文件大小
   */
  formatFileSize(size: number): string {
    if (size == null || isNaN(size)) return '0 B';
    const units = ['B', 'KB', 'MB', 'GB', 'TB'];
    let idx = 0;
    let value = size;
    while (value >= 1024 && idx < units.length - 1) {
      value /= 1024;
      idx++;
    }
    const formatted = value >= 100 ? Math.round(value).toString() : value.toFixed(1);
    return `${formatted} ${units[idx]}`;
  }

  /**
   * 获取文件图标
   */
  getFileIcon(type: string): string {
    if (type.startsWith('image/')) return '🖼️';
    if (type.startsWith('video/')) return '🎬';
    if (type.startsWith('audio/')) return '🎵';
    if (type.includes('pdf')) return '📄';
    if (type.includes('word') || type.includes('document')) return '📝';
    if (type.includes('excel') || type.includes('spreadsheet')) return '📊';
    if (type.includes('powerpoint') || type.includes('presentation')) return '📑';
    if (type.includes('zip') || type.includes('rar') || type.includes('7z')) return '📦';
    return '📎';
  }

  /**
   * 检查是否为图片文件
   */
  isImageFile(type: string): boolean {
    return type.startsWith('image/');
  }

  /**
   * 下载文件
   */
  downloadFile(url: string, name: string): void {
    const link = document.createElement('a');
    link.href = url;
    link.download = name;
    link.target = '_blank';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  // UI 辅助方法
  hasSpacesDisabled(): boolean {
    return !this.canEdit || !this.commercialScenes?.spaces?.some(s => s?.selected)
  }

  hasRoomsDisabled(): boolean {
    return !this.canEdit || !this.homeScenes?.rooms?.some((r: { selected?: boolean }) => r?.selected === true)
  }

  getLevels(levels: any): string[] {
    if (!levels) return []
    return Object.keys(levels)
  }

  /**
   * 获取空间类型的显示名称
   */
  getSpaceTypeName(spaceType: string): string {
    let name = this.spaceTypeMap?.[spaceType] || '其他';
    return name
  }

  /**
   * 获取空间图标
   */
  getSpaceIcon(spaceType: 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': 'other'
    };
    return iconMap[spaceType] || 'room';
  }

  /**
   * 获取进程颜色
   */
  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<{ spaceId: string; spaceName: string; items: any[] }> {
    if (!this.isMultiSpaceProject) {
      return [{
        spaceId: 'default',
        spaceName: '单空间项目',
        items: []
      }];
    }

    const grouped = new Map<string, any[]>();

    for (const space of this.projectSpaces) {
      const deliverables = this.quotation.spaces.filter(d => d.spaceId === space.id);
      if (deliverables.length > 0) {
        grouped.set(space.id, deliverables);
      }
    }

    return Array.from(grouped.entries()).map(([spaceId, items]) => ({
      spaceId,
      spaceName: items[0]?.name || '未知空间',
      items
    }));
  }

  /**
   * 计算完成进度
   */
  get completionProgress(): number {
    if (this.quotation.spaces.length === 0) return 0;
    const approvedCount = this.quotation.spaces.filter(d => {
      return Object.values(d.processes).some((p: any) => p.enabled);
    }).length;
    return Math.round((approvedCount / this.quotation.spaces.length) * 100);
  }

  /**
   * 获取总进度（多空间）
   */
  getOverallProgress(): number {
    if (!this.isMultiSpaceProject) return this.completionProgress;

    let totalProgress = 0;
    let totalSpaces = 0;

    for (const space of this.projectSpaces) {
      const spaceProgress = this.getSpaceProgress(space.id);
      totalProgress += spaceProgress;
      totalSpaces++;
    }

    return totalSpaces > 0 ? Math.round(totalProgress / totalSpaces) : 0;
  }

  /**
   * 获取当前选中的空间信息
   */
  get currentSpace(): Project | null {
    if (!this.isMultiSpaceProject || !this.activeSpaceId) return null;
    return this.projectSpaces.find(s => s.id === this.activeSpaceId) || null;
  }
}