import { AppDataSource } from '@/server/data-source';
import { AreaEntity, AreaLevel } from './area.entity';
import { DisabledStatus } from '@/share/types';

export class AreaService {
  private areaRepository = AppDataSource.getRepository(AreaEntity);

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

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

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

    return areas;
  }

  /**
   * 获取指定节点的子树
   */
  async getSubTree(areaId: number): Promise<AreaEntity | null> {
    const area = await this.areaRepository.findOne({
      where: {
        id: areaId,
        isDeleted: 0
      },
      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
          },
          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[] = [];

    // 创建映射
    areas.forEach(area => {
      areaMap.set(area.id, area);
    });

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

    return tree;
  }

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

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

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

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

    return path;
  }

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