import { GenericCrudService } from '@d8d/shared-crud';
import { DataSource, DeepPartial, In } from 'typeorm';
import { GoodsMt } from '../entities/goods.entity.mt';
import { FileMt } from '@d8d/file-module-mt';

export class GoodsServiceMt extends GenericCrudService<GoodsMt> {
  constructor(dataSource: DataSource) {
    super(dataSource, GoodsMt, {
      userTracking: {
        createdByField: 'createdBy',
        updatedByField: 'updatedBy'
      },
      relationFields: {
        slideImageIds: {
          relationName: 'slideImages',
          targetEntity: FileMt
        }
      },
      tenantOptions: {
        enabled: true,
        tenantIdField: 'tenantId'
      }
    });
  }

  /**
   * 重写create方法，处理子商品分类继承
   */
  async create(data: DeepPartial<GoodsMt>, userId?: string | number): Promise<GoodsMt> {
    // 如果是子商品（spuId > 0）且没有指定分类ID，从父商品继承分类信息
    if (data.spuId && data.spuId > 0) {
      // 检查是否缺少分类ID（值为0或未定义）
      const needsCategoryInheritance =
        (!data.categoryId1 || data.categoryId1 === 0) ||
        (!data.categoryId2 || data.categoryId2 === 0) ||
        (!data.categoryId3 || data.categoryId3 === 0);

      if (needsCategoryInheritance) {
        // 获取父商品信息
        const parentGoods = await this.repository.findOne({
          where: { id: data.spuId } as any,
          select: ['categoryId1', 'categoryId2', 'categoryId3', 'goodsType', 'supplierId', 'merchantId']
        });

        if (parentGoods) {
          console.debug('从父商品继承分类信息:', {
            parentId: data.spuId,
            parentCategories: {
              categoryId1: parentGoods.categoryId1,
              categoryId2: parentGoods.categoryId2,
              categoryId3: parentGoods.categoryId3
            },
            childCategories: {
              categoryId1: data.categoryId1,
              categoryId2: data.categoryId2,
              categoryId3: data.categoryId3
            }
          });

          // 继承父商品的分类信息（只有当子商品没有指定或为0时才继承）
          if (!data.categoryId1 || data.categoryId1 === 0) {
            data.categoryId1 = parentGoods.categoryId1;
          }
          if (!data.categoryId2 || data.categoryId2 === 0) {
            data.categoryId2 = parentGoods.categoryId2;
          }
          if (!data.categoryId3 || data.categoryId3 === 0) {
            data.categoryId3 = parentGoods.categoryId3;
          }

          // 可选：继承其他字段（如果子商品没有指定）
          if (!data.goodsType) {
            data.goodsType = parentGoods.goodsType;
          }
          if (!data.supplierId && parentGoods.supplierId) {
            data.supplierId = parentGoods.supplierId;
          }
          if (!data.merchantId && parentGoods.merchantId) {
            data.merchantId = parentGoods.merchantId;
          }

          console.debug('继承后的分类信息:', {
            categoryId1: data.categoryId1,
            categoryId2: data.categoryId2,
            categoryId3: data.categoryId3
          });
        } else {
          console.debug('父商品不存在，无法继承分类信息:', data.spuId);
        }
      }
    }

    // 调用父类的create方法
    return super.create(data, userId);
  }

  /**
   * 重写getById方法，增强父子商品详情支持
   */
  async getById(id: number, relations: string[] = [], userId?: string | number): Promise<GoodsMt | null> {
    // 先调用父类的getById方法获取商品详情
    const goods = await super.getById(id, relations, userId);
    if (!goods) {
      return null;
    }

    // 根据商品类型添加额外的父子商品信息
    if (goods.spuId === 0) {
      // 父商品：获取子商品列表
      const children = await this.repository.find({
        where: { spuId: id, state: 1 } as any,
        relations: ['category1', 'category2', 'category3', 'supplier', 'merchant', 'imageFile', 'slideImages'],
        order: { sort: 'ASC', createdAt: 'ASC' }
      });

      // 将子商品列表添加到返回结果中
      (goods as any).children = children;
      (goods as any).childGoodsIds = children.map(child => child.id);
    } else if (goods.spuId > 0) {
      // 子商品：获取父商品基本信息
      // 添加租户ID过滤，确保父商品与子商品在同一租户下
      const parent = await this.repository.findOne({
        where: { id: goods.spuId, tenantId: goods.tenantId } as any,
        select: ['id', 'name', 'price', 'costPrice', 'stock', 'imageFileId', 'goodsType', 'spuId']
      });

      // 将父商品信息添加到返回结果中
      (goods as any).parent = parent;
    }

    return goods;
  }

  /**
   * 重写getList方法，批量填充父商品的childGoodsIds字段和子商品的parent对象
   */
  async getList(
    page: number = 1,
    pageSize: number = 10,
    keyword?: string,
    searchFields?: string[],
    where?: Partial<GoodsMt>,
    relations: string[] = [],
    order: { [P in keyof GoodsMt]?: 'ASC' | 'DESC' } = {},
    filters?: { [key: string]: any },
    userId?: string | number
  ): Promise<[GoodsMt[], number]> {
    // 1. 先调用父类的getList获取数据
    const [data, total] = await super.getList(
      page, pageSize, keyword, searchFields, where, relations, order, filters, userId
    );

    // 2. 批量查询所有父商品的子商品ID
    const parentGoodsIds = data.filter(goods => goods.spuId === 0).map(goods => goods.id);
    if (parentGoodsIds.length > 0) {
      const childGoodsMap = await this.getChildGoodsIdsByParentIds(parentGoodsIds);

      // 3. 为每个父商品设置childGoodsIds
      data.forEach(goods => {
        if (goods.spuId === 0) {
          (goods as any).childGoodsIds = childGoodsMap.get(goods.id) || [];
        }
      });
    }

    // 4. 批量查询所有子商品的父商品信息
    const childGoodsList = data.filter(goods => goods.spuId > 0);
    if (childGoodsList.length > 0) {
      const parentGoodsMap = await this.getParentGoodsByChildIds(childGoodsList);

      // 5. 为每个子商品设置parent对象
      data.forEach(goods => {
        if (goods.spuId > 0) {
          const parent = parentGoodsMap.get(goods.spuId);
          if (parent) {
            (goods as any).parent = parent;
          }
        }
      });
    }

    return [data, total];
  }

  /**
   * 辅助方法：批量查询父商品的子商品ID
   */
  private async getChildGoodsIdsByParentIds(parentIds: number[]): Promise<Map<number, number[]>> {
    const childGoods = await this.repository.find({
      where: { spuId: In(parentIds), state: 1 } as any,
      select: ['id', 'spuId']
    });

    const map = new Map<number, number[]>();
    childGoods.forEach(child => {
      const parentId = child.spuId;
      if (!map.has(parentId)) {
        map.set(parentId, []);
      }
      map.get(parentId)!.push(child.id);
    });

    return map;
  }

  /**
   * 辅助方法：批量查询子商品的父商品信息
   */
  private async getParentGoodsByChildIds(childGoodsList: GoodsMt[]): Promise<Map<number, any>> {
    // 收集所有父商品ID
    const parentIds = [...new Set(childGoodsList.map(child => child.spuId))];
    if (parentIds.length === 0) {
      return new Map();
    }

    // 假设所有商品在同一租户下（通过查询过滤）
    const tenantId = childGoodsList[0]?.tenantId;
    if (!tenantId) {
      return new Map();
    }

    // 查询父商品信息，选择与ParentGoodsSchema匹配的字段
    const parentGoods = await this.repository.find({
      where: { id: In(parentIds), tenantId } as any,
      select: ['id', 'name', 'price', 'costPrice', 'stock', 'imageFileId', 'goodsType', 'spuId']
    });

    const map = new Map<number, any>();
    parentGoods.forEach(parent => {
      map.set(parent.id, {
        id: parent.id,
        name: parent.name,
        price: parent.price,
        costPrice: parent.costPrice,
        stock: parent.stock,
        imageFileId: parent.imageFileId,
        goodsType: parent.goodsType,
        spuId: parent.spuId // 父商品的spuId总是0
      });
    });

    return map;
  }
}