import { DataSource } from 'typeorm';
import { OrderGoods } from '../entities/order-goods.entity';
import { GenericCrudService } from '@d8d/shared-crud';

export class UserOrderGoodsService extends GenericCrudService<OrderGoods> {
  constructor(dataSource: DataSource) {
    super(dataSource, OrderGoods, {
      userTracking: {
        createdByField: 'createdBy',
        updatedByField: 'updatedBy'
      }
    });
  }

  /**
   * 获取当前用户的订单商品列表
   */
  async getUserOrderGoodsList(
    page: number = 1,
    pageSize: number = 10,
    keyword?: string,
    userId?: string | number
  ): Promise<[OrderGoods[], number]> {
    const skip = (page - 1) * pageSize;
    const query = this.repository.createQueryBuilder('orderGoods')
      .leftJoinAndSelect('orderGoods.order', 'order')
      .leftJoinAndSelect('orderGoods.goods', 'goods')
      .leftJoinAndSelect('orderGoods.supplier', 'supplier')
      .leftJoinAndSelect('orderGoods.imageFile', 'imageFile');

    // 数据权限过滤：只返回当前用户订单的商品
    if (userId) {
      query.andWhere('order.userId = :userId', { userId });
    }

    // 关键词搜索
    if (keyword) {
      query.andWhere('(orderGoods.orderNo LIKE :keyword OR orderGoods.goodsName LIKE :keyword)', {
        keyword: `%${keyword}%`
      });
    }

    query.skip(skip).take(pageSize).orderBy('orderGoods.id', 'DESC');

    return query.getManyAndCount();
  }

  /**
   * 获取当前用户的订单商品详情
   */
  async getUserOrderGoodsById(id: number, userId?: string | number): Promise<OrderGoods | null> {
    const orderGoods = await this.repository.findOne({
      where: { id },
      relations: ['order', 'goods', 'supplier', 'imageFile']
    });

    if (!orderGoods) {
      return null;
    }

    // 数据权限验证：检查订单是否属于当前用户
    if (userId && orderGoods.order && orderGoods.order.userId !== userId) {
      throw new Error('无权访问该订单商品');
    }

    return orderGoods;
  }

  /**
   * 为当前用户创建订单商品
   */
  async createUserOrderGoods(data: Partial<OrderGoods>, userId?: string | number): Promise<OrderGoods> {
    // 验证订单是否属于当前用户
    if (userId && data.orderId) {
      const orderRepository = this.dataSource.getRepository('Order');
      const order = await orderRepository.findOne({
        where: { id: data.orderId },
        select: ['userId']
      });

      if (!order || order.userId !== userId) {
        throw new Error('无权为该订单创建商品');
      }
    }

    return this.create(data, userId);
  }

  /**
   * 更新当前用户的订单商品
   */
  async updateUserOrderGoods(id: number, data: Partial<OrderGoods>, userId?: string | number): Promise<OrderGoods | null> {
    // 先验证权限
    const existing = await this.getUserOrderGoodsById(id, userId);
    if (!existing) {
      return null;
    }

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

  /**
   * 删除当前用户的订单商品
   */
  async deleteUserOrderGoods(id: number, userId?: string | number): Promise<boolean> {
    // 先验证权限
    const existing = await this.getUserOrderGoodsById(id, userId);
    if (!existing) {
      return false;
    }

    return this.delete(id, userId);
  }
}