import { DataSource } from 'typeorm';
import { AreaEntity, AreaLevel } from './area.entity';
import { DisabledStatus } from '@d8d/shared-types';

export class AreaService {
  private areaRepository;

  constructor(dataSource: DataSource) {
    this.areaRepository = dataSource.getRepository(AreaEntity);
  }

  /**
   * 获取完整的省市区树形结构
   */
  async getAreaTree(): Promise<AreaEntity[]> {
    const areas = await this.areaRepository.find({
      where: { isDeleted: 0 },
      order: {
        id: 'ASC',
        level: 'ASC',
        name: 'ASC',
      }
    });

    // 构建树形结构
    return this.buildTree(areas);
  }

  /**
   * 根据层级获取树形结构
   */
  async getAreaTreeByLevel(level: AreaLevel): Promise<AreaEntity[]> {
    const areas = await this.areaRepository.find({
      where: {
        level,
        isDeleted: 0,
        isDisabled: DisabledStatus.ENABLED
      },
      relations: ['children'],
      order: {
        id: 'ASC',
        level: 'ASC',
        name: 'ASC'
      }
    });

    return areas;
  }

  /**
   * 获取指定节点的子树
   */
  async getSubTree(areaId: number): Promise<AreaEntity | null> {
    const area = await this.areaRepository.findOne({
      where: {
        id: areaId,
        isDeleted: 0,
        isDisabled: DisabledStatus.ENABLED
      },
      relations: ['children'],
    });

    if (!area) return null;

    // 递归加载所有子节点
    await this.loadChildrenRecursively(area);
    return area;
  }

  /**
   * 递归加载所有子节点
   */
  private async loadChildrenRecursively(area: AreaEntity): Promise<void> {
    if (area.children && area.children.length > 0) {
      for (const child of area.children) {
        const fullChild = await this.areaRepository.findOne({
          where: {
            id: child.id,
            isDeleted: 0,
            isDisabled: DisabledStatus.ENABLED
          },
          relations: ['children'],
        });

        if (fullChild) {
          child.children = fullChild.children;
          await this.loadChildrenRecursively(child);
        }
      }
    }
  }

  /**
   * 构建树形结构
   */
  private buildTree(areas: AreaEntity[]): AreaEntity[] {
    const areaMap = new Map<number, AreaEntity>();
    const tree: AreaEntity[] = [];

    // 创建映射并初始化children数组
    areas.forEach(area => {
      const node = new AreaEntity({ ...area });
      node.children = [];
      areaMap.set(area.id, node);
    });

    // 构建树形结构
    areas.forEach(area => {
      const node = areaMap.get(area.id)!;
      if (area.parentId === null || area.parentId === 0) {
        tree.push(node);
      } else {
        const parent = areaMap.get(area.parentId);
        if (parent && parent.children) {
          parent.children.push(node);
        }
      }
    });

    return tree;
  }

  /**
   * 获取区域路径（从根节点到当前节点）
   */
  async getAreaPath(areaId: number): Promise<AreaEntity[]> {
    const path: AreaEntity[] = [];
    let currentArea = await this.areaRepository.findOne({
      where: { id: areaId, isDeleted: 0, isDisabled: DisabledStatus.ENABLED }
    });

    while (currentArea) {
      path.unshift(currentArea);

      if (currentArea.parentId === null || currentArea.parentId === 0) {
        break;
      }

      currentArea = await this.areaRepository.findOne({
        where: { id: currentArea.parentId, isDeleted: 0, isDisabled: DisabledStatus.ENABLED }
      });
    }

    return path;
  }

  /**
   * 获取所有启用状态的省市区
   */
  async getEnabledAreas(): Promise<AreaEntity[]> {
    return this.areaRepository.find({
      where: {
        isDeleted: 0,
        isDisabled: DisabledStatus.ENABLED
      },
      order: {
        id: 'ASC',
        level: 'ASC',
        name: 'ASC',
      }
    });
  }
}