import { Component, OnInit, Input, 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 { WxworkAuth } from 'fmode-ng/social';

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

/**
 * 交付文件接口
 */
interface DeliveryFile {
  id: string;
  url: string;
  name: string;
  size: number;
  uploadTime: Date;
  uploadedBy: string;
  productId: string;
  deliveryType: 'white_model' | 'soft_decor' | 'rendering' | 'post_process';
  stage: string;
  projectFile?: FmodeObject;
}

/**
 * 交付执行阶段组件
 *
 * 功能：
 * 1. 白模、软装、渲染、后期四种交付类型管理
 * 2. 多场景Product分开管理交付物
 * 3. 使用ProjectFileService存储文件
 * 4. 数据持久化到FmodeParse
 */
@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 = true;

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

  // Product-based 场景管理
  projectProducts: Project[] = [];
  isMultiProductProject: boolean = false;
  activeProductId: string = '';

  // 交付类型定义
  deliveryTypes = [
    {
      id: 'white_model',
      name: '白模',
      icon: 'cube-outline',
      color: 'primary',
      description: '空间结构建模、基础框架搭建'
    },
    {
      id: 'soft_decor',
      name: '软装',
      icon: 'color-palette-outline',
      color: 'secondary',
      description: '家具配置、材质选择、色彩搭配'
    },
    {
      id: 'rendering',
      name: '渲染',
      icon: 'image-outline',
      color: 'tertiary',
      description: '高清效果图、全景图、细节特写'
    },
    {
      id: 'post_process',
      name: '后期',
      icon: 'color-wand-outline',
      color: 'success',
      description: '色彩调整、效果优化、最终成品'
    }
  ];

  activeDeliveryType: string = 'white_model';

  // 交付文件管理 (按Product和类型分类)
  deliveryFiles: {
    [productId: string]: {
      white_model: DeliveryFile[];
      soft_decor: DeliveryFile[];
      rendering: DeliveryFile[];
      post_process: DeliveryFile[];
    };
  } = {};

  // 上传进度
  uploadingDeliveryFiles: boolean = false;
  uploadProgress: number = 0;

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

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

  async ngOnInit() {
    // 从路由或Input获取参数
    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('contact', 'assignee');
        this.project = await query.get(this.projectId);
        this.customer = this.project.get('contact');
      }

      // 如果没有currentUser，尝试获取
      if (!this.currentUser && this.cid) {
        // @ts-ignore - WxworkAuth type issue with fmode-ng
        const wxwork = new WxworkAuth({ cid: this.cid, appId: 'crm' });
        this.currentUser = await wxwork.currentProfile();

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

      // 加载项目场景Product数据
      if (this.project) {
        await this.loadProjectProducts();
        await this.loadDeliveryFiles();
      }

      this.cdr.markForCheck();

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

  /**
   * 加载项目的Product场景数据
   */
  async loadProjectProducts(): Promise<void> {
    if (!this.project) return;

    try {
      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;
      }

      console.log(`已加载 ${this.projectProducts.length} 个场景Product`);
    } catch (error) {
      console.error('加载项目场景失败:', error);
    }
  }

  /**
   * 加载交付文件 (从ProjectFile表按category查询)
   */
  async loadDeliveryFiles(): Promise<void> {
    if (!this.project) return;

    try {
      const targetProjectId = this.project.id!;

      // 为每个产品初始化交付文件结构
      for (const product of this.projectProducts) {
        this.deliveryFiles[product.id] = {
          white_model: [],
          soft_decor: [],
          rendering: [],
          post_process: []
        };

        // 加载各类型的交付文件
        for (const deliveryType of this.deliveryTypes) {
          const files = await this.projectFileService.getProjectFiles(
            targetProjectId,
            {
              fileType: `delivery_${deliveryType.id}`,
              stage: 'delivery'
            }
          );

          // 过滤当前产品的文件
          const productFiles = files.filter(file => {
            const data = file.get('data');
            return data?.productId === product.id || data?.spaceId === product.id;
          });

          // 转换为DeliveryFile格式
          this.deliveryFiles[product.id][deliveryType.id as keyof typeof this.deliveryFiles[typeof product.id]] = productFiles.map(projectFile => ({
            id: projectFile.id || '',
            url: projectFile.get('fileUrl') || '',
            name: projectFile.get('fileName') || '',
            size: projectFile.get('fileSize') || 0,
            uploadTime: projectFile.createdAt || new Date(),
            uploadedBy: projectFile.get('uploadedBy')?.get('name') || '',
            productId: product.id,
            deliveryType: deliveryType.id as any,
            stage: 'delivery',
            projectFile: projectFile
          }));
        }
      }

      this.cdr.markForCheck();
      console.log('已加载交付文件:', this.deliveryFiles);

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

  /**
   * 选择场景Product
   */
  selectProduct(productId: string): void {
    this.activeProductId = productId;
    this.cdr.markForCheck();
  }

  /**
   * 选择交付类型
   */
  selectDeliveryType(typeId: string): void {
    this.activeDeliveryType = typeId;
    this.cdr.markForCheck();
  }

  /**
   * 上传交付文件
   */
  async uploadDeliveryFile(event: any, productId: string, deliveryType: string): Promise<void> {
    const files = event.target.files;
    if (!files || files.length === 0) return;

    try {
      this.uploadingDeliveryFiles = true;
      this.uploadProgress = 0;
      const targetProjectId = this.projectId || this.project?.id;

      if (!targetProjectId) {
        console.error('未找到项目ID，无法上传文件');
        return;
      }

      // 初始化产品的交付文件结构（如果不存在）
      if (!this.deliveryFiles[productId]) {
        this.deliveryFiles[productId] = {
          white_model: [],
          soft_decor: [],
          rendering: [],
          post_process: []
        };
      }

      const totalFiles = files.length;
      let uploadedFiles = 0;

      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;
        }

        // 使用ProjectFileService上传到服务器并创建ProjectFile记录
        const projectFile = await this.projectFileService.uploadProjectFileWithRecord(
          file,
          targetProjectId,
          `delivery_${deliveryType}`,
          productId,
          'delivery', // stage参数
          {
            deliveryType: deliveryType,
            productId: productId,
            uploadedFor: 'delivery_execution'
          },
          (progress) => {
            // 计算总体进度
            const fileProgress = (uploadedFiles + (progress / 100)) / totalFiles;
            this.uploadProgress = Math.round(fileProgress * 100);
            this.cdr.markForCheck();
          }
        );

        // 创建交付文件记录
        const deliveryFile: DeliveryFile = {
          id: projectFile.id || '',
          url: projectFile.get('fileUrl') || '',
          name: projectFile.get('fileName') || file.name,
          size: projectFile.get('fileSize') || file.size,
          uploadTime: projectFile.createdAt || new Date(),
          uploadedBy: this.currentUser?.get('name') || '',
          productId: productId,
          deliveryType: deliveryType as any,
          stage: 'delivery',
          projectFile: projectFile
        };

        // 添加到对应类型的数组中
        if (deliveryFile.id) {
          this.deliveryFiles[productId][deliveryType as keyof typeof this.deliveryFiles[typeof productId]].push(deliveryFile);
        }

        uploadedFiles++;
        this.uploadProgress = Math.round((uploadedFiles / totalFiles) * 100);
      }

      this.cdr.markForCheck();
      console.log(`成功上传 ${uploadedFiles} 个交付文件`);

    } catch (error) {
      console.error('上传交付文件失败:', error);
      alert('文件上传失败，请重试');
    } finally {
      this.uploadingDeliveryFiles = false;
      this.uploadProgress = 0;
      this.cdr.markForCheck();
    }
  }

  /**
   * 删除交付文件
   */
  async deleteDeliveryFile(productId: string, deliveryType: string, fileId: string): Promise<void> {
    if (!confirm('确定要删除这个文件吗？')) {
      return;
    }

    try {
      // 查找文件
      const fileArray = this.deliveryFiles[productId][deliveryType as keyof typeof this.deliveryFiles[typeof productId]];
      const file = fileArray.find(f => f.id === fileId);

      if (file && file.projectFile) {
        // 使用ProjectFileService删除服务器上的文件
        await this.projectFileService.deleteProjectFile(fileId);
      }

      // 从列表中移除
      this.deliveryFiles[productId][deliveryType as keyof typeof this.deliveryFiles[typeof productId]] =
        fileArray.filter(f => f.id !== fileId);

      this.cdr.markForCheck();

    } catch (error) {
      console.error('删除交付文件失败:', error);
      alert('删除文件失败，请重试');
    }
  }

  /**
   * 获取产品的交付文件
   */
  getProductDeliveryFiles(productId: string, deliveryType: string): DeliveryFile[] {
    if (!this.deliveryFiles[productId]) {
      return [];
    }
    return this.deliveryFiles[productId][deliveryType as keyof typeof this.deliveryFiles[typeof productId]] || [];
  }

  /**
   * 获取产品所有交付类型的文件总数
   */
  getTotalDeliveryFileCount(productId: string): number {
    if (!this.deliveryFiles[productId]) return 0;

    return this.deliveryTypes.reduce((total, type) => {
      const files = this.getProductDeliveryFiles(productId, type.id);
      return total + files.length;
    }, 0);
  }

  /**
   * 获取当前类型的文件数量
   */
  getCurrentTypeFileCount(productId: string, typeId: string): number {
    return this.getProductDeliveryFiles(productId, typeId).length;
  }

  /**
   * 获取交付类型名称
   */
  getDeliveryTypeName(typeId: string): string {
    const type = this.deliveryTypes.find(t => t.id === typeId);
    return type?.name || typeId;
  }

  /**
   * 获取交付类型描述
   */
  getDeliveryTypeDescription(typeId: string): string {
    const type = this.deliveryTypes.find(t => t.id === typeId);
    return type?.description || '';
  }

  /**
   * 触发文件输入点击
   */
  triggerFileInput(inputId: string): void {
    const element = document.getElementById(inputId) as HTMLInputElement;
    if (element) {
      element.click();
    }
  }

  /**
   * 格式化文件大小
   */
  formatFileSize(bytes: number): string {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }

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

  /**
   * 判断是否为图片文件
   */
  isImageFile(filename: string): boolean {
    const ext = filename.split('.').pop()?.toLowerCase();
    return ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(ext || '');
  }

  /**
   * 预览文件
   */
  previewFile(file: DeliveryFile): void {
    window.open(file.url, '_blank');
  }

  /**
   * 下载文件
   */
  downloadFile(file: DeliveryFile): void {
    const link = document.createElement('a');
    link.href = file.url;
    link.download = file.name;
    link.click();
  }
}
