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

export class UserOrderGoodsMtService extends GenericCrudService<OrderGoodsMt> {
  constructor(dataSource: DataSource) {
    super(dataSource, OrderGoodsMt, {
      userTracking: {
        createdByField: 'createdBy',
        updatedByField: 'updatedBy'
      },
      tenantOptions: { enabled: true, tenantIdField: 'tenantId' }
    });
  }

  /**
   * 获取当前用户的订单商品列表
   */
  async getUserOrderGoodsList(
    page: number = 1,
    pageSize: number = 10,
    keyword?: string,
    userId?: string | number,
    tenantId?: number
  ): Promise<[OrderGoodsMt[], 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 (tenantId) {
      query.andWhere('orderGoods.tenantId = :tenantId', { tenantId });
    }

    // 数据权限过滤：只返回当前用户订单的商品
    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, tenantId?: number): Promise<OrderGoodsMt | null> {
    const orderGoods = await this.repository.findOne({
      where: { id, ...(tenantId && { tenantId }) },
      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<OrderGoodsMt>, userId?: string | number, tenantId?: number): Promise<OrderGoodsMt> {
    // 验证订单是否属于当前用户
    if (userId && data.orderId) {
      const orderRepository = this.dataSource.getRepository('OrderMt');
      const order = await orderRepository.findOne({
        where: { id: data.orderId, ...(tenantId && { tenantId }) },
        select: ['userId']
      });

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

    return this.create(data, userId);
  }

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

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

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

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