import { GenericCrudService } from '@d8d/shared-crud';
import { DataSource, Repository, DataSourceOptions, In, Not } from 'typeorm';
import { EmploymentOrder } from '../entities/employment-order.entity';
import { OrderPerson } from '../entities/order-person.entity';
import { OrderPersonAsset } from '../entities/order-person-asset.entity';
import { AssetType, AssetFileType, AssetStatus } from '../schemas/order.schema';
import { FileService, File } from '@d8d/core-module/file-module';
import { OrderStatus, WorkStatus } from '@d8d/allin-enums';

export class OrderService extends GenericCrudService<EmploymentOrder> {
  private readonly orderPersonRepository: Repository<OrderPerson>;
  private readonly orderPersonAssetRepository: Repository<OrderPersonAsset>;
  private readonly fileRepository: Repository<File>;
  private fileService: FileService;

  constructor(dataSource: DataSource) {
    super(dataSource, EmploymentOrder);
    this.orderPersonRepository = dataSource.getRepository(OrderPerson);
    this.orderPersonAssetRepository = dataSource.getRepository(OrderPersonAsset);
    this.fileRepository = dataSource.getRepository(File);
    this.fileService = new FileService(dataSource);
  }

  /**
   * 创建订单 - 覆盖父类方法，添加验证和业务逻辑
   */
  override async create(data: Partial<EmploymentOrder>, userId?: string | number): Promise<EmploymentOrder> {
    // 验证枚举值
    if (data.orderStatus && !Object.values(OrderStatus).includes(data.orderStatus)) {
      throw new Error('订单状态无效');
    }
    if (data.workStatus && !Object.values(WorkStatus).includes(data.workStatus)) {
      throw new Error('工作状态无效');
    }

    // 设置默认值
    const orderData = {
      ...data,
      orderStatus: data.orderStatus || OrderStatus.DRAFT,
      workStatus: data.workStatus || WorkStatus.NOT_WORKING,
    };

    return super.create(orderData, userId);
  }

  /**
   * 更新订单 - 覆盖父类方法，添加验证
   */
  override async update(id: number, data: Partial<EmploymentOrder>, userId?: string | number): Promise<EmploymentOrder | null> {
    // 验证枚举值
    if (data.orderStatus && !Object.values(OrderStatus).includes(data.orderStatus)) {
      throw new Error('订单状态无效');
    }
    if (data.workStatus && !Object.values(WorkStatus).includes(data.workStatus)) {
      throw new Error('工作状态无效');
    }

    return super.update(id, data, userId);
  }

  /**
   * 分页查询订单 - 自定义方法，返回源服务的格式
   */
  async findAll(query: {
    orderName?: string;
    platformId?: number;
    companyId?: number;
    channelId?: number;
    orderStatus?: OrderStatus;
    startDate?: string;
    endDate?: string;
    page?: number;
    limit?: number;
  }): Promise<{ data: any[]; total: number }> {
    const {
      orderName,
      platformId,
      companyId,
      channelId,
      orderStatus,
      startDate,
      endDate,
      page = 1,
      limit = 10
    } = query;

    const queryBuilder = this.repository.createQueryBuilder('order');

    // 构建查询条件
    if (orderName) {
      queryBuilder.andWhere('order.orderName LIKE :orderName', { orderName: `%${orderName}%` });
    }
    if (platformId) {
      queryBuilder.andWhere('order.platformId = :platformId', { platformId });
    }
    if (companyId) {
      queryBuilder.andWhere('order.companyId = :companyId', { companyId });
    }
    if (channelId) {
      queryBuilder.andWhere('order.channelId = :channelId', { channelId });
    }
    if (orderStatus) {
      queryBuilder.andWhere('order.orderStatus = :orderStatus', { orderStatus });
    }
    // 日期范围查询 - 基于createTime字段
    if (startDate) {
      queryBuilder.andWhere('order.createTime >= :startDate', { startDate: `${startDate}T00:00:00Z` });
    }
    if (endDate) {
      queryBuilder.andWhere('order.createTime <= :endDate', { endDate: `${endDate}T23:59:59Z` });
    }

    // 获取总数
    const total = await queryBuilder.getCount();

    // 获取数据
    const data = await queryBuilder
      .skip((page - 1) * limit)
      .take(limit)
      .orderBy('order.createTime', 'DESC')
      .getMany();

    // 获取每个订单的人员数量
    const orderIds = data.map(order => order.id);
    let personCounts: Array<{ orderId: number; count: number }> = [];

    if (orderIds.length > 0) {
      const personCountQuery = await this.orderPersonRepository
        .createQueryBuilder('orderPerson')
        .select('orderPerson.orderId', 'orderId')
        .addSelect('COUNT(orderPerson.id)', 'count')
        .where('orderPerson.orderId IN (:...orderIds)', { orderIds })
        .groupBy('orderPerson.orderId')
        .getRawMany();

      personCounts = personCountQuery.map(item => ({
        orderId: item.orderId,
        count: parseInt(item.count)
      }));
    }

    // 格式化返回数据
    const formattedData = data.map(order => {
      const personCount = personCounts.find(pc => pc.orderId === order.id)?.count || 0;
      return {
        id: order.id,
        orderName: order.orderName,
        platformId: order.platformId,
        companyId: order.companyId,
        channelId: order.channelId,
        expectedStartDate: order.expectedStartDate,
        actualStartDate: order.actualStartDate,
        actualEndDate: order.actualEndDate,
        orderStatus: order.orderStatus,
        workStatus: order.workStatus,
        createTime: order.createTime,
        updateTime: order.updateTime,
        personCount
      };
    });

    return { data: formattedData, total };
  }

  /**
   * 查询单个订单详情 - 自定义方法
   */
  async findOne(id: number): Promise<any | null> {
    const order = await this.repository.findOne({
      where: { id },
      relations: ['orderPersons', 'orderPersons.person']
    });

    if (!order) {
      return null;
    }

    // 获取订单人员详情（这里简化处理，实际可能需要关联更多信息）
    const orderPersons = order.orderPersons || [];

    return {
      id: order.id,
      orderName: order.orderName,
      platformId: order.platformId,
      companyId: order.companyId,
      channelId: order.channelId,
      expectedStartDate: order.expectedStartDate,
      actualStartDate: order.actualStartDate,
      actualEndDate: order.actualEndDate,
      orderStatus: order.orderStatus,
      workStatus: order.workStatus,
      createTime: order.createTime,
      updateTime: order.updateTime,
      orderPersons: orderPersons.map(person => ({
        id: person.id, // 注意：schema期望id字段，不是opId
        orderId: person.orderId,
        personId: person.personId,
        joinDate: person.joinDate,
        leaveDate: person.leaveDate,
        workStatus: person.workStatus,
        salaryDetail: person.salaryDetail,
        // 残疾人员的详细信息
        person: person.person ? {
          id: person.person.id,
          name: person.person.name,
          gender: person.person.gender,
          disabilityType: person.person.disabilityType,
          phone: person.person.phone,
          // 可以根据需要添加更多字段
        } : null
      }))
    };
  }

  /**
   * 订单激活 - 自定义业务方法
   */
  async activateOrder(orderId: number): Promise<boolean> {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      // 查询订单
      const order = await queryRunner.manager.findOne(EmploymentOrder, {
        where: { id: orderId }
      });

      if (!order) {
        throw new Error(`订单ID ${orderId} 不存在`);
      }

      if (order.orderStatus !== OrderStatus.DRAFT) {
        throw new Error(`只有草稿状态的订单才能激活，当前订单状态为: ${order.orderStatus}`);
      }

      // 更新订单状态为已确认
      order.orderStatus = OrderStatus.CONFIRMED;
      order.actualStartDate = new Date();
      await queryRunner.manager.save(order);

      // 更新订单人员状态为待就业
      await queryRunner.manager.update(OrderPerson,
        { orderId: orderId },
        { workStatus: WorkStatus.PRE_WORKING }
      );

      await queryRunner.commitTransaction();
      return true;
    } catch (error) {
      await queryRunner.rollbackTransaction();
      throw error;
    } finally {
      await queryRunner.release();
    }
  }

  /**
   * 订单关闭 - 自定义业务方法
   */
  async closeOrder(orderId: number): Promise<boolean> {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      // 查询订单
      const order = await queryRunner.manager.findOne(EmploymentOrder, {
        where: { id: orderId }
      });

      if (!order) {
        throw new Error(`订单ID ${orderId} 不存在`);
      }

      if (order.orderStatus !== OrderStatus.CONFIRMED && order.orderStatus !== OrderStatus.IN_PROGRESS) {
        throw new Error(`只有已确认或进行中的订单才能关闭，当前订单状态为: ${order.orderStatus}`);
      }

      // 更新订单状态为已完成
      order.orderStatus = OrderStatus.COMPLETED;
      order.actualEndDate = new Date();
      await queryRunner.manager.save(order);

      // 更新订单人员状态为已离职
      await queryRunner.manager.update(OrderPerson,
        { orderId: orderId },
        {
          workStatus: WorkStatus.RESIGNED,
          leaveDate: new Date()
        }
      );

      await queryRunner.commitTransaction();
      return true;
    } catch (error) {
      await queryRunner.rollbackTransaction();
      throw error;
    } finally {
      await queryRunner.release();
    }
  }

  /**
   * 批量添加人员到订单 - 自定义业务方法
   */
  async batchAddPersons(orderId: number, persons: Array<{
    personId: number;
    joinDate: Date;
    salaryDetail: number;
  }>): Promise<{ success: boolean; message: string; addedCount: number }> {
    // 验证订单是否存在
    const order = await this.repository.findOne({
      where: { id: orderId }
    });

    if (!order) {
      throw new Error(`订单ID ${orderId} 不存在`);
    }

    if (order.orderStatus === OrderStatus.COMPLETED || order.orderStatus === OrderStatus.CANCELLED) {
      throw new Error(`订单ID ${orderId} 已结束或已取消，无法添加人员`);
    }

    // 检查哪些人员已经在订单中
    const existingPersons = await this.orderPersonRepository.find({
      where: { orderId }
    });

    const existingPersonIds = existingPersons.map(p => p.personId);

    // 过滤掉已存在的人员
    const newPersons = persons.filter(p => !existingPersonIds.includes(p.personId));

    if (newPersons.length === 0) {
      return { success: true, message: '所有人员都已在此订单中', addedCount: 0 };
    }

    // 使用事务添加新人员
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      // 创建订单人员关联
      const orderPersons = newPersons.map(person => {
        return queryRunner.manager.create(OrderPerson, {
          orderId: orderId,
          personId: person.personId,
          joinDate: person.joinDate,
          workStatus: WorkStatus.NOT_WORKING,
          salaryDetail: person.salaryDetail,
        });
      });

      await queryRunner.manager.save(orderPersons);

      await queryRunner.commitTransaction();

      return {
        success: true,
        message: `成功添加 ${newPersons.length} 个人员到订单`,
        addedCount: newPersons.length
      };
    } catch (error) {
      await queryRunner.rollbackTransaction();
      throw error;
    } finally {
      await queryRunner.release();
    }
  }

  /**
   * 验证文件ID是否存在
   */
  async validateFileId(fileId: number): Promise<boolean> {
    try {
      const file = await this.fileRepository.findOne({ where: { id: fileId } });
      return !!file;
    } catch (error) {
      console.error('验证文件ID失败:', error);
      return false;
    }
  }

  /**
   * 创建订单人员资产 - 自定义业务方法
   */
  async createOrderPersonAsset(data: {
    orderId: number;
    personId: number;
    assetType: AssetType;
    assetFileType: AssetFileType;
    fileId: number;
    relatedTime?: Date;
  }): Promise<OrderPersonAsset> {
    // 验证文件ID是否存在
    const fileExists = await this.validateFileId(data.fileId);
    if (!fileExists) {
      throw new Error('文件不存在');
    }

    // 验证订单和人员关联是否存在
    const orderPerson = await this.orderPersonRepository.findOne({
      where: { orderId: data.orderId, personId: data.personId }
    });

    if (!orderPerson) {
      throw new Error(`人员ID ${data.personId} 不在订单ID ${data.orderId} 中`);
    }

    // 创建资产记录
    const asset = new OrderPersonAsset({
      orderId: data.orderId,
      personId: data.personId,
      assetType: data.assetType,
      assetFileType: data.assetFileType,
      fileId: data.fileId,
      relatedTime: data.relatedTime || new Date()
    });

    return await this.orderPersonAssetRepository.save(asset);
  }

  /**
   * 查询订单人员资产 - 自定义业务方法
   */
  async queryOrderPersonAsset(query: {
    orderId?: number;
    personId?: number;
    assetType?: string;
    assetFileType?: string;
    page?: number;
    limit?: number;
  }): Promise<{ data: OrderPersonAsset[]; total: number }> {
    const {
      orderId,
      personId,
      assetType,
      assetFileType,
      page = 1,
      limit = 10
    } = query;

    const queryBuilder = this.orderPersonAssetRepository.createQueryBuilder('asset');

    // 构建查询条件
    if (orderId) {
      queryBuilder.andWhere('asset.orderId = :orderId', { orderId });
    }
    if (personId) {
      queryBuilder.andWhere('asset.personId = :personId', { personId });
    }
    if (assetType) {
      queryBuilder.andWhere('asset.assetType = :assetType', { assetType });
    }
    if (assetFileType) {
      queryBuilder.andWhere('asset.assetFileType = :assetFileType', { assetFileType });
    }

    // 获取总数
    const total = await queryBuilder.getCount();

    // 获取数据，加载文件关系
    const data = await queryBuilder
      .leftJoinAndSelect('asset.file', 'file')
      .skip((page - 1) * limit)
      .take(limit)
      .orderBy('asset.updateTime', 'DESC')
      .getMany();

    return { data, total };
  }

  /**
   * 删除订单人员资产 - 自定义业务方法
   */
  async deleteOrderPersonAsset(id: number): Promise<{ success: boolean; message: string }> {
    const asset = await this.orderPersonAssetRepository.findOne({
      where: { id }
    });

    if (!asset) {
      throw new Error(`资产ID ${id} 不存在`);
    }

    await this.orderPersonAssetRepository.delete({ id });

    return {
      success: true,
      message: `成功删除资产ID ${id}`
    };
  }

  /**
   * 更新订单人员工作状态 - 自定义业务方法
   */
  async updatePersonWorkStatus(orderId: number, personId: number, workStatus: WorkStatus): Promise<{ success: boolean; message: string }> {
    // 验证订单是否存在
    const order = await this.repository.findOne({
      where: { id: orderId }
    });

    if (!order) {
      throw new Error(`订单ID ${orderId} 不存在`);
    }

    // 验证工作状态是否有效
    if (!Object.values(WorkStatus).includes(workStatus)) {
      throw new Error('工作状态无效');
    }

    // 查找订单人员关联
    const orderPerson = await this.orderPersonRepository.findOne({
      where: { orderId, personId }
    });

    if (!orderPerson) {
      throw new Error(`人员ID ${personId} 不在订单ID ${orderId} 中`);
    }

    // 更新工作状态
    orderPerson.workStatus = workStatus;

    // 根据工作状态设置相关日期
    if (workStatus === WorkStatus.WORKING && !orderPerson.actualStartDate) {
      orderPerson.actualStartDate = new Date();
    } else if (workStatus === WorkStatus.RESIGNED && !orderPerson.leaveDate) {
      orderPerson.leaveDate = new Date();
    }

    await this.orderPersonRepository.save(orderPerson);

    return {
      success: true,
      message: `成功更新人员 ${personId} 的工作状态为 ${workStatus}`
    };
  }

  /**
   * 获取企业打卡视频统计
   * @param companyId 企业ID
   * @returns 打卡视频统计结果
   */
  async getCheckinStatistics(companyId: number): Promise<{
    companyId: number;
    checkinVideoCount: number;
    totalVideos: number;
  }> {
    // 统计打卡视频数量（asset_type = 'checkin_video'）
    const checkinVideoCount = await this.orderPersonAssetRepository
      .createQueryBuilder('asset')
      .innerJoin('asset.order', 'order') // 关联employment_order表
      .where('order.companyId = :companyId', { companyId })
      .andWhere('asset.assetType = :assetType', { assetType: AssetType.CHECKIN_VIDEO })
      .getCount();

    // 统计总视频数量
    const totalVideos = await this.orderPersonAssetRepository
      .createQueryBuilder('asset')
      .innerJoin('asset.order', 'order')
      .where('order.companyId = :companyId', { companyId })
      .andWhere('asset.assetFileType = :fileType', { fileType: 'video' })
      .getCount();

    return {
      companyId,
      checkinVideoCount,
      totalVideos
    };
  }

  /**
   * 获取企业视频分类统计
   * @param companyId 企业ID
   * @param assetType 可选的视频类型过滤
   * @returns 视频分类统计结果
   */
  async getVideoStatistics(companyId: number, assetType?: string): Promise<{
    companyId: number;
    stats: Array<{ assetType: AssetType; count: number; percentage: number }>;
    total: number;
  }> {
    // 构建基础查询
    const queryBuilder = this.orderPersonAssetRepository
      .createQueryBuilder('asset')
      .innerJoin('asset.order', 'order')
      .where('order.companyId = :companyId', { companyId })
      .andWhere('asset.assetFileType = :fileType', { fileType: 'video' });

    // 如果指定了视频类型，则过滤
    if (assetType) {
      queryBuilder.andWhere('asset.assetType = :assetType', { assetType });
    }

    // 按视频类型分组统计
    const statsQuery = queryBuilder
      .select('asset.assetType', 'assetType')
      .addSelect('COUNT(asset.id)', 'count')
      .groupBy('asset.assetType');

    const rawStats = await statsQuery.getRawMany();

    // 计算总数
    const total = rawStats.reduce((sum, item) => sum + parseInt(item.count), 0);

    // 格式化统计结果，计算百分比
    const stats = rawStats.map(item => ({
      assetType: item.assetType as AssetType,
      count: parseInt(item.count),
      percentage: total > 0 ? (parseInt(item.count) / total) * 100 : 0
    }));

    return {
      companyId,
      stats,
      total
    };
  }

  /**
   * 获取企业维度订单查询
   * @param companyId 企业ID（从认证用户获取，优先使用）
   * @param filters 查询过滤器
   * @returns 订单列表
   */
  async getCompanyOrders(
    companyId: number,
    filters: {
      orderName?: string;
      orderStatus?: OrderStatus;
      startDate?: string;
      endDate?: string;
      page?: number;
      limit?: number;
      sortBy?: 'createTime' | 'updateTime' | 'orderName';
      sortOrder?: 'ASC' | 'DESC';
    }
  ): Promise<{ data: any[]; total: number }> {
    const {
      orderName,
      orderStatus,
      startDate,
      endDate,
      page = 1,
      limit = 10,
      sortBy = 'createTime',
      sortOrder = 'DESC'
    } = filters;

    const queryBuilder = this.repository.createQueryBuilder('order');

    // 企业数据隔离：必须包含company_id条件
    queryBuilder.andWhere('order.companyId = :companyId', { companyId });

    // 构建查询条件
    if (orderName) {
      queryBuilder.andWhere('order.orderName LIKE :orderName', { orderName: `%${orderName}%` });
    }
    if (orderStatus) {
      queryBuilder.andWhere('order.orderStatus = :orderStatus', { orderStatus });
    }
    // 日期范围查询 - 基于createTime字段
    if (startDate) {
      queryBuilder.andWhere('order.createTime >= :startDate', { startDate: `${startDate}T00:00:00Z` });
    }
    if (endDate) {
      queryBuilder.andWhere('order.createTime <= :endDate', { endDate: `${endDate}T23:59:59Z` });
    }

    // 获取总数
    const total = await queryBuilder.getCount();

    // 应用排序
    const orderByField = sortBy === 'orderName' ? 'order.orderName' : `order.${sortBy}`;
    queryBuilder.orderBy(orderByField, sortOrder);

    // 获取数据
    const data = await queryBuilder
      .skip((page - 1) * limit)
      .take(limit)
      .getMany();

    // 获取每个订单的人员数量
    const orderIds = data.map(order => order.id);
    let personCounts: Array<{ orderId: number; count: number }> = [];

    if (orderIds.length > 0) {
      const personCountQuery = await this.orderPersonRepository
        .createQueryBuilder('orderPerson')
        .select('orderPerson.orderId', 'orderId')
        .addSelect('COUNT(orderPerson.id)', 'count')
        .where('orderPerson.orderId IN (:...orderIds)', { orderIds })
        .groupBy('orderPerson.orderId')
        .getRawMany();

      personCounts = personCountQuery.map(item => ({
        orderId: item.orderId,
        count: parseInt(item.count)
      }));
    }

    // 格式化返回数据
    const formattedData = data.map(order => {
      const personCount = personCounts.find(pc => pc.orderId === order.id)?.count || 0;
      return {
        id: order.id,
        orderName: order.orderName,
        platformId: order.platformId,
        companyId: order.companyId,
        channelId: order.channelId,
        expectedStartDate: order.expectedStartDate,
        actualStartDate: order.actualStartDate,
        actualEndDate: order.actualEndDate,
        orderStatus: order.orderStatus,
        workStatus: order.workStatus,
        createTime: order.createTime,
        updateTime: order.updateTime,
        personCount
      };
    });

    return { data: formattedData, total };
  }

  /**
   * 获取企业维度视频查询
   * @param companyId 企业ID（从认证用户获取，优先使用）
   * @param filters 查询过滤器
   * @returns 视频列表
   */
  async getCompanyVideos(
    companyId: number,
    filters: {
      assetType?: AssetType;
      page?: number;
      pageSize?: number;
      sortBy?: 'relatedTime' | 'createTime' | 'updateTime';
      sortOrder?: 'ASC' | 'DESC';
    }
  ): Promise<{ data: any[]; total: number }> {
    const {
      assetType,
      page = 1,
      pageSize = 10,
      sortBy = 'relatedTime',
      sortOrder = 'DESC'
    } = filters;

    const queryBuilder = this.orderPersonAssetRepository.createQueryBuilder('asset');

    // 企业数据隔离：必须通过employment_order表关联过滤company_id
    queryBuilder
      .innerJoin('asset.order', 'order') // 关联employment_order表
      .where('order.companyId = :companyId', { companyId })
      .andWhere('asset.assetFileType = :fileType', { fileType: 'video' }); // 只查询视频文件

    // 视频类型过滤
    if (assetType) {
      queryBuilder.andWhere('asset.assetType = :assetType', { assetType });
    }

    // 获取总数
    const total = await queryBuilder.getCount();

    // 应用排序
    const orderByField = sortBy === 'relatedTime' ? 'asset.relatedTime' : `asset.${sortBy}`;
    queryBuilder.orderBy(orderByField, sortOrder);

    // 获取数据，加载文件关系
    const data = await queryBuilder
      .leftJoinAndSelect('asset.file', 'file')
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getMany();

    // 格式化返回数据，确保包含文件详情
    const formattedData = data.map(asset => ({
      id: asset.id,
      orderId: asset.orderId,
      personId: asset.personId,
      assetType: asset.assetType,
      assetFileType: asset.assetFileType,
      fileId: asset.fileId,
      file: asset.file ? {
        id: asset.file.id,
        name: asset.file.name,
        type: asset.file.type,
        size: asset.file.size,
        path: asset.file.path,
        fullUrl: asset.file.fullUrl,
        description: asset.file.description,
        uploadTime: asset.file.uploadTime
      } : undefined,
      relatedTime: asset.relatedTime,
      createTime: asset.createTime,
      updateTime: asset.updateTime
    }));

    return { data: formattedData, total };
  }

  /**
   * 批量下载视频文件
   * @param companyId 企业ID（从认证用户获取，优先使用）
   * @param filters 批量下载过滤器
   * @returns 批量下载结果（文件URL列表）
   */
  async batchDownloadVideos(
    companyId: number,
    filters: {
      downloadScope: 'company' | 'person';
      personId?: number;
      assetTypes?: string[];
      fileIds?: number[];
    }
  ): Promise<{ success: boolean; message: string; files: any[]; totalFiles: number }> {
    const { downloadScope, personId, assetTypes, fileIds } = filters;

    // 构建查询条件
    const queryBuilder = this.orderPersonAssetRepository.createQueryBuilder('asset');

    // 企业数据隔离：必须通过employment_order表关联过滤company_id
    queryBuilder
      .innerJoin('asset.order', 'order')
      .where('order.companyId = :companyId', { companyId })
      .andWhere('asset.assetFileType = :fileType', { fileType: 'video' }); // 只查询视频文件

    // 根据下载范围添加额外过滤条件
    if (downloadScope === 'person') {
      if (!personId) {
        throw new Error('个人维度下载需要指定personId');
      }
      queryBuilder.andWhere('asset.personId = :personId', { personId });
    }

    // 视频类型过滤
    if (assetTypes && assetTypes.length > 0) {
      queryBuilder.andWhere('asset.assetType IN (:...assetTypes)', { assetTypes });
    }

    // 文件ID过滤（如果指定了具体文件）
    if (fileIds && fileIds.length > 0) {
      queryBuilder.andWhere('asset.fileId IN (:...fileIds)', { fileIds });
    }

    // 获取视频资产记录，加载文件关系
    const assets = await queryBuilder
      .leftJoinAndSelect('asset.file', 'file')
      .orderBy('asset.relatedTime', 'DESC')
      .getMany();

    if (assets.length === 0) {
      return {
        success: true,
        message: '未找到符合条件的视频文件',
        files: [],
        totalFiles: 0
      };
    }

    // 生成文件URL列表
    const files: any[] = [];
    for (const asset of assets) {
      if (!asset.file) {
        continue; // 跳过没有文件记录的资产
      }

      // 使用file-module的预签名URL功能
      // 注意：这里假设file.fullUrl已经包含了预签名URL，或者需要调用fileService生成
      // 根据现有代码，File实体已经有fullUrl属性，应该可以直接使用
      const fileUrl = asset.file.fullUrl || `文件ID ${asset.file.id} 缺少访问URL`;

      files.push({
        id: asset.file.id,
        name: asset.file.name,
        size: asset.file.size,
        url: fileUrl,
        assetType: asset.assetType,
        orderId: asset.orderId,
        personId: asset.personId,
        relatedTime: asset.relatedTime
      });
    }

    return {
      success: true,
      message: `批量下载成功，共生成 ${files.length} 个文件URL`,
      files,
      totalFiles: files.length
    };
  }

  /**
   * 更新视频审核状态
   * @param assetId 资产ID
   * @param status 审核状态
   * @returns 更新后的视频资产信息
   */
  async updateVideoStatus(assetId: number, status: AssetStatus): Promise<OrderPersonAsset> {
    // 查找视频资产
    const asset = await this.orderPersonAssetRepository.findOne({
      where: { id: assetId },
      relations: ['file']
    });

    if (!asset) {
      throw new Error(`视频资产ID ${assetId} 不存在`);
    }

    // 验证状态值
    if (!Object.values(AssetStatus).includes(status)) {
      throw new Error(`无效的视频审核状态: ${status}`);
    }

    // 更新状态
    asset.status = status;
    await this.orderPersonAssetRepository.save(asset);

    return asset;
  }
}