import {
  Controller,
  Get,
  Route,
  Security,
  Tags,
  SuccessResponse,
  Response,
  Path,
  Query,
  Post,
  Body,
} from "tsoa";
import { AppDataSource } from "../database/data-source";
import HttpSuccess from "../interfaces/http-success";
import HttpStatusCode from "../interfaces/http-status";
import HttpError from "../interfaces/http-error";
import { In, LessThan, Brackets } from "typeorm";
import { OrgRevision } from "../entities/OrgRevision";
import { OrgRoot } from "../entities/OrgRoot";
import { OrgChild1 } from "../entities/OrgChild1";
import { OrgChild2 } from "../entities/OrgChild2";
import { OrgChild3 } from "../entities/OrgChild3";
import { OrgChild4 } from "../entities/OrgChild4";
import { PosType } from "../entities/PosType";
import { PosLevel } from "../entities/PosLevel";
import { PosMaster } from "../entities/PosMaster";
import { EmployeePosMaster } from "../entities/EmployeePosMaster";
import Extension from "../interfaces/extension";
import { LeaveType } from "../entities/LeaveType";
import HttpStatus from "../interfaces/http-status";
import { Profile } from "../entities/Profile";
import { Position } from "../entities/Position";
import { ProfileEducation } from "../entities/ProfileEducation";
import { ProfileSalary } from "../entities/ProfileSalary";
import { viewRegistryOfficer } from "../entities/view/viewRegistryOfficer";
import { viewRegistryEmployee } from "../entities/view/viewRegistryEmployee";
import { EmployeeTempPosMaster } from "../entities/EmployeeTempPosMaster";
// import { sendWebSocket } from "../services/webSocket";
import { Registry } from "../entities/Registry";
import { RegistryEmployee } from "../entities/RegistryEmployee";
@Route("api/v1/org/report")
@Tags("Report")
@Security("bearerAuth")
@Response(
  HttpStatusCode.INTERNAL_SERVER_ERROR,
  "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง",
)
export class ReportController extends Controller {
  private orgRevisionRepository = AppDataSource.getRepository(OrgRevision);
  private orgRootRepository = AppDataSource.getRepository(OrgRoot);
  private child1Repository = AppDataSource.getRepository(OrgChild1);
  private child2Repository = AppDataSource.getRepository(OrgChild2);
  private child3Repository = AppDataSource.getRepository(OrgChild3);
  private child4Repository = AppDataSource.getRepository(OrgChild4);
  private posTypepository = AppDataSource.getRepository(PosType);
  private posLevelRepository = AppDataSource.getRepository(PosLevel);
  private posMasterRepository = AppDataSource.getRepository(PosMaster);
  private profileRepository = AppDataSource.getRepository(Profile);
  private empPosMasterRepository = AppDataSource.getRepository(EmployeePosMaster);
  private empTempPosMasterRepository = AppDataSource.getRepository(EmployeeTempPosMaster);
  private positionRepository = AppDataSource.getRepository(Position);
  private profileEducationRepository = AppDataSource.getRepository(ProfileEducation);
  private profileSalaryRepository = AppDataSource.getRepository(ProfileSalary);

  /**
   * API รายงานสถิติข้อมูลข้าราชการ กทม. สามัญ
   *
   * @summary รายงานสถิติข้อมูลข้าราชการ กทม. สามัญ
   *
   */
  @Get("registry-officer")
  async registryOfficer(
    @Query() node?: number,
    @Query() nodeId?: string,
    @Query() posType?: string,
    @Query() posLevel?: string,
    @Query() position?: string,
    @Query() positionExecutive?: string,
    @Query() gender?: string,
    @Query() status?: string,
    @Query() education?: string,
    @Query() dateStart?: Date,
    @Query() dateEnd?: Date,
    @Query() ageMin?: number,
    @Query() ageMax?: number,
    @Query() isProbation?: boolean,
    @Query() isRetire?: boolean,
    @Query() isRetireLaw?: boolean,
    @Query() isCurrent?: boolean,
    @Query() retireType?: string,
    @Query() tenureType?: string,
    @Query() tenureMin?: number,
    @Query() tenureMax?: number,
    @Query() positionArea?: string,
    @Query() educationLevel?: string,
    @Query() field?: string,
    @Query() sortBy: string = "posMasterNo",
    @Query() sort: "ASC" | "DESC" = "ASC",
  ) {
    const _null: any = null;
    if (!dateStart) {
      dateStart = _null;
    }
    if (!dateEnd) {
      dateEnd = _null;
    }
    if (ageMin && (ageMin < 18 || ageMin > 60)) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ageMin must be between 18 and 60");
    }
    if (ageMax && (ageMax < 18 || ageMax > 60)) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ageMax must be between 18 and 60");
    }
    if (ageMin && ageMax && ageMin > ageMax) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ageMin cannot be greater than ageMax");
    }
    ageMin = ageMin ?? 18;
    ageMax = ageMax ?? 60;

    tenureMin = tenureMin ?? 0;
    tenureMax = tenureMax ?? 20;

    let nodeCondition = "1=1";
    if (node === 0 && nodeId) {
      nodeCondition = "registryOfficer.orgRootId = :nodeId";
    } else if (node === 1 && nodeId) {
      nodeCondition = "registryOfficer.orgChild1Id = :nodeId";
    } else if (node === 2 && nodeId) {
      nodeCondition = "registryOfficer.orgChild2Id = :nodeId";
    } else if (node === 3 && nodeId) {
      nodeCondition = "registryOfficer.orgChild3Id = :nodeId";
    } else if (node === 4 && nodeId) {
      nodeCondition = "registryOfficer.orgChild4Id = :nodeId";
    }
    let dateAppointCondition = "1=1";
    if (dateStart && dateEnd) {
      dateAppointCondition =
        "DATE(registryOfficer.dateAppoint) >= :startDateAppoint AND DATE(registryOfficer.dateAppoint) <= :endDateAppoint";
    } else if (dateStart) {
      dateAppointCondition = "DATE(registryOfficer.dateAppoint) >= :startDateAppoint";
    } else if (dateEnd) {
      dateAppointCondition = "DATE(registryOfficer.dateAppoint) <= :endDateAppoint";
    }

    const IsLeavecondition = ["registryOfficer.isLeave = :isLeave"];
    const parameters: any = { isLeave: isRetire };
    if (retireType && retireType.trim() !== "") {
      IsLeavecondition.push("registryOfficer.leaveType = :retireType");
      parameters.retireType = retireType;
    }

    let retireLawCondition = "1=1";
    if (isRetireLaw) {
      retireLawCondition =
        "DATE(registryOfficer.dateRetireLaw) >= :startDateRetireLaw AND DATE(registryOfficer.dateRetireLaw) <= :endDateRetireLaw";
    }

    let tenureTypeCondition = "1=1";
    if (tenureType != "" && tenureType == "position") {
      tenureTypeCondition = "registryOfficer.Years BETWEEN :tenureMin AND :tenureMax";
    } else if (tenureType != "" && tenureType == "level") {
      tenureTypeCondition = "registryOfficer.levelYears BETWEEN :tenureMin AND :tenureMax";
    } else if (tenureType != "" && tenureType == "posExecutive") {
      tenureTypeCondition = "registryOfficer.posExecutiveYears BETWEEN :tenureMin AND :tenureMax";
    }
    // ดึงผ่าน Table แทน View
    // const [lists, total] = await AppDataSource.getRepository(viewRegistryOfficer)
    const [lists, total] = await AppDataSource.getRepository(Registry)
      .createQueryBuilder("registryOfficer")
      .where(nodeCondition, {
        nodeId: nodeId,
      })
      .andWhere(tenureTypeCondition, {
        tenureMin: tenureMin,
        tenureMax: tenureMax,
      })
      .andWhere("registryOfficer.age BETWEEN :ageMin AND :ageMax", {
        ageMin,
        ageMax,
      })
      .andWhere(dateAppointCondition, {
        startDateAppoint: dateStart?.toISOString().split("T")[0],
        endDateAppoint: dateEnd?.toISOString().split("T")[0],
      })
      .andWhere(retireLawCondition, {
        startDateRetireLaw: new Date(new Date().getFullYear() - 1, 9, 1, 0, 0, 0, 0)
          ?.toISOString()
          .split("T")[0],
        endDateRetireLaw: new Date(new Date().getFullYear(), 8, 30, 23, 59, 59, 999)
          .toISOString()
          .split("T")[0],
      })
      .andWhere("registryOfficer.isProbation = :isProbation", {
        isProbation: isProbation,
      })
      .andWhere(IsLeavecondition.join(" AND "), parameters)
      .andWhere(
        posType != null && posType != "" ? "registryOfficer.posTypeName = :posTypeName" : "1=1",
        {
          posTypeName: `${posType}`,
        },
      )
      .andWhere(
        posLevel != null && posLevel != "" ? "registryOfficer.posLevelName = :posLevelName" : "1=1",
        {
          posLevelName: `${posLevel}`,
        },
      )
      .andWhere(
        position != null && position != "" ? "registryOfficer.position = :position" : "1=1",
        {
          position: `${position}`,
        },
      )
      .andWhere(
        positionExecutive != null && positionExecutive != ""
          ? "registryOfficer.posExecutiveName = :posExecutiveName"
          : "1=1",
        {
          posExecutiveName: `${positionExecutive}`,
        },
      )
      .andWhere(gender != null && gender != "" ? "registryOfficer.gender = :gender" : "1=1", {
        gender: `${gender}`,
      })
      .andWhere(
        status != null && status != "" ? "registryOfficer.relationship = :relationship" : "1=1",
        {
          relationship: `${status}`,
        },
      )
      .andWhere(
        positionArea != null && positionArea != ""
          ? "registryOfficer.positionArea LIKE :positionArea"
          : "1=1",
        {
          positionArea: `%${positionArea}%`,
        },
      )
      .andWhere(
        education != null && education != "" ? "registryOfficer.degrees LIKE :degrees" : "1=1",
        {
          degrees: `%${education}%`,
        },
      )
      .andWhere(
        educationLevel != null && educationLevel != ""
          ? "registryOfficer.educationLevels LIKE :educationLevels"
          : "1=1",
        {
          educationLevels: `%${educationLevel}%`,
        },
      )
      .andWhere(field != null && field != "" ? "registryOfficer.fields LIKE :fields" : "1=1", {
        fields: `%${field}%`,
      })
      .andWhere(
        isCurrent === undefined || isCurrent === null
          ? "1=1"
          : isCurrent === true
            ? "registryOfficer.posMasterNo IS NOT NULL"
            : "registryOfficer.posMasterNo IS NULL",
      )
      .orderBy(`registryOfficer.${sortBy}`, sort)
      .getManyAndCount();

    const mapData = [];
    for await (const x of lists) {
      let _educations: any = [];
      if (!education && !educationLevel && !field) {
        _educations =
          Array.isArray(x.Educations) && x.Educations != null
            ? (x.Educations as any[]).filter((i: any) => i.isEducation == true)
            : [];
        if (_educations.length == 0) {
          _educations =
            Array.isArray(x.Educations) && x.Educations != null
              ? (x.Educations as any[]).filter((i: any) => i.isHigh == true)
              : [];
        }
      } else {
        _educations =
          Array.isArray(x.Educations) && x.Educations != null
            ? (x.Educations as any[]).filter(
                (i: any) =>
                  // i.degree === education ||
                  // i.educationLevel === educationLevel ||
                  // i.field === field
                  (education ? i.degree?.toString().includes(education) : false) ||
                  (educationLevel
                    ? i.educationLevel?.toString().includes(educationLevel)
                    : false) ||
                  (field ? i.field?.toString().includes(field) : false),
              )
            : [];
      }
      mapData.push({
        profileId: x.profileId,
        citizenId: x.citizenId,
        prefix: x.prefix,
        firstName: x.firstName,
        lastName: x.lastName,
        isProbation: x.isProbation,
        isLeave: x.isLeave,
        isRetirement: x.isRetirement,
        leaveType: x.leaveType,
        posMasterNo: x.posMasterNo,
        orgRootId: x.orgRootId,
        orgChild1Id: x.orgChild1Id,
        orgChild2Id: x.orgChild2Id,
        orgChild3Id: x.orgChild3Id,
        orgChild4Id: x.orgChild4Id,
        orgRootName: x.orgRootName,
        orgChild1Name: x.orgChild1Name,
        orgChild2Name: x.orgChild2Name,
        orgChild3Name: x.orgChild3Name,
        orgChild4Name: x.orgChild4Name,
        org: x.org,
        searchShortName: x.searchShortName,
        posExecutiveName: x.posExecutiveName,
        position: x.position,
        positionArea: x.positionArea,
        posTypeName: x.posTypeName,
        posLevelName: x.posLevelName,
        gender: x.gender,
        relationship: x.relationship,
        dateAppoint: x.dateAppoint,
        dateRetire: x.dateRetire,
        dateRetireLaw: x.dateRetireLaw,
        birthdate: x.birthdate,
        Educations: _educations,
        age: x.age,
        currentPosition: null,
        lengthPosition: null,
        positionDate: {
          Years: x.Years ? x.Years : 0,
          Months: x.Months ? x.Months : 0,
          Days: x.Days ? x.Days : 0,
        },
        levelDate: {
          Years: x.levelYears ? x.levelYears : 0,
          Months: x.levelMonths ? x.levelMonths : 0,
          Days: x.levelDays ? x.levelDays : 0,
        },
        posExecutiveDate: {
          Years: x.posExecutiveYears ? x.posExecutiveYears : 0,
          Months: x.posExecutiveMonths ? x.posExecutiveMonths : 0,
          Days: x.posExecutiveDays ? x.posExecutiveDays : 0,
        },
      });
    }
    return new HttpSuccess({
      data: mapData,
      total: total,
    });
  }

  /**
   * API รายงานสถิติข้อมูลลูกจ้างประจำ กทม.
   *
   * @summary รายงานสถิติข้อมูลลูกจ้างประจำ กทม.
   *
   */
  @Get("registry-emp")
  async registryEmployee(
    @Query() node?: number,
    @Query() nodeId?: string,
    @Query() posType?: string,
    @Query() posLevel?: string,
    @Query() position?: string,
    @Query() gender?: string,
    @Query() status?: string,
    @Query() education?: string,
    @Query() dateStart?: Date,
    @Query() dateEnd?: Date,
    @Query() isProbation?: boolean,
    @Query() isRetire?: boolean,
    @Query() isRetireLaw?: boolean,
    @Query() isCurrent?: boolean,
    @Query() retireType?: string,
    @Query() ageMin?: number,
    @Query() ageMax?: number,
    @Query() tenureType?: string,
    @Query() tenureMin?: number,
    @Query() tenureMax?: number,
    @Query() educationLevel?: string,
    @Query() field?: string,
    @Query() sortBy: string = "posMasterNo",
    @Query() sort: "ASC" | "DESC" = "ASC",
  ) {
    const _null: any = null;
    if (!dateStart) {
      dateStart = _null;
    }
    if (!dateEnd) {
      dateEnd = _null;
    }
    if (ageMin && (ageMin < 18 || ageMin > 60)) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ageMin must be between 18 and 60");
    }
    if (ageMax && (ageMax < 18 || ageMax > 60)) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ageMax must be between 18 and 60");
    }
    if (ageMin && ageMax && ageMin > ageMax) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ageMin cannot be greater than ageMax");
    }
    ageMin = ageMin ?? 18;
    ageMax = ageMax ?? 60;

    tenureMin = tenureMin ?? 0;
    tenureMax = tenureMax ?? 20;

    let nodeCondition = "1=1";
    if (node === 0 && nodeId) {
      nodeCondition = "registryEmployee.orgRootId = :nodeId";
    } else if (node === 1 && nodeId) {
      nodeCondition = "registryEmployee.orgChild1Id = :nodeId";
    } else if (node === 2 && nodeId) {
      nodeCondition = "registryEmployee.orgChild2Id = :nodeId";
    } else if (node === 3 && nodeId) {
      nodeCondition = "registryEmployee.orgChild3Id = :nodeId";
    } else if (node === 4 && nodeId) {
      nodeCondition = "registryEmployee.orgChild4Id = :nodeId";
    }
    let dateAppointCondition = "1=1";
    if (dateStart && dateEnd) {
      dateAppointCondition =
        "DATE(registryEmployee.dateAppoint) >= :startDateAppoint AND DATE(registryEmployee.dateAppoint) <= :endDateAppoint";
    } else if (dateStart) {
      dateAppointCondition = "DATE(registryEmployee.dateAppoint) >= :startDateAppoint";
    } else if (dateEnd) {
      dateAppointCondition = "DATE(registryEmployee.dateAppoint) <= :endDateAppoint";
    }

    const IsLeavecondition = ["registryEmployee.isLeave = :isLeave"];
    const parameters: any = { isLeave: isRetire };
    if (retireType && retireType.trim() !== "") {
      IsLeavecondition.push("registryEmployee.leaveType = :retireType");
      parameters.retireType = retireType;
    }

    let tenureTypeCondition = "1=1";
    if (tenureType != "" && tenureType == "position") {
      tenureTypeCondition = "registryEmployee.Years BETWEEN :tenureMin AND :tenureMax";
    } else if (tenureType != "" && tenureType == "level") {
      tenureTypeCondition = "registryEmployee.levelYears BETWEEN :tenureMin AND :tenureMax";
    }

    let retireLawCondition = "1=1";
    if (isRetireLaw) {
      retireLawCondition =
        "DATE(registryEmployee.dateRetireLaw) >= :startDateRetireLaw AND DATE(registryEmployee.dateRetireLaw) <= :endDateRetireLaw";
    }
    // ดึงผ่าน Table แทน View
    // const [lists, total] = await AppDataSource.getRepository(viewRegistryEmployee)
    const [lists, total] = await AppDataSource.getRepository(RegistryEmployee)
      .createQueryBuilder("registryEmployee")
      .where(nodeCondition, {
        nodeId: nodeId,
      })
      .andWhere(tenureTypeCondition, {
        tenureMin: tenureMin,
        tenureMax: tenureMax,
      })
      .andWhere("registryEmployee.age BETWEEN :ageMin AND :ageMax", {
        ageMin,
        ageMax,
      })
      .andWhere(dateAppointCondition, {
        startDateAppoint: dateStart?.toISOString().split("T")[0],
        endDateAppoint: dateEnd?.toISOString().split("T")[0],
      })
      .andWhere(retireLawCondition, {
        startDateRetireLaw: new Date(new Date().getFullYear() - 1, 9, 1, 0, 0, 0, 0)
          ?.toISOString()
          .split("T")[0],
        endDateRetireLaw: new Date(new Date().getFullYear(), 8, 30, 23, 59, 59, 999)
          .toISOString()
          .split("T")[0],
      })
      .andWhere("registryEmployee.isProbation = :isProbation", {
        isProbation: isProbation,
      })
      .andWhere(IsLeavecondition.join(" AND "), parameters)
      .andWhere("registryEmployee.employeeClass = 'PERM'")
      .andWhere(
        posType != null && posType != "" ? "registryEmployee.posTypeName LIKE :posTypeName" : "1=1",
        {
          posTypeName: `${posType}`,
        },
      )
      .andWhere(
        posLevel != null && posLevel != ""
          ? "registryEmployee.posLevelName LIKE :posLevelName"
          : "1=1",
        {
          posLevelName: `${posLevel}`,
        },
      )
      .andWhere(
        position != null && position != "" ? "registryEmployee.position LIKE :position" : "1=1",
        {
          position: `${position}`,
        },
      )
      .andWhere(gender != null && gender != "" ? "registryEmployee.gender LIKE :gender" : "1=1", {
        gender: `${gender}`,
      })
      .andWhere(
        status != null && status != "" ? "registryEmployee.relationship LIKE :relationship" : "1=1",
        {
          relationship: `${status}`,
        },
      )
      .andWhere(
        education != null && education != "" ? "registryEmployee.degrees LIKE :degrees" : "1=1",
        {
          degrees: `%${education}%`,
        },
      )
      .andWhere(
        educationLevel != null && educationLevel != ""
          ? "registryEmployee.educationLevels LIKE :educationLevels"
          : "1=1",
        {
          educationLevels: `%${educationLevel}%`,
        },
      )
      .andWhere(field != null && field != "" ? "registryEmployee.fields LIKE :fields" : "1=1", {
        fields: `%${field}%`,
      })
      .andWhere(
        isCurrent === undefined || isCurrent === null
          ? "1=1"
          : isCurrent === true
            ? "registryEmployee.posMasterNo IS NOT NULL"
            : "registryEmployee.posMasterNo IS NULL",
      )
      .orderBy(`registryEmployee.${sortBy}`, sort)
      .getManyAndCount();

    const mapData = [];
    for await (const x of lists) {
      let _educations: any = [];
      if (!education && !educationLevel && !field) {
        _educations =
          Array.isArray(x.Educations) && x.Educations != null
            ? (x.Educations as any[]).filter((i: any) => i.isEducation == true)
            : [];
        if (_educations.length == 0) {
          _educations =
            Array.isArray(x.Educations) && x.Educations != null
              ? (x.Educations as any[]).filter((i: any) => i.isHigh == true)
              : [];
        }
      } else {
        _educations =
          Array.isArray(x.Educations) && x.Educations != null
            ? (x.Educations as any[]).filter(
                (i: any) =>
                  (education ? i.degree?.toString().includes(education) : false) ||
                  (educationLevel
                    ? i.educationLevel?.toString().includes(educationLevel)
                    : false) ||
                  (field ? i.field?.toString().includes(field) : false),
              )
            : [];
      }
      mapData.push({
        profileId: x.profileEmployeeId,
        citizenId: x.citizenId,
        prefix: x.prefix,
        firstName: x.firstName,
        lastName: x.lastName,
        isProbation: x.isProbation,
        isLeave: x.isLeave,
        isRetirement: x.isRetirement,
        leaveType: x.leaveType,
        posMasterNo: x.posMasterNo,
        orgRootId: x.orgRootId,
        orgChild1Id: x.orgChild1Id,
        orgChild2Id: x.orgChild2Id,
        orgChild3Id: x.orgChild3Id,
        orgChild4Id: x.orgChild4Id,
        orgRootName: x.orgRootName,
        orgChild1Name: x.orgChild1Name,
        orgChild2Name: x.orgChild2Name,
        orgChild3Name: x.orgChild3Name,
        orgChild4Name: x.orgChild4Name,
        org: x.org,
        searchShortName: x.searchShortName,
        position: x.position,
        posTypeName: x.posTypeName,
        posLevelName: x.posLevelName,
        gender: x.gender,
        relationship: x.relationship,
        dateAppoint: x.dateAppoint,
        dateRetire: x.dateRetire,
        dateRetireLaw: x.dateRetireLaw,
        birthdate: x.birthdate,
        Educations: _educations != null ? _educations : [],
        // degree: x.degrees,
        // educationLevel: x.educationLevels,
        // field: x.fields,
        age: x.age,
        currentPosition: null,
        lengthPosition: null,
        positionDate: {
          Years: x.Years ? x.Years : 0,
          Months: x.Months ? x.Months : 0,
          Days: x.Days ? x.Days : 0,
        },
        levelDate: {
          posExecutiveYears: x.levelYears ? x.levelYears : 0,
          posExecutiveMonths: x.levelMonths ? x.levelMonths : 0,
          posExecutiveDays: x.levelDays ? x.levelDays : 0,
        },
      });
    }
    return new HttpSuccess({
      data: mapData,
      total: total,
    });
  }

  /**
   * API Report1
   *
   * @summary Report1
   *
   */
  @Post("report1")
  async NewReport1(
    @Body()
    reqBody: {
      node: number;
      nodeId: string;
    },
  ) {
    let _nodeId: string = reqBody.nodeId ? reqBody.nodeId : "";
    let _node: number = reqBody.node ? reqBody.node : 0;
    if (_nodeId === "" || _node < 0 || _node > 4) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
    }

    let orgName: string = "";
    let data = new Array();
    let no = 1;

    switch (_node) {
      case 0: {
        // ดึงข้อมูล orgRoot ตาม nodeId และลูกทั้งหมด (cascade 0..4)
        const orgRootData = await this.orgRootRepository.find({
          where: { id: _nodeId },
          order: {
            orgRootOrder: "ASC",
            posMasters: {
              posMasterOrder: "ASC",
              posMasterCreatedAt: "ASC",
            },
          },
          relations: [
            "posMasters",
            "posMasters.positions",
            "posMasters.positions.posLevel",
            "posMasters.positions.posType",
            "posMasters.positions.posExecutive",
          ],
        });
        if (!orgRootData || orgRootData.length === 0) {
          throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล orgRoot");
        }
        orgName = orgRootData[0].orgRootName ?? "";

        const orgRootIds = orgRootData.map((r) => r.id) || null;
        const orgChild1Data = await this.child1Repository.find({
          where: { orgRootId: In(orgRootIds) },
          order: {
            orgChild1Order: "ASC",
            posMasters: {
              posMasterOrder: "ASC",
              posMasterCreatedAt: "ASC",
            },
          },
          relations: [
            "posMasters",
            "posMasters.positions",
            "posMasters.positions.posLevel",
            "posMasters.positions.posType",
            "posMasters.positions.posExecutive",
          ],
        });
        const orgChild1Ids = orgChild1Data.map((c) => c.id) || null;
        const orgChild2Data = await this.child2Repository.find({
          where: { orgChild1: In(orgChild1Ids) },
          order: {
            orgChild2Order: "ASC",
            posMasters: {
              posMasterOrder: "ASC",
              posMasterCreatedAt: "ASC",
            },
          },
          relations: [
            "posMasters",
            "posMasters.positions",
            "posMasters.positions.posLevel",
            "posMasters.positions.posType",
            "posMasters.positions.posExecutive",
          ],
        });
        const orgChild2Ids = orgChild2Data.map((c) => c.id) || null;
        const orgChild3Data = await this.child3Repository.find({
          where: { orgChild2: In(orgChild2Ids) },
          order: {
            orgChild3Order: "ASC",
            posMasters: {
              posMasterOrder: "ASC",
              posMasterCreatedAt: "ASC",
            },
          },
          relations: [
            "posMasters",
            "posMasters.positions",
            "posMasters.positions.posLevel",
            "posMasters.positions.posType",
            "posMasters.positions.posExecutive",
          ],
        });
        const orgChild3Ids = orgChild3Data.map((c) => c.id) || null;
        const orgChild4Data = await this.child4Repository.find({
          where: { orgChild3: In(orgChild3Ids) },
          order: {
            orgChild4Order: "ASC",
            posMasters: {
              posMasterOrder: "ASC",
              posMasterCreatedAt: "ASC",
            },
          },
          relations: [
            "posMasters",
            "posMasters.positions",
            "posMasters.positions.posLevel",
            "posMasters.positions.posType",
            "posMasters.positions.posExecutive",
          ],
        });

        let _nodeTemp: any = null;
        for (let orgRoot of orgRootData) {
          const posMastersFiltered = orgRoot.posMasters
            .filter((x) => x.orgChild1Id == null)
            .sort((a, b) => a.posMasterOrder - b.posMasterOrder);

          for (let posMaster of posMastersFiltered) {
            if (posMaster.orgChild1Id == null) {
              const positionName = [
                ...new Set(
                  posMaster.positions
                    .sort((a: any, b: any) => a.orderNo - b.orderNo)
                    .map((x) =>
                      x.positionArea ? `${x.positionName} (${x.positionArea})` : x.positionName,
                    ),
                ),
              ];
              const posType = [
                ...new Set(
                  posMaster.positions
                    .filter((x: any) => x.posType != null)
                    .map((x) => x.posType.posTypeName),
                ),
              ];
              const posLevel = [
                ...new Set(
                  posMaster.positions
                    .filter((x: any) => x.posLevel != null)
                    .map((x) => x.posLevel.posLevelName),
                ),
              ];
              const posExecutive = [
                ...new Set(
                  posMaster.positions
                    .filter((x: any) => x.posExecutive != null)
                    .map((x: any) =>
                      x.positionExecutiveField
                        ? `${x.posExecutive.posExecutiveName} (${x.positionExecutiveField})`
                        : x.posExecutive.posExecutiveName,
                    ),
                ),
              ];

              let node = {
                orgTreeName: orgRoot.orgRootName,
                orgTreeShortName: orgRoot.orgRootShortName,
                posMasterNo: posMaster.posMasterNo,
                positionName: positionName.join(" หรือ "),
                posType: posType.join(" หรือ "),
                posLevel: posLevel.join(" หรือ "),
                posExecutive: posExecutive.join(" หรือ "),
                reason: posMaster.reason == null ? "" : posMaster.reason,
              };
              if (_nodeTemp == null) {
                const head = {
                  posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName.toString()),
                  posExecutive: Extension.ToThaiNumber(node.orgTreeName.toString()),
                  positionName: "",
                  posType: "",
                  posLevel: "",
                  reason: "",
                };
                data.push(head);
                const _head = {
                  no: Extension.ToThaiNumber(no.toString()),
                  posMasterNo:
                    node.posMasterNo == null
                      ? ""
                      : Extension.ToThaiNumber(node.posMasterNo.toString()),
                  posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                  positionName: Extension.ToThaiNumber(node.positionName.toString()),
                  posType: Extension.ToThaiNumber(node.posType.toString()),
                  posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                  reason: Extension.ToThaiNumber(node.reason.toString()),
                };
                data.push(_head);
              } else {
                if (
                  node.orgTreeShortName != _nodeTemp.orgTreeShortName ||
                  node.orgTreeName != _nodeTemp.orgTreeName
                ) {
                  const head = {
                    posMasterNo:
                      node.orgTreeShortName == _nodeTemp.orgTreeShortName
                        ? ""
                        : node.orgTreeShortName,
                    posExecutive:
                      node.orgTreeName == _nodeTemp.orgTreeName
                        ? ""
                        : Extension.ToThaiNumber(node.orgTreeName.toString()),
                    positionName: "",
                    posType: "",
                    posLevel: "",
                    reason: "",
                  };
                  data.push(head);
                  _nodeTemp = null;
                }
                const head = {
                  no: Extension.ToThaiNumber(no.toString()),
                  posMasterNo:
                    node.posMasterNo == null
                      ? ""
                      : Extension.ToThaiNumber(node.posMasterNo.toString()),
                  posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                  positionName: Extension.ToThaiNumber(node.positionName.toString()),
                  posType: Extension.ToThaiNumber(node.posType.toString()),
                  posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                  reason: Extension.ToThaiNumber(node.reason.toString()),
                };
                data.push(head);
              }
              no += 1;
              _nodeTemp = node;
            }
          }
          _nodeTemp = null;

          for (let orgChild1 of orgChild1Data.filter(
            (orgChild1) => orgChild1.orgRootId === orgRoot.id,
          )) {
            const posMastersFiltered = orgChild1.posMasters
              .filter((x) => x.orgChild2Id == null)
              .sort((a, b) => a.posMasterOrder - b.posMasterOrder);

            for (let posMaster of posMastersFiltered) {
              if (posMaster.orgChild2Id == null) {
                const positionName = [
                  ...new Set(
                    posMaster.positions
                      .sort((a: any, b: any) => a.orderNo - b.orderNo)
                      .map((x) =>
                        x.positionArea ? `${x.positionName} (${x.positionArea})` : x.positionName,
                      ),
                  ),
                ];
                const posType = [
                  ...new Set(
                    posMaster.positions
                      .filter((x: any) => x.posType != null)
                      .map((x) => x.posType.posTypeName),
                  ),
                ];
                const posLevel = [
                  ...new Set(
                    posMaster.positions
                      .filter((x: any) => x.posLevel != null)
                      .map((x) => x.posLevel.posLevelName),
                  ),
                ];
                const posExecutive = [
                  ...new Set(
                    posMaster.positions
                      .filter((x: any) => x.posExecutive != null)
                      .map((x: any) =>
                        x.positionExecutiveField
                          ? `${x.posExecutive.posExecutiveName} (${x.positionExecutiveField})`
                          : x.posExecutive.posExecutiveName,
                      ),
                  ),
                ];

                let node = {
                  orgTreeName: orgChild1.orgChild1Name,
                  orgTreeShortName: orgChild1.orgChild1ShortName,
                  posMasterNo: posMaster.posMasterNo,
                  positionName: positionName.join(" หรือ "),
                  posType: posType.join(" หรือ "),
                  posLevel: posLevel.join(" หรือ "),
                  posExecutive: posExecutive.join(" หรือ "),
                  reason: posMaster.reason == null ? "" : posMaster.reason,
                };
                if (_nodeTemp == null) {
                  const head = {
                    posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName?.toString() ?? ""),
                    posExecutive: Extension.ToThaiNumber(node.orgTreeName?.toString() ?? ""),
                    positionName: "",
                    posType: "",
                    posLevel: "",
                    reason: "",
                  };
                  data.push(head);
                  const _head = {
                    no: Extension.ToThaiNumber(no.toString()),
                    posMasterNo:
                      node.posMasterNo == null
                        ? ""
                        : Extension.ToThaiNumber(node.posMasterNo.toString()),
                    posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                    positionName: Extension.ToThaiNumber(node.positionName.toString()),
                    posType: Extension.ToThaiNumber(node.posType.toString()),
                    posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                    reason: Extension.ToThaiNumber(node.reason.toString()),
                  };
                  data.push(_head);
                } else {
                  if (
                    node.orgTreeShortName != _nodeTemp.orgTreeShortName ||
                    node.orgTreeName != _nodeTemp.orgTreeName
                  ) {
                    const head = {
                      posMasterNo:
                        node.orgTreeShortName == _nodeTemp.orgTreeShortName
                          ? ""
                          : node.orgTreeShortName,
                      posExecutive:
                        node.orgTreeName == _nodeTemp.orgTreeName
                          ? ""
                          : Extension.ToThaiNumber(node.orgTreeName.toString()),
                      positionName: "",
                      posType: "",
                      posLevel: "",
                      reason: "",
                    };
                    data.push(head);
                    _nodeTemp = null;
                  }
                  const head = {
                    no: Extension.ToThaiNumber(no.toString()),
                    posMasterNo:
                      node.posMasterNo == null
                        ? ""
                        : Extension.ToThaiNumber(node.posMasterNo.toString()),
                    posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                    positionName: Extension.ToThaiNumber(node.positionName.toString()),
                    posType: Extension.ToThaiNumber(node.posType.toString()),
                    posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                    reason: Extension.ToThaiNumber(node.reason.toString()),
                  };
                  data.push(head);
                }
                no += 1;
                _nodeTemp = node;
              }
            }

            for (let orgChild2 of orgChild2Data.filter(
              (orgChild2) => orgChild2.orgChild1Id === orgChild1.id,
            )) {
              const posMastersFiltered = orgChild2.posMasters
                .filter((x) => x.orgChild3Id == null)
                .sort((a, b) => a.posMasterOrder - b.posMasterOrder);

              for (let posMaster of posMastersFiltered) {
                if (posMaster.orgChild3Id == null) {
                  const positionName = [
                    ...new Set(
                      posMaster.positions
                        .sort((a: any, b: any) => a.orderNo - b.orderNo)
                        .map((x) =>
                          x.positionArea ? `${x.positionName} (${x.positionArea})` : x.positionName,
                        ),
                    ),
                  ];
                  const posType = [
                    ...new Set(
                      posMaster.positions
                        .filter((x: any) => x.posType != null)
                        .map((x) => x.posType.posTypeName),
                    ),
                  ];
                  const posLevel = [
                    ...new Set(
                      posMaster.positions
                        .filter((x: any) => x.posLevel != null)
                        .map((x) => x.posLevel.posLevelName),
                    ),
                  ];
                  const posExecutive = [
                    ...new Set(
                      posMaster.positions
                        .filter((x: any) => x.posExecutive != null)
                        .map((x: any) =>
                          x.positionExecutiveField
                            ? `${x.posExecutive.posExecutiveName} (${x.positionExecutiveField})`
                            : x.posExecutive.posExecutiveName,
                        ),
                    ),
                  ];

                  let node = {
                    orgTreeName: orgChild2.orgChild2Name,
                    orgTreeShortName: orgChild2.orgChild2ShortName,
                    posMasterNo: posMaster.posMasterNo,
                    positionName: positionName.join(" หรือ "),
                    posType: posType.join(" หรือ "),
                    posLevel: posLevel.join(" หรือ "),
                    posExecutive: posExecutive.join(" หรือ "),
                    reason: posMaster.reason == null ? "" : posMaster.reason,
                  };
                  if (_nodeTemp == null) {
                    const head = {
                      posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName?.toString() ?? ""),
                      posExecutive: Extension.ToThaiNumber(node.orgTreeName?.toString() ?? ""),
                      positionName: "",
                      posType: "",
                      posLevel: "",
                      reason: "",
                    };
                    data.push(head);
                    const _head = {
                      no: Extension.ToThaiNumber(no.toString()),
                      posMasterNo:
                        node.posMasterNo == null
                          ? ""
                          : Extension.ToThaiNumber(node.posMasterNo.toString()),
                      posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                      positionName: Extension.ToThaiNumber(node.positionName.toString()),
                      posType: Extension.ToThaiNumber(node.posType.toString()),
                      posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                      reason: Extension.ToThaiNumber(node.reason.toString()),
                    };
                    data.push(_head);
                  } else {
                    if (
                      node.orgTreeShortName != _nodeTemp.orgTreeShortName ||
                      node.orgTreeName != _nodeTemp.orgTreeName
                    ) {
                      const head = {
                        posMasterNo:
                          node.orgTreeShortName == _nodeTemp.orgTreeShortName
                            ? ""
                            : node.orgTreeShortName,
                        posExecutive:
                          node.orgTreeName == _nodeTemp.orgTreeName
                            ? ""
                            : Extension.ToThaiNumber(node.orgTreeName.toString()),
                        positionName: "",
                        posType: "",
                        posLevel: "",
                        reason: "",
                      };
                      data.push(head);
                      _nodeTemp = null;
                    }
                    const head = {
                      no: Extension.ToThaiNumber(no.toString()),
                      posMasterNo:
                        node.posMasterNo == null
                          ? ""
                          : Extension.ToThaiNumber(node.posMasterNo.toString()),
                      posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                      positionName: Extension.ToThaiNumber(node.positionName.toString()),
                      posType: Extension.ToThaiNumber(node.posType.toString()),
                      posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                      reason: Extension.ToThaiNumber(node.reason.toString()),
                    };
                    data.push(head);
                  }
                  no += 1;
                  _nodeTemp = node;
                }
              }

              for (let orgChild3 of orgChild3Data.filter(
                (orgChild3) => orgChild3.orgChild2Id === orgChild2.id,
              )) {
                await Promise.all(
                  orgChild3.posMasters
                    .filter((x) => x.orgChild4Id == null)
                    .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
                    .map(async (posMaster) => {
                      if (posMaster.orgChild4Id == null) {
                        const positionName = [
                          ...new Set(
                            posMaster.positions
                              .sort((a: any, b: any) => a.orderNo - b.orderNo)
                              .map((x) =>
                                x.positionArea
                                  ? `${x.positionName} (${x.positionArea})`
                                  : x.positionName,
                              ),
                          ),
                        ];
                        const posType = [
                          ...new Set(
                            posMaster.positions
                              .filter((x: any) => x.posType != null)
                              .map((x) => x.posType.posTypeName),
                          ),
                        ];
                        const posLevel = [
                          ...new Set(
                            posMaster.positions
                              .filter((x: any) => x.posLevel != null)
                              .map((x) => x.posLevel.posLevelName),
                          ),
                        ];
                        const posExecutive = [
                          ...new Set(
                            posMaster.positions
                              .filter((x: any) => x.posExecutive != null)
                              .map((x: any) =>
                                x.positionExecutiveField
                                  ? `${x.posExecutive.posExecutiveName} (${x.positionExecutiveField})`
                                  : x.posExecutive.posExecutiveName,
                              ),
                          ),
                        ];

                        let node = {
                          orgTreeName: orgChild3.orgChild3Name,
                          orgTreeShortName: orgChild3.orgChild3ShortName,
                          posMasterNo: posMaster.posMasterNo,
                          positionName: positionName.join(" หรือ "),
                          posType: posType.join(" หรือ "),
                          posLevel: posLevel.join(" หรือ "),
                          posExecutive: posExecutive.join(" หรือ "),
                          reason: posMaster.reason == null ? "" : posMaster.reason,
                        };
                        if (_nodeTemp == null) {
                          const head = {
                            posMasterNo: Extension.ToThaiNumber(
                              node.orgTreeShortName?.toString() ?? "",
                            ),
                            posExecutive: Extension.ToThaiNumber(
                              node.orgTreeName?.toString() ?? "",
                            ),
                            positionName: "",
                            posType: "",
                            posLevel: "",
                            reason: "",
                          };
                          data.push(head);
                          const _head = {
                            no: Extension.ToThaiNumber(no.toString()),
                            posMasterNo:
                              node.posMasterNo == null
                                ? ""
                                : Extension.ToThaiNumber(node.posMasterNo.toString()),
                            posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                            positionName: Extension.ToThaiNumber(node.positionName.toString()),
                            posType: Extension.ToThaiNumber(node.posType.toString()),
                            posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                            reason: Extension.ToThaiNumber(node.reason.toString()),
                          };
                          data.push(_head);
                        } else {
                          if (
                            node.orgTreeShortName != _nodeTemp.orgTreeShortName ||
                            node.orgTreeName != _nodeTemp.orgTreeName
                          ) {
                            const head = {
                              posMasterNo:
                                node.orgTreeShortName == _nodeTemp.orgTreeShortName
                                  ? ""
                                  : node.orgTreeShortName,
                              posExecutive:
                                node.orgTreeName == _nodeTemp.orgTreeName
                                  ? ""
                                  : Extension.ToThaiNumber(node.orgTreeName.toString()),
                              positionName: "",
                              posType: "",
                              posLevel: "",
                              reason: "",
                            };
                            data.push(head);
                            _nodeTemp = null;
                          }
                          const head = {
                            no: Extension.ToThaiNumber(no.toString()),
                            posMasterNo:
                              node.posMasterNo == null
                                ? ""
                                : Extension.ToThaiNumber(node.posMasterNo.toString()),
                            posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                            positionName: Extension.ToThaiNumber(node.positionName.toString()),
                            posType: Extension.ToThaiNumber(node.posType.toString()),
                            posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                            reason: Extension.ToThaiNumber(node.reason.toString()),
                          };
                          data.push(head);
                        }
                        no += 1;
                        _nodeTemp = node;
                      }
                    }),
                );

                for (let orgChild4 of orgChild4Data.filter(
                  (orgChild4) => orgChild4.orgChild3Id === orgChild3.id,
                )) {
                  await Promise.all(
                    orgChild4.posMasters
                      .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
                      .map(async (posMaster) => {
                        const positionName = [
                          ...new Set(
                            posMaster.positions
                              .sort((a: any, b: any) => a.orderNo - b.orderNo)
                              .map((x) =>
                                x.positionArea
                                  ? `${x.positionName} (${x.positionArea})`
                                  : x.positionName,
                              ),
                          ),
                        ];
                        const posType = [
                          ...new Set(
                            posMaster.positions
                              .filter((x: any) => x.posType != null)
                              .map((x) => x.posType.posTypeName),
                          ),
                        ];
                        const posLevel = [
                          ...new Set(
                            posMaster.positions
                              .filter((x: any) => x.posLevel != null)
                              .map((x) => x.posLevel.posLevelName),
                          ),
                        ];
                        const posExecutive = [
                          ...new Set(
                            posMaster.positions
                              .filter((x: any) => x.posExecutive != null)
                              .map((x: any) =>
                                x.positionExecutiveField
                                  ? `${x.posExecutive.posExecutiveName} (${x.positionExecutiveField})`
                                  : x.posExecutive.posExecutiveName,
                              ),
                          ),
                        ];

                        let node = {
                          orgTreeName: orgChild4.orgChild4Name,
                          orgTreeShortName: orgChild4.orgChild4ShortName,
                          posMasterNo: posMaster.posMasterNo,
                          positionName: positionName.join(" หรือ "),
                          posType: posType.join(" หรือ "),
                          posLevel: posLevel.join(" หรือ "),
                          posExecutive: posExecutive.join(" หรือ "),
                          reason: posMaster.reason == null ? "" : posMaster.reason,
                        };
                        if (_nodeTemp == null) {
                          const head = {
                            posMasterNo: Extension.ToThaiNumber(
                              node.orgTreeShortName?.toString() ?? "",
                            ),
                            posExecutive: Extension.ToThaiNumber(
                              node.orgTreeName?.toString() ?? "",
                            ),
                            positionName: "",
                            posType: "",
                            posLevel: "",
                            reason: "",
                          };
                          data.push(head);
                          const _head = {
                            no: Extension.ToThaiNumber(no.toString()),
                            posMasterNo:
                              node.posMasterNo == null
                                ? ""
                                : Extension.ToThaiNumber(node.posMasterNo.toString()),
                            posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                            positionName: Extension.ToThaiNumber(node.positionName.toString()),
                            posType: Extension.ToThaiNumber(node.posType.toString()),
                            posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                            reason: Extension.ToThaiNumber(node.reason.toString()),
                          };
                          data.push(_head);
                        } else {
                          if (
                            node.orgTreeShortName != _nodeTemp.orgTreeShortName ||
                            node.orgTreeName != _nodeTemp.orgTreeName
                          ) {
                            const head = {
                              posMasterNo:
                                node.orgTreeShortName == _nodeTemp.orgTreeShortName
                                  ? ""
                                  : node.orgTreeShortName,
                              posExecutive:
                                node.orgTreeName == _nodeTemp.orgTreeName
                                  ? ""
                                  : Extension.ToThaiNumber(node.orgTreeName.toString()),
                              positionName: "",
                              posType: "",
                              posLevel: "",
                              reason: "",
                            };
                            data.push(head);
                            _nodeTemp = null;
                          }
                          const head = {
                            no: Extension.ToThaiNumber(no.toString()),
                            posMasterNo:
                              node.posMasterNo == null
                                ? ""
                                : Extension.ToThaiNumber(node.posMasterNo.toString()),
                            posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                            positionName: Extension.ToThaiNumber(node.positionName.toString()),
                            posType: Extension.ToThaiNumber(node.posType.toString()),
                            posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                            reason: Extension.ToThaiNumber(node.reason.toString()),
                          };
                          data.push(head);
                        }
                        no += 1;
                        _nodeTemp = node;
                      }),
                  );
                }
              }
            }
          }
        }
        break;
      }
      case 1: {
        // ดึง orgChild1 และลูก (orgChild2, orgChild3, orgChild4)
        const orgChild1Data = await this.child1Repository.find({
          where: { id: _nodeId },
          order: {
            orgChild1Order: "ASC",
            posMasters: {
              posMasterOrder: "ASC",
              posMasterCreatedAt: "ASC",
            },
          },
          relations: [
            "posMasters",
            "posMasters.positions",
            "posMasters.positions.posLevel",
            "posMasters.positions.posType",
            "posMasters.positions.posExecutive",
          ],
        });
        if (!orgChild1Data || orgChild1Data.length === 0) {
          throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล orgChild1");
        }
        orgName = orgChild1Data[0].orgChild1Name ?? "";
        // cascade ลูก
        const orgChild1Ids = orgChild1Data.map((c) => c.id) || null;
        const orgChild2Data = await this.child2Repository.find({
          where: { orgChild1: In(orgChild1Ids) },
          order: {
            orgChild2Order: "ASC",
            posMasters: {
              posMasterOrder: "ASC",
              posMasterCreatedAt: "ASC",
            },
          },
          relations: [
            "posMasters",
            "posMasters.positions",
            "posMasters.positions.posLevel",
            "posMasters.positions.posType",
            "posMasters.positions.posExecutive",
          ],
        });
        const orgChild2Ids = orgChild2Data.map((c) => c.id) || null;
        const orgChild3Data = await this.child3Repository.find({
          where: { orgChild2: In(orgChild2Ids) },
          order: {
            orgChild3Order: "ASC",
            posMasters: {
              posMasterOrder: "ASC",
              posMasterCreatedAt: "ASC",
            },
          },
          relations: [
            "posMasters",
            "posMasters.positions",
            "posMasters.positions.posLevel",
            "posMasters.positions.posType",
            "posMasters.positions.posExecutive",
          ],
        });
        const orgChild3Ids = orgChild3Data.map((c) => c.id) || null;
        const orgChild4Data = await this.child4Repository.find({
          where: { orgChild3: In(orgChild3Ids) },
          order: {
            orgChild4Order: "ASC",
            posMasters: {
              posMasterOrder: "ASC",
              posMasterCreatedAt: "ASC",
            },
          },
          relations: [
            "posMasters",
            "posMasters.positions",
            "posMasters.positions.posLevel",
            "posMasters.positions.posType",
            "posMasters.positions.posExecutive",
          ],
        });
        let _nodeTemp: any = null;
        for (let orgChild1 of orgChild1Data) {
          await Promise.all(
            orgChild1.posMasters
              .filter((x) => x.orgChild2Id == null)
              .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
              .map(async (posMaster) => {
                if (posMaster.orgChild2Id == null) {
                  // --- push data logic (เหมือน node 0) ---
                  const positionName = [
                    ...new Set(
                      posMaster.positions
                        .sort((a: any, b: any) => a.orderNo - b.orderNo)
                        .map((x) =>
                          x.positionArea ? `${x.positionName} (${x.positionArea})` : x.positionName,
                        ),
                    ),
                  ];
                  const posType = [
                    ...new Set(
                      posMaster.positions
                        .filter((x: any) => x.posType != null)
                        .map((x) => x.posType.posTypeName),
                    ),
                  ];
                  const posLevel = [
                    ...new Set(
                      posMaster.positions
                        .filter((x: any) => x.posLevel != null)
                        .map((x) => x.posLevel.posLevelName),
                    ),
                  ];
                  const posExecutive = [
                    ...new Set(
                      posMaster.positions
                        .filter((x: any) => x.posExecutive != null)
                        .map((x: any) =>
                          x.positionExecutiveField
                            ? `${x.posExecutive.posExecutiveName} (${x.positionExecutiveField})`
                            : x.posExecutive.posExecutiveName,
                        ),
                    ),
                  ];
                  let node = {
                    orgTreeName: orgChild1.orgChild1Name,
                    orgTreeShortName: orgChild1.orgChild1ShortName,
                    posMasterNo: posMaster.posMasterNo,
                    positionName: positionName.join(" หรือ "),
                    posType: posType.join(" หรือ "),
                    posLevel: posLevel.join(" หรือ "),
                    posExecutive: posExecutive.join(" หรือ "),
                    reason: posMaster.reason == null ? "" : posMaster.reason,
                  };
                  if (_nodeTemp == null) {
                    const head = {
                      posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName?.toString() ?? ""),
                      posExecutive: Extension.ToThaiNumber(node.orgTreeName?.toString() ?? ""),
                      positionName: "",
                      posType: "",
                      posLevel: "",
                      reason: "",
                    };
                    data.push(head);
                    const _head = {
                      no: Extension.ToThaiNumber(no.toString()),
                      posMasterNo:
                        node.posMasterNo == null
                          ? ""
                          : Extension.ToThaiNumber(node.posMasterNo.toString()),
                      posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                      positionName: Extension.ToThaiNumber(node.positionName.toString()),
                      posType: Extension.ToThaiNumber(node.posType.toString()),
                      posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                      reason: Extension.ToThaiNumber(node.reason.toString()),
                    };
                    data.push(_head);
                  } else {
                    if (
                      node.orgTreeShortName != _nodeTemp.orgTreeShortName ||
                      node.orgTreeName != _nodeTemp.orgTreeName
                    ) {
                      const head = {
                        posMasterNo:
                          node.orgTreeShortName == _nodeTemp.orgTreeShortName
                            ? ""
                            : node.orgTreeShortName,
                        posExecutive:
                          node.orgTreeName == _nodeTemp.orgTreeName
                            ? ""
                            : Extension.ToThaiNumber(node.orgTreeName.toString()),
                        positionName: "",
                        posType: "",
                        posLevel: "",
                        reason: "",
                      };
                      data.push(head);
                      _nodeTemp = null;
                    }
                    const head = {
                      no: Extension.ToThaiNumber(no.toString()),
                      posMasterNo:
                        node.posMasterNo == null
                          ? ""
                          : Extension.ToThaiNumber(node.posMasterNo.toString()),
                      posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                      positionName: Extension.ToThaiNumber(node.positionName.toString()),
                      posType: Extension.ToThaiNumber(node.posType.toString()),
                      posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                      reason: Extension.ToThaiNumber(node.reason.toString()),
                    };
                    data.push(head);
                  }
                  no += 1;
                  _nodeTemp = node;
                }
              }),
          );
          for (let orgChild2 of orgChild2Data.filter(
            (orgChild2) => orgChild2.orgChild1Id === orgChild1.id,
          )) {
            await Promise.all(
              orgChild2.posMasters
                .filter((x) => x.orgChild3Id == null)
                .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
                .map(async (posMaster) => {
                  if (posMaster.orgChild3Id == null) {
                    // --- push data logic (เหมือน node 0) ---
                    const positionName = [
                      ...new Set(
                        posMaster.positions
                          .sort((a: any, b: any) => a.orderNo - b.orderNo)
                          .map((x) =>
                            x.positionArea
                              ? `${x.positionName} (${x.positionArea})`
                              : x.positionName,
                          ),
                      ),
                    ];
                    const posType = [
                      ...new Set(
                        posMaster.positions
                          .filter((x: any) => x.posType != null)
                          .map((x) => x.posType.posTypeName),
                      ),
                    ];
                    const posLevel = [
                      ...new Set(
                        posMaster.positions
                          .filter((x: any) => x.posLevel != null)
                          .map((x) => x.posLevel.posLevelName),
                      ),
                    ];
                    const posExecutive = [
                      ...new Set(
                        posMaster.positions
                          .filter((x: any) => x.posExecutive != null)
                          .map((x: any) =>
                            x.positionExecutiveField
                              ? `${x.posExecutive.posExecutiveName} (${x.positionExecutiveField})`
                              : x.posExecutive.posExecutiveName,
                          ),
                      ),
                    ];
                    let node = {
                      orgTreeName: orgChild2.orgChild2Name,
                      orgTreeShortName: orgChild2.orgChild2ShortName,
                      posMasterNo: posMaster.posMasterNo,
                      positionName: positionName.join(" หรือ "),
                      posType: posType.join(" หรือ "),
                      posLevel: posLevel.join(" หรือ "),
                      posExecutive: posExecutive.join(" หรือ "),
                      reason: posMaster.reason == null ? "" : posMaster.reason,
                    };
                    if (_nodeTemp == null) {
                      const head = {
                        posMasterNo: Extension.ToThaiNumber(
                          node.orgTreeShortName?.toString() ?? "",
                        ),
                        posExecutive: Extension.ToThaiNumber(node.orgTreeName?.toString() ?? ""),
                        positionName: "",
                        posType: "",
                        posLevel: "",
                        reason: "",
                      };
                      data.push(head);
                      const _head = {
                        no: Extension.ToThaiNumber(no.toString()),
                        posMasterNo:
                          node.posMasterNo == null
                            ? ""
                            : Extension.ToThaiNumber(node.posMasterNo.toString()),
                        posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                        positionName: Extension.ToThaiNumber(node.positionName.toString()),
                        posType: Extension.ToThaiNumber(node.posType.toString()),
                        posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                        reason: Extension.ToThaiNumber(node.reason.toString()),
                      };
                      data.push(_head);
                    } else {
                      if (
                        node.orgTreeShortName != _nodeTemp.orgTreeShortName ||
                        node.orgTreeName != _nodeTemp.orgTreeName
                      ) {
                        const head = {
                          posMasterNo:
                            node.orgTreeShortName == _nodeTemp.orgTreeShortName
                              ? ""
                              : node.orgTreeShortName,
                          posExecutive:
                            node.orgTreeName == _nodeTemp.orgTreeName
                              ? ""
                              : Extension.ToThaiNumber(node.orgTreeName.toString()),
                          positionName: "",
                          posType: "",
                          posLevel: "",
                          reason: "",
                        };
                        data.push(head);
                        _nodeTemp = null;
                      }
                      const head = {
                        no: Extension.ToThaiNumber(no.toString()),
                        posMasterNo:
                          node.posMasterNo == null
                            ? ""
                            : Extension.ToThaiNumber(node.posMasterNo.toString()),
                        posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                        positionName: Extension.ToThaiNumber(node.positionName.toString()),
                        posType: Extension.ToThaiNumber(node.posType.toString()),
                        posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                        reason: Extension.ToThaiNumber(node.reason.toString()),
                      };
                      data.push(head);
                    }
                    no += 1;
                    _nodeTemp = node;
                  }
                }),
            );
            for (let orgChild3 of orgChild3Data.filter(
              (orgChild3) => orgChild3.orgChild2Id === orgChild2.id,
            )) {
              await Promise.all(
                orgChild3.posMasters
                  .filter((x) => x.orgChild4Id == null)
                  .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
                  .map(async (posMaster) => {
                    if (posMaster.orgChild4Id == null) {
                      // --- push data logic (เหมือน node 0) ---
                      const positionName = [
                        ...new Set(
                          posMaster.positions
                            .sort((a: any, b: any) => a.orderNo - b.orderNo)
                            .map((x) =>
                              x.positionArea
                                ? `${x.positionName} (${x.positionArea})`
                                : x.positionName,
                            ),
                        ),
                      ];
                      const posType = [
                        ...new Set(
                          posMaster.positions
                            .filter((x: any) => x.posType != null)
                            .map((x) => x.posType.posTypeName),
                        ),
                      ];
                      const posLevel = [
                        ...new Set(
                          posMaster.positions
                            .filter((x: any) => x.posLevel != null)
                            .map((x) => x.posLevel.posLevelName),
                        ),
                      ];
                      const posExecutive = [
                        ...new Set(
                          posMaster.positions
                            .filter((x: any) => x.posExecutive != null)
                            .map((x: any) =>
                              x.positionExecutiveField
                                ? `${x.posExecutive.posExecutiveName} (${x.positionExecutiveField})`
                                : x.posExecutive.posExecutiveName,
                            ),
                        ),
                      ];
                      let node = {
                        orgTreeName: orgChild3.orgChild3Name,
                        orgTreeShortName: orgChild3.orgChild3ShortName,
                        posMasterNo: posMaster.posMasterNo,
                        positionName: positionName.join(" หรือ "),
                        posType: posType.join(" หรือ "),
                        posLevel: posLevel.join(" หรือ "),
                        posExecutive: posExecutive.join(" หรือ "),
                        reason: posMaster.reason == null ? "" : posMaster.reason,
                      };
                      if (_nodeTemp == null) {
                        const head = {
                          posMasterNo: Extension.ToThaiNumber(
                            node.orgTreeShortName?.toString() ?? "",
                          ),
                          posExecutive: Extension.ToThaiNumber(node.orgTreeName?.toString() ?? ""),
                          positionName: "",
                          posType: "",
                          posLevel: "",
                          reason: "",
                        };
                        data.push(head);
                        const _head = {
                          no: Extension.ToThaiNumber(no.toString()),
                          posMasterNo:
                            node.posMasterNo == null
                              ? ""
                              : Extension.ToThaiNumber(node.posMasterNo.toString()),
                          posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                          positionName: Extension.ToThaiNumber(node.positionName.toString()),
                          posType: Extension.ToThaiNumber(node.posType.toString()),
                          posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                          reason: Extension.ToThaiNumber(node.reason.toString()),
                        };
                        data.push(_head);
                      } else {
                        if (
                          node.orgTreeShortName != _nodeTemp.orgTreeShortName ||
                          node.orgTreeName != _nodeTemp.orgTreeName
                        ) {
                          const head = {
                            posMasterNo:
                              node.orgTreeShortName == _nodeTemp.orgTreeShortName
                                ? ""
                                : node.orgTreeShortName,
                            posExecutive:
                              node.orgTreeName == _nodeTemp.orgTreeName
                                ? ""
                                : Extension.ToThaiNumber(node.orgTreeName.toString()),
                            positionName: "",
                            posType: "",
                            posLevel: "",
                            reason: "",
                          };
                          data.push(head);
                          _nodeTemp = null;
                        }
                        const head = {
                          no: Extension.ToThaiNumber(no.toString()),
                          posMasterNo:
                            node.posMasterNo == null
                              ? ""
                              : Extension.ToThaiNumber(node.posMasterNo.toString()),
                          posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                          positionName: Extension.ToThaiNumber(node.positionName.toString()),
                          posType: Extension.ToThaiNumber(node.posType.toString()),
                          posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                          reason: Extension.ToThaiNumber(node.reason.toString()),
                        };
                        data.push(head);
                      }
                      no += 1;
                      _nodeTemp = node;
                    }
                  }),
              );
              for (let orgChild4 of orgChild4Data.filter(
                (orgChild4) => orgChild4.orgChild3Id === orgChild3.id,
              )) {
                await Promise.all(
                  orgChild4.posMasters
                    .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
                    .map(async (posMaster) => {
                      // --- push data logic (เหมือน node 0) ---
                      const positionName = [
                        ...new Set(
                          posMaster.positions
                            .sort((a: any, b: any) => a.orderNo - b.orderNo)
                            .map((x) =>
                              x.positionArea
                                ? `${x.positionName} (${x.positionArea})`
                                : x.positionName,
                            ),
                        ),
                      ];
                      const posType = [
                        ...new Set(
                          posMaster.positions
                            .filter((x: any) => x.posType != null)
                            .map((x) => x.posType.posTypeName),
                        ),
                      ];
                      const posLevel = [
                        ...new Set(
                          posMaster.positions
                            .filter((x: any) => x.posLevel != null)
                            .map((x) => x.posLevel.posLevelName),
                        ),
                      ];
                      const posExecutive = [
                        ...new Set(
                          posMaster.positions
                            .filter((x: any) => x.posExecutive != null)
                            .map((x: any) =>
                              x.positionExecutiveField
                                ? `${x.posExecutive.posExecutiveName} (${x.positionExecutiveField})`
                                : x.posExecutive.posExecutiveName,
                            ),
                        ),
                      ];
                      let node = {
                        orgTreeName: orgChild4.orgChild4Name,
                        orgTreeShortName: orgChild4.orgChild4ShortName,
                        posMasterNo: posMaster.posMasterNo,
                        positionName: positionName.join(" หรือ "),
                        posType: posType.join(" หรือ "),
                        posLevel: posLevel.join(" หรือ "),
                        posExecutive: posExecutive.join(" หรือ "),
                        reason: posMaster.reason == null ? "" : posMaster.reason,
                      };
                      if (_nodeTemp == null) {
                        const head = {
                          posMasterNo: Extension.ToThaiNumber(
                            node.orgTreeShortName?.toString() ?? "",
                          ),
                          posExecutive: Extension.ToThaiNumber(node.orgTreeName?.toString() ?? ""),
                          positionName: "",
                          posType: "",
                          posLevel: "",
                          reason: "",
                        };
                        data.push(head);
                        const _head = {
                          no: Extension.ToThaiNumber(no.toString()),
                          posMasterNo:
                            node.posMasterNo == null
                              ? ""
                              : Extension.ToThaiNumber(node.posMasterNo.toString()),
                          posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                          positionName: Extension.ToThaiNumber(node.positionName.toString()),
                          posType: Extension.ToThaiNumber(node.posType.toString()),
                          posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                          reason: Extension.ToThaiNumber(node.reason.toString()),
                        };
                        data.push(_head);
                      } else {
                        if (
                          node.orgTreeShortName != _nodeTemp.orgTreeShortName ||
                          node.orgTreeName != _nodeTemp.orgTreeName
                        ) {
                          const head = {
                            posMasterNo:
                              node.orgTreeShortName == _nodeTemp.orgTreeShortName
                                ? ""
                                : node.orgTreeShortName,
                            posExecutive:
                              node.orgTreeName == _nodeTemp.orgTreeName
                                ? ""
                                : Extension.ToThaiNumber(node.orgTreeName.toString()),
                            positionName: "",
                            posType: "",
                            posLevel: "",
                            reason: "",
                          };
                          data.push(head);
                          _nodeTemp = null;
                        }
                        const head = {
                          no: Extension.ToThaiNumber(no.toString()),
                          posMasterNo:
                            node.posMasterNo == null
                              ? ""
                              : Extension.ToThaiNumber(node.posMasterNo.toString()),
                          posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                          positionName: Extension.ToThaiNumber(node.positionName.toString()),
                          posType: Extension.ToThaiNumber(node.posType.toString()),
                          posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                          reason: Extension.ToThaiNumber(node.reason.toString()),
                        };
                        data.push(head);
                      }
                      no += 1;
                      _nodeTemp = node;
                    }),
                );
              }
            }
          }
        }
        break;
      }
      case 2: {
        // ดึง orgChild2 และลูก (orgChild3, orgChild4)
        const orgChild2Data = await this.child2Repository.find({
          where: {
            id: _nodeId,
          },
          order: {
            orgChild2Order: "ASC",
            posMasters: {
              posMasterOrder: "ASC",
              posMasterCreatedAt: "ASC",
            },
          },
          relations: [
            "posMasters",
            "posMasters.positions",
            "posMasters.positions.posLevel",
            "posMasters.positions.posType",
            "posMasters.positions.posExecutive",
          ],
        });
        if (!orgChild2Data || orgChild2Data.length === 0) {
          throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล orgChild2");
        }
        orgName = orgChild2Data[0].orgChild2Name ?? "";
        // cascade ลูก
        const orgChild2Ids = orgChild2Data.map((c) => c.id) || null;
        const orgChild3Data = await this.child3Repository.find({
          where: { orgChild2: In(orgChild2Ids) },
          order: {
            orgChild3Order: "ASC",
            posMasters: {
              posMasterOrder: "ASC",
              posMasterCreatedAt: "ASC",
            },
          },
          relations: [
            "posMasters",
            "posMasters.positions",
            "posMasters.positions.posLevel",
            "posMasters.positions.posType",
            "posMasters.positions.posExecutive",
          ],
        });
        const orgChild3Ids = orgChild3Data.map((c) => c.id) || null;
        const orgChild4Data = await this.child4Repository.find({
          where: { orgChild3: In(orgChild3Ids) },
          order: {
            orgChild4Order: "ASC",
            posMasters: {
              posMasterOrder: "ASC",
              posMasterCreatedAt: "ASC",
            },
          },
          relations: [
            "posMasters",
            "posMasters.positions",
            "posMasters.positions.posLevel",
            "posMasters.positions.posType",
            "posMasters.positions.posExecutive",
          ],
        });
        let _nodeTemp: any = null;
        for (let orgChild2 of orgChild2Data) {
          await Promise.all(
            orgChild2.posMasters
              .filter((x) => x.orgChild3Id == null)
              .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
              .map(async (posMaster) => {
                if (posMaster.orgChild3Id == null) {
                  // --- push data logic (เหมือน node 0) ---
                  const positionName = [
                    ...new Set(
                      posMaster.positions
                        .sort((a: any, b: any) => a.orderNo - b.orderNo)
                        .map((x) =>
                          x.positionArea ? `${x.positionName} (${x.positionArea})` : x.positionName,
                        ),
                    ),
                  ];
                  const posType = [
                    ...new Set(
                      posMaster.positions
                        .filter((x: any) => x.posType != null)
                        .map((x) => x.posType.posTypeName),
                    ),
                  ];
                  const posLevel = [
                    ...new Set(
                      posMaster.positions
                        .filter((x: any) => x.posLevel != null)
                        .map((x) => x.posLevel.posLevelName),
                    ),
                  ];
                  const posExecutive = [
                    ...new Set(
                      posMaster.positions
                        .filter((x: any) => x.posExecutive != null)
                        .map((x: any) =>
                          x.positionExecutiveField
                            ? `${x.posExecutive.posExecutiveName} (${x.positionExecutiveField})`
                            : x.posExecutive.posExecutiveName,
                        ),
                    ),
                  ];
                  let node = {
                    orgTreeName: orgChild2.orgChild2Name,
                    orgTreeShortName: orgChild2.orgChild2ShortName,
                    posMasterNo: posMaster.posMasterNo,
                    positionName: positionName.join(" หรือ "),
                    posType: posType.join(" หรือ "),
                    posLevel: posLevel.join(" หรือ "),
                    posExecutive: posExecutive.join(" หรือ "),
                    reason: posMaster.reason == null ? "" : posMaster.reason,
                  };
                  if (_nodeTemp == null) {
                    const head = {
                      posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName?.toString() ?? ""),
                      posExecutive: Extension.ToThaiNumber(node.orgTreeName?.toString() ?? ""),
                      positionName: "",
                      posType: "",
                      posLevel: "",
                      reason: "",
                    };
                    data.push(head);
                    const _head = {
                      no: Extension.ToThaiNumber(no.toString()),
                      posMasterNo:
                        node.posMasterNo == null
                          ? ""
                          : Extension.ToThaiNumber(node.posMasterNo.toString()),
                      posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                      positionName: Extension.ToThaiNumber(node.positionName.toString()),
                      posType: Extension.ToThaiNumber(node.posType.toString()),
                      posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                      reason: Extension.ToThaiNumber(node.reason.toString()),
                    };
                    data.push(_head);
                  } else {
                    if (
                      node.orgTreeShortName != _nodeTemp.orgTreeShortName ||
                      node.orgTreeName != _nodeTemp.orgTreeName
                    ) {
                      const head = {
                        posMasterNo:
                          node.orgTreeShortName == _nodeTemp.orgTreeShortName
                            ? ""
                            : node.orgTreeShortName,
                        posExecutive:
                          node.orgTreeName == _nodeTemp.orgTreeName
                            ? ""
                            : Extension.ToThaiNumber(node.orgTreeName.toString()),
                        positionName: "",
                        posType: "",
                        posLevel: "",
                        reason: "",
                      };
                      data.push(head);
                      _nodeTemp = null;
                    }
                    const head = {
                      no: Extension.ToThaiNumber(no.toString()),
                      posMasterNo:
                        node.posMasterNo == null
                          ? ""
                          : Extension.ToThaiNumber(node.posMasterNo.toString()),
                      posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                      positionName: Extension.ToThaiNumber(node.positionName.toString()),
                      posType: Extension.ToThaiNumber(node.posType.toString()),
                      posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                      reason: Extension.ToThaiNumber(node.reason.toString()),
                    };
                    data.push(head);
                  }
                  no += 1;
                  _nodeTemp = node;
                }
              }),
          );
          for (let orgChild3 of orgChild3Data.filter(
            (orgChild3) => orgChild3.orgChild2Id === orgChild2.id,
          )) {
            await Promise.all(
              orgChild3.posMasters
                .filter((x) => x.orgChild4Id == null)
                .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
                .map(async (posMaster) => {
                  if (posMaster.orgChild4Id == null) {
                    // --- push data logic (เหมือน node 0) ---
                    const positionName = [
                      ...new Set(
                        posMaster.positions
                          .sort((a: any, b: any) => a.orderNo - b.orderNo)
                          .map((x) =>
                            x.positionArea
                              ? `${x.positionName} (${x.positionArea})`
                              : x.positionName,
                          ),
                      ),
                    ];
                    const posType = [
                      ...new Set(
                        posMaster.positions
                          .filter((x: any) => x.posType != null)
                          .map((x) => x.posType.posTypeName),
                      ),
                    ];
                    const posLevel = [
                      ...new Set(
                        posMaster.positions
                          .filter((x: any) => x.posLevel != null)
                          .map((x) => x.posLevel.posLevelName),
                      ),
                    ];
                    const posExecutive = [
                      ...new Set(
                        posMaster.positions
                          .filter((x: any) => x.posExecutive != null)
                          .map((x: any) =>
                            x.positionExecutiveField
                              ? `${x.posExecutive.posExecutiveName} (${x.positionExecutiveField})`
                              : x.posExecutive.posExecutiveName,
                          ),
                      ),
                    ];
                    let node = {
                      orgTreeName: orgChild3.orgChild3Name,
                      orgTreeShortName: orgChild3.orgChild3ShortName,
                      posMasterNo: posMaster.posMasterNo,
                      positionName: positionName.join(" หรือ "),
                      posType: posType.join(" หรือ "),
                      posLevel: posLevel.join(" หรือ "),
                      posExecutive: posExecutive.join(" หรือ "),
                      reason: posMaster.reason == null ? "" : posMaster.reason,
                    };
                    if (_nodeTemp == null) {
                      const head = {
                        posMasterNo: Extension.ToThaiNumber(
                          node.orgTreeShortName?.toString() ?? "",
                        ),
                        posExecutive: Extension.ToThaiNumber(node.orgTreeName?.toString() ?? ""),
                        positionName: "",
                        posType: "",
                        posLevel: "",
                        reason: "",
                      };
                      data.push(head);
                      const _head = {
                        no: Extension.ToThaiNumber(no.toString()),
                        posMasterNo:
                          node.posMasterNo == null
                            ? ""
                            : Extension.ToThaiNumber(node.posMasterNo.toString()),
                        posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                        positionName: Extension.ToThaiNumber(node.positionName.toString()),
                        posType: Extension.ToThaiNumber(node.posType.toString()),
                        posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                        reason: Extension.ToThaiNumber(node.reason.toString()),
                      };
                      data.push(_head);
                    } else {
                      if (
                        node.orgTreeShortName != _nodeTemp.orgTreeShortName ||
                        node.orgTreeName != _nodeTemp.orgTreeName
                      ) {
                        const head = {
                          posMasterNo:
                            node.orgTreeShortName == _nodeTemp.orgTreeShortName
                              ? ""
                              : node.orgTreeShortName,
                          posExecutive:
                            node.orgTreeName == _nodeTemp.orgTreeName
                              ? ""
                              : Extension.ToThaiNumber(node.orgTreeName.toString()),
                          positionName: "",
                          posType: "",
                          posLevel: "",
                          reason: "",
                        };
                        data.push(head);
                        _nodeTemp = null;
                      }
                      const head = {
                        no: Extension.ToThaiNumber(no.toString()),
                        posMasterNo:
                          node.posMasterNo == null
                            ? ""
                            : Extension.ToThaiNumber(node.posMasterNo.toString()),
                        posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                        positionName: Extension.ToThaiNumber(node.positionName.toString()),
                        posType: Extension.ToThaiNumber(node.posType.toString()),
                        posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                        reason: Extension.ToThaiNumber(node.reason.toString()),
                      };
                      data.push(head);
                    }
                    no += 1;
                    _nodeTemp = node;
                  }
                }),
            );
            for (let orgChild4 of orgChild4Data.filter(
              (orgChild4) => orgChild4.orgChild3Id === orgChild3.id,
            )) {
              await Promise.all(
                orgChild4.posMasters
                  .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
                  .map(async (posMaster) => {
                    // --- push data logic (เหมือน node 0) ---
                    const positionName = [
                      ...new Set(
                        posMaster.positions
                          .sort((a: any, b: any) => a.orderNo - b.orderNo)
                          .map((x) =>
                            x.positionArea
                              ? `${x.positionName} (${x.positionArea})`
                              : x.positionName,
                          ),
                      ),
                    ];
                    const posType = [
                      ...new Set(
                        posMaster.positions
                          .filter((x: any) => x.posType != null)
                          .map((x) => x.posType.posTypeName),
                      ),
                    ];
                    const posLevel = [
                      ...new Set(
                        posMaster.positions
                          .filter((x: any) => x.posLevel != null)
                          .map((x) => x.posLevel.posLevelName),
                      ),
                    ];
                    const posExecutive = [
                      ...new Set(
                        posMaster.positions
                          .filter((x: any) => x.posExecutive != null)
                          .map((x: any) =>
                            x.positionExecutiveField
                              ? `${x.posExecutive.posExecutiveName} (${x.positionExecutiveField})`
                              : x.posExecutive.posExecutiveName,
                          ),
                      ),
                    ];
                    let node = {
                      orgTreeName: orgChild4.orgChild4Name,
                      orgTreeShortName: orgChild4.orgChild4ShortName,
                      posMasterNo: posMaster.posMasterNo,
                      positionName: positionName.join(" หรือ "),
                      posType: posType.join(" หรือ "),
                      posLevel: posLevel.join(" หรือ "),
                      posExecutive: posExecutive.join(" หรือ "),
                      reason: posMaster.reason == null ? "" : posMaster.reason,
                    };
                    if (_nodeTemp == null) {
                      const head = {
                        posMasterNo: Extension.ToThaiNumber(
                          node.orgTreeShortName?.toString() ?? "",
                        ),
                        posExecutive: Extension.ToThaiNumber(node.orgTreeName?.toString() ?? ""),
                        positionName: "",
                        posType: "",
                        posLevel: "",
                        reason: "",
                      };
                      data.push(head);
                      const _head = {
                        no: Extension.ToThaiNumber(no.toString()),
                        posMasterNo:
                          node.posMasterNo == null
                            ? ""
                            : Extension.ToThaiNumber(node.posMasterNo.toString()),
                        posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                        positionName: Extension.ToThaiNumber(node.positionName.toString()),
                        posType: Extension.ToThaiNumber(node.posType.toString()),
                        posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                        reason: Extension.ToThaiNumber(node.reason.toString()),
                      };
                      data.push(_head);
                    } else {
                      if (
                        node.orgTreeShortName != _nodeTemp.orgTreeShortName ||
                        node.orgTreeName != _nodeTemp.orgTreeName
                      ) {
                        const head = {
                          posMasterNo:
                            node.orgTreeShortName == _nodeTemp.orgTreeShortName
                              ? ""
                              : node.orgTreeShortName,
                          posExecutive:
                            node.orgTreeName == _nodeTemp.orgTreeName
                              ? ""
                              : Extension.ToThaiNumber(node.orgTreeName.toString()),
                          positionName: "",
                          posType: "",
                          posLevel: "",
                          reason: "",
                        };
                        data.push(head);
                        _nodeTemp = null;
                      }
                      const head = {
                        no: Extension.ToThaiNumber(no.toString()),
                        posMasterNo:
                          node.posMasterNo == null
                            ? ""
                            : Extension.ToThaiNumber(node.posMasterNo.toString()),
                        posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                        positionName: Extension.ToThaiNumber(node.positionName.toString()),
                        posType: Extension.ToThaiNumber(node.posType.toString()),
                        posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                        reason: Extension.ToThaiNumber(node.reason.toString()),
                      };
                      data.push(head);
                    }
                    no += 1;
                    _nodeTemp = node;
                  }),
              );
            }
          }
        }
        break;
      }
      case 3: {
        // ดึง orgChild3 และลูก (orgChild4)
        const orgChild3Data = await this.child3Repository.find({
          where: { id: _nodeId },
          order: {
            orgChild3Order: "ASC",
            posMasters: {
              posMasterOrder: "ASC",
              posMasterCreatedAt: "ASC",
            },
          },
          relations: [
            "posMasters",
            "posMasters.positions",
            "posMasters.positions.posLevel",
            "posMasters.positions.posType",
            "posMasters.positions.posExecutive",
          ],
        });
        if (!orgChild3Data || orgChild3Data.length === 0) {
          throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล orgChild3");
        }
        orgName = orgChild3Data[0].orgChild3Name ?? "";
        // cascade ลูก
        const orgChild3Ids = orgChild3Data.map((c) => c.id) || null;
        const orgChild4Data = await this.child4Repository.find({
          where: { orgChild3: In(orgChild3Ids) },
          order: {
            orgChild4Order: "ASC",
            posMasters: {
              posMasterOrder: "ASC",
              posMasterCreatedAt: "ASC",
            },
          },
          relations: [
            "posMasters",
            "posMasters.positions",
            "posMasters.positions.posLevel",
            "posMasters.positions.posType",
            "posMasters.positions.posExecutive",
          ],
        });
        let _nodeTemp: any = null;
        for (let orgChild3 of orgChild3Data) {
          await Promise.all(
            orgChild3.posMasters
              .filter((x) => x.orgChild4Id == null)
              .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
              .map(async (posMaster) => {
                if (posMaster.orgChild4Id == null) {
                  // --- push data logic (เหมือน node 0) ---
                  const positionName = [
                    ...new Set(
                      posMaster.positions
                        .sort((a: any, b: any) => a.orderNo - b.orderNo)
                        .map((x) =>
                          x.positionArea ? `${x.positionName} (${x.positionArea})` : x.positionName,
                        ),
                    ),
                  ];
                  const posType = [
                    ...new Set(
                      posMaster.positions
                        .filter((x: any) => x.posType != null)
                        .map((x) => x.posType.posTypeName),
                    ),
                  ];
                  const posLevel = [
                    ...new Set(
                      posMaster.positions
                        .filter((x: any) => x.posLevel != null)
                        .map((x) => x.posLevel.posLevelName),
                    ),
                  ];
                  const posExecutive = [
                    ...new Set(
                      posMaster.positions
                        .filter((x: any) => x.posExecutive != null)
                        .map((x: any) =>
                          x.positionExecutiveField
                            ? `${x.posExecutive.posExecutiveName} (${x.positionExecutiveField})`
                            : x.posExecutive.posExecutiveName,
                        ),
                    ),
                  ];
                  let node = {
                    orgTreeName: orgChild3.orgChild3Name,
                    orgTreeShortName: orgChild3.orgChild3ShortName,
                    posMasterNo: posMaster.posMasterNo,
                    positionName: positionName.join(" หรือ "),
                    posType: posType.join(" หรือ "),
                    posLevel: posLevel.join(" หรือ "),
                    posExecutive: posExecutive.join(" หรือ "),
                    reason: posMaster.reason == null ? "" : posMaster.reason,
                  };
                  if (_nodeTemp == null) {
                    const head = {
                      posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName?.toString() ?? ""),
                      posExecutive: Extension.ToThaiNumber(node.orgTreeName?.toString() ?? ""),
                      positionName: "",
                      posType: "",
                      posLevel: "",
                      reason: "",
                    };
                    data.push(head);
                    const _head = {
                      no: Extension.ToThaiNumber(no.toString()),
                      posMasterNo:
                        node.posMasterNo == null
                          ? ""
                          : Extension.ToThaiNumber(node.posMasterNo.toString()),
                      posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                      positionName: Extension.ToThaiNumber(node.positionName.toString()),
                      posType: Extension.ToThaiNumber(node.posType.toString()),
                      posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                      reason: Extension.ToThaiNumber(node.reason.toString()),
                    };
                    data.push(_head);
                  } else {
                    if (
                      node.orgTreeShortName != _nodeTemp.orgTreeShortName ||
                      node.orgTreeName != _nodeTemp.orgTreeName
                    ) {
                      const head = {
                        posMasterNo:
                          node.orgTreeShortName == _nodeTemp.orgTreeShortName
                            ? ""
                            : node.orgTreeShortName,
                        posExecutive:
                          node.orgTreeName == _nodeTemp.orgTreeName
                            ? ""
                            : Extension.ToThaiNumber(node.orgTreeName.toString()),
                        positionName: "",
                        posType: "",
                        posLevel: "",
                        reason: "",
                      };
                      data.push(head);
                      _nodeTemp = null;
                    }
                    const head = {
                      no: Extension.ToThaiNumber(no.toString()),
                      posMasterNo:
                        node.posMasterNo == null
                          ? ""
                          : Extension.ToThaiNumber(node.posMasterNo.toString()),
                      posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                      positionName: Extension.ToThaiNumber(node.positionName.toString()),
                      posType: Extension.ToThaiNumber(node.posType.toString()),
                      posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                      reason: Extension.ToThaiNumber(node.reason.toString()),
                    };
                    data.push(head);
                  }
                  no += 1;
                  _nodeTemp = node;
                }
              }),
          );
          for (let orgChild4 of orgChild4Data.filter(
            (orgChild4) => orgChild4.orgChild3Id === orgChild3.id,
          )) {
            await Promise.all(
              orgChild4.posMasters
                .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
                .map(async (posMaster) => {
                  // --- push data logic (เหมือน node 0) ---
                  const positionName = [
                    ...new Set(
                      posMaster.positions
                        .sort((a: any, b: any) => a.orderNo - b.orderNo)
                        .map((x) =>
                          x.positionArea ? `${x.positionName} (${x.positionArea})` : x.positionName,
                        ),
                    ),
                  ];
                  const posType = [
                    ...new Set(
                      posMaster.positions
                        .filter((x: any) => x.posType != null)
                        .map((x) => x.posType.posTypeName),
                    ),
                  ];
                  const posLevel = [
                    ...new Set(
                      posMaster.positions
                        .filter((x: any) => x.posLevel != null)
                        .map((x) => x.posLevel.posLevelName),
                    ),
                  ];
                  const posExecutive = [
                    ...new Set(
                      posMaster.positions
                        .filter((x: any) => x.posExecutive != null)
                        .map((x: any) =>
                          x.positionExecutiveField
                            ? `${x.posExecutive.posExecutiveName} (${x.positionExecutiveField})`
                            : x.posExecutive.posExecutiveName,
                        ),
                    ),
                  ];
                  let node = {
                    orgTreeName: orgChild4.orgChild4Name,
                    orgTreeShortName: orgChild4.orgChild4ShortName,
                    posMasterNo: posMaster.posMasterNo,
                    positionName: positionName.join(" หรือ "),
                    posType: posType.join(" หรือ "),
                    posLevel: posLevel.join(" หรือ "),
                    posExecutive: posExecutive.join(" หรือ "),
                    reason: posMaster.reason == null ? "" : posMaster.reason,
                  };
                  if (_nodeTemp == null) {
                    const head = {
                      posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName?.toString() ?? ""),
                      posExecutive: Extension.ToThaiNumber(node.orgTreeName?.toString() ?? ""),
                      positionName: "",
                      posType: "",
                      posLevel: "",
                      reason: "",
                    };
                    data.push(head);
                    const _head = {
                      no: Extension.ToThaiNumber(no.toString()),
                      posMasterNo:
                        node.posMasterNo == null
                          ? ""
                          : Extension.ToThaiNumber(node.posMasterNo.toString()),
                      posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                      positionName: Extension.ToThaiNumber(node.positionName.toString()),
                      posType: Extension.ToThaiNumber(node.posType.toString()),
                      posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                      reason: Extension.ToThaiNumber(node.reason.toString()),
                    };
                    data.push(_head);
                  } else {
                    if (
                      node.orgTreeShortName != _nodeTemp.orgTreeShortName ||
                      node.orgTreeName != _nodeTemp.orgTreeName
                    ) {
                      const head = {
                        posMasterNo:
                          node.orgTreeShortName == _nodeTemp.orgTreeShortName
                            ? ""
                            : node.orgTreeShortName,
                        posExecutive:
                          node.orgTreeName == _nodeTemp.orgTreeName
                            ? ""
                            : Extension.ToThaiNumber(node.orgTreeName.toString()),
                        positionName: "",
                        posType: "",
                        posLevel: "",
                        reason: "",
                      };
                      data.push(head);
                      _nodeTemp = null;
                    }
                    const head = {
                      no: Extension.ToThaiNumber(no.toString()),
                      posMasterNo:
                        node.posMasterNo == null
                          ? ""
                          : Extension.ToThaiNumber(node.posMasterNo.toString()),
                      posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                      positionName: Extension.ToThaiNumber(node.positionName.toString()),
                      posType: Extension.ToThaiNumber(node.posType.toString()),
                      posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                      reason: Extension.ToThaiNumber(node.reason.toString()),
                    };
                    data.push(head);
                  }
                  no += 1;
                  _nodeTemp = node;
                }),
            );
          }
        }
        break;
      }
      case 4: {
        // ดึงข้อมูล orgChild4 ตาม nodeId
        const orgChild4Data = await this.child4Repository.find({
          where: { id: _nodeId },
          order: {
            orgChild4Order: "ASC",
            posMasters: {
              posMasterOrder: "ASC",
              posMasterCreatedAt: "ASC",
            },
          },
          relations: [
            "posMasters",
            "posMasters.positions",
            "posMasters.positions.posLevel",
            "posMasters.positions.posType",
            "posMasters.positions.posExecutive",
          ],
        });
        if (!orgChild4Data || orgChild4Data.length === 0) {
          throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล orgChild4");
        }
        orgName = orgChild4Data[0].orgChild4Name ?? "";
        let _nodeTemp: any = null;
        for (let orgChild4 of orgChild4Data) {
          await Promise.all(
            orgChild4.posMasters
              .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
              .map(async (posMaster) => {
                const positionName = [
                  ...new Set(
                    posMaster.positions
                      .sort((a: any, b: any) => a.orderNo - b.orderNo)
                      .map((x) =>
                        x.positionArea ? `${x.positionName} (${x.positionArea})` : x.positionName,
                      ),
                  ),
                ];
                const posType = [
                  ...new Set(
                    posMaster.positions
                      .filter((x: any) => x.posType != null)
                      .map((x) => x.posType.posTypeName),
                  ),
                ];
                const posLevel = [
                  ...new Set(
                    posMaster.positions
                      .filter((x: any) => x.posLevel != null)
                      .map((x) => x.posLevel.posLevelName),
                  ),
                ];
                const posExecutive = [
                  ...new Set(
                    posMaster.positions
                      .filter((x: any) => x.posExecutive != null)
                      .map((x: any) =>
                        x.positionExecutiveField
                          ? `${x.posExecutive.posExecutiveName} (${x.positionExecutiveField})`
                          : x.posExecutive.posExecutiveName,
                      ),
                  ),
                ];

                let node = {
                  orgTreeName: orgChild4.orgChild4Name,
                  orgTreeShortName: orgChild4.orgChild4ShortName,
                  posMasterNo: posMaster.posMasterNo,
                  positionName: positionName.join(" หรือ "),
                  posType: posType.join(" หรือ "),
                  posLevel: posLevel.join(" หรือ "),
                  posExecutive: posExecutive.join(" หรือ "),
                  reason: posMaster.reason == null ? "" : posMaster.reason,
                };
                if (_nodeTemp == null) {
                  const head = {
                    posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName?.toString() ?? ""),
                    posExecutive: Extension.ToThaiNumber(node.orgTreeName?.toString() ?? ""),
                    positionName: "",
                    posType: "",
                    posLevel: "",
                    reason: "",
                  };
                  data.push(head);
                  const _head = {
                    no: Extension.ToThaiNumber(no.toString()),
                    posMasterNo:
                      node.posMasterNo == null
                        ? ""
                        : Extension.ToThaiNumber(node.posMasterNo.toString()),
                    posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                    positionName: Extension.ToThaiNumber(node.positionName.toString()),
                    posType: Extension.ToThaiNumber(node.posType.toString()),
                    posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                    reason: Extension.ToThaiNumber(node.reason.toString()),
                  };
                  data.push(_head);
                } else {
                  if (
                    node.orgTreeShortName != _nodeTemp.orgTreeShortName ||
                    node.orgTreeName != _nodeTemp.orgTreeName
                  ) {
                    const head = {
                      posMasterNo:
                        node.orgTreeShortName == _nodeTemp.orgTreeShortName
                          ? ""
                          : node.orgTreeShortName,
                      posExecutive:
                        node.orgTreeName == _nodeTemp.orgTreeName
                          ? ""
                          : Extension.ToThaiNumber(node.orgTreeName.toString()),
                      positionName: "",
                      posType: "",
                      posLevel: "",
                      reason: "",
                    };
                    data.push(head);
                    _nodeTemp = null;
                  }
                  const head = {
                    no: Extension.ToThaiNumber(no.toString()),
                    posMasterNo:
                      node.posMasterNo == null
                        ? ""
                        : Extension.ToThaiNumber(node.posMasterNo.toString()),
                    posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                    positionName: Extension.ToThaiNumber(node.positionName.toString()),
                    posType: Extension.ToThaiNumber(node.posType.toString()),
                    posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                    reason: Extension.ToThaiNumber(node.reason.toString()),
                  };
                  data.push(head);
                }
                no += 1;
                _nodeTemp = node;
              }),
          );
        }
        break;
      }
      default: {
        throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
      }
    }

    return new HttpSuccess({
      template: "report1",
      reportName: "report1",
      data: { org: orgName, data },
    });
  }

  /**
   * API Report1
   *
   * @summary Report1
   *
   */
  @Get("report1/{rootId}")
  async findReport1(@Path() rootId: string) {
    // const orgRevision = await this.orgRevisionRepository.findOne({
    //   where: { orgRevisionIsDraft: true, orgRevisionIsCurrent: false },
    //   relations: ["orgRoots"],
    // });
    // if (!orgRevision) {
    //   throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
    // }

    const orgRootData = await this.orgRootRepository.find({
      where: {
        id: rootId,
        // orgRevisionId: orgRevision.id,
      },
      order: { orgRootOrder: "ASC" },
      relations: [
        "posMasters",
        "posMasters.positions",
        "posMasters.positions.posLevel",
        "posMasters.positions.posType",
        "posMasters.positions.posExecutive",
      ],
    });
    const orgName = orgRootData[0].orgRootName ?? "";
    const orgRootIds = orgRootData.map((orgRoot) => orgRoot.id) || null;
    const orgChild1Data = await this.child1Repository.find({
      where: {
        orgRootId: In(orgRootIds),
      },
      order: { orgChild1Order: "ASC" },
      relations: [
        "posMasters",
        "posMasters.positions",
        "posMasters.positions.posLevel",
        "posMasters.positions.posType",
        "posMasters.positions.posExecutive",
      ],
    });

    const orgChild1Ids = orgChild1Data.map((orgChild1) => orgChild1.id) || null;
    const orgChild2Data = await this.child2Repository.find({
      where: {
        orgChild1: In(orgChild1Ids),
      },
      order: { orgChild2Order: "ASC" },
      relations: [
        "posMasters",
        "posMasters.positions",
        "posMasters.positions.posLevel",
        "posMasters.positions.posType",
        "posMasters.positions.posExecutive",
      ],
    });

    const orgChild2Ids = orgChild2Data.map((orgChild2) => orgChild2.id) || null;
    const orgChild3Data = await this.child3Repository.find({
      where: {
        orgChild2: In(orgChild2Ids),
      },
      order: { orgChild3Order: "ASC" },
      relations: [
        "posMasters",
        "posMasters.positions",
        "posMasters.positions.posLevel",
        "posMasters.positions.posType",
        "posMasters.positions.posExecutive",
      ],
    });

    const orgChild3Ids = orgChild3Data.map((orgChild3) => orgChild3.id) || null;
    const orgChild4Data = await this.child4Repository.find({
      where: {
        orgChild3: In(orgChild3Ids),
      },
      order: { orgChild4Order: "ASC" },
      relations: [
        "posMasters",
        "posMasters.positions",
        "posMasters.positions.posLevel",
        "posMasters.positions.posType",
        "posMasters.positions.posExecutive",
      ],
    });

    let data = new Array();
    let _node: any;
    let no = 1;
    for (let orgRoot of orgRootData) {
      await Promise.all(
        orgRoot.posMasters
          .filter((x) => x.orgChild1Id == null)
          .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
          .map(async (posMaster) => {
            if (posMaster.orgChild1Id == null) {
              const positionName = [
                ...new Set(
                  posMaster.positions
                    .sort((a: any, b: any) => a.orderNo - b.orderNo)
                    .map((x) =>
                      x.positionArea ? `${x.positionName} (${x.positionArea})` : x.positionName,
                    ),
                ),
              ];
              const posType = [
                ...new Set(
                  posMaster.positions
                    .filter((x: any) => x.posType != null)
                    .map((x) => x.posType.posTypeName),
                ),
              ];
              const posLevel = [
                ...new Set(
                  posMaster.positions
                    .filter((x: any) => x.posLevel != null)
                    .map((x) => x.posLevel.posLevelName),
                ),
              ];
              const posExecutive = [
                ...new Set(
                  posMaster.positions
                    .filter((x: any) => x.posExecutive != null)
                    .map((x: any) =>
                      x.positionExecutiveField
                        ? `${x.posExecutive.posExecutiveName} (${x.positionExecutiveField})`
                        : x.posExecutive.posExecutiveName,
                    ),
                ),
              ];

              let node = {
                orgTreeName: orgRoot.orgRootName,
                orgTreeShortName: orgRoot.orgRootShortName,
                posMasterNo: posMaster.posMasterNo,
                positionName: positionName.join(" หรือ "),
                posType: posType.join(" หรือ "),
                posLevel: posLevel.join(" หรือ "),
                posExecutive: posExecutive.join(" หรือ "),
                reason: posMaster.reason == null ? "" : posMaster.reason,
              };
              if (_node == null) {
                const head = {
                  posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName.toString()),
                  posExecutive: Extension.ToThaiNumber(node.orgTreeName.toString()),
                  positionName: "",
                  posType: "",
                  posLevel: "",
                  reason: "",
                };
                data.push(head);
                const _head = {
                  no: Extension.ToThaiNumber(no.toString()),
                  posMasterNo:
                    node.posMasterNo == null
                      ? ""
                      : Extension.ToThaiNumber(node.posMasterNo.toString()),
                  posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                  positionName: Extension.ToThaiNumber(node.positionName.toString()),
                  posType: Extension.ToThaiNumber(node.posType.toString()),
                  posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                  reason: Extension.ToThaiNumber(node.reason.toString()),
                };
                data.push(_head);
              } else {
                if (
                  node.orgTreeShortName != _node.orgTreeShortName ||
                  node.orgTreeName != _node.orgTreeName
                ) {
                  const head = {
                    posMasterNo:
                      node.orgTreeShortName == _node.orgTreeShortName ? "" : node.orgTreeShortName,
                    posExecutive:
                      node.orgTreeName == _node.orgTreeName
                        ? ""
                        : Extension.ToThaiNumber(node.orgTreeName.toString()),
                    positionName: "",
                    posType: "",
                    posLevel: "",
                    reason: "",
                  };
                  data.push(head);
                  _node == null;
                }
                const head = {
                  no: Extension.ToThaiNumber(no.toString()),
                  posMasterNo:
                    node.posMasterNo == null
                      ? ""
                      : Extension.ToThaiNumber(node.posMasterNo.toString()),
                  posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                  positionName: Extension.ToThaiNumber(node.positionName.toString()),
                  posType: Extension.ToThaiNumber(node.posType.toString()),
                  posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                  reason: Extension.ToThaiNumber(node.reason.toString()),
                };
                data.push(head);
              }
              no += 1;
              _node = node;
            }
          }),
      );
      _node = null;

      for (let orgChild1 of orgChild1Data.filter(
        (orgChild1) => orgChild1.orgRootId === orgRoot.id,
      )) {
        await Promise.all(
          orgChild1.posMasters
            .filter((x) => x.orgChild2Id == null)
            .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
            .map(async (posMaster) => {
              if (posMaster.orgChild2Id == null) {
                const positionName = [
                  ...new Set(
                    posMaster.positions
                      .sort((a: any, b: any) => a.orderNo - b.orderNo)
                      .map((x) =>
                        x.positionArea ? `${x.positionName} (${x.positionArea})` : x.positionName,
                      ),
                  ),
                ];
                const posType = [
                  ...new Set(
                    posMaster.positions
                      .filter((x: any) => x.posType != null)
                      .map((x) => x.posType.posTypeName),
                  ),
                ];
                const posLevel = [
                  ...new Set(
                    posMaster.positions
                      .filter((x: any) => x.posLevel != null)
                      .map((x) => x.posLevel.posLevelName),
                  ),
                ];
                const posExecutive = [
                  ...new Set(
                    posMaster.positions
                      .filter((x: any) => x.posExecutive != null)
                      .map((x: any) =>
                        x.positionExecutiveField
                          ? `${x.posExecutive.posExecutiveName} (${x.positionExecutiveField})`
                          : x.posExecutive.posExecutiveName,
                      ),
                  ),
                ];

                let node = {
                  orgTreeName: orgChild1.orgChild1Name,
                  orgTreeShortName: orgChild1.orgChild1ShortName,
                  posMasterNo: posMaster.posMasterNo,
                  positionName: positionName.join(" หรือ "),
                  posType: posType.join(" หรือ "),
                  posLevel: posLevel.join(" หรือ "),
                  posExecutive: posExecutive.join(" หรือ "),
                  reason: posMaster.reason == null ? "" : posMaster.reason,
                };
                if (_node == null) {
                  const head = {
                    posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName.toString()),
                    posExecutive: Extension.ToThaiNumber(node.orgTreeName.toString()),
                    positionName: "",
                    posType: "",
                    posLevel: "",
                    reason: "",
                  };
                  data.push(head);
                  const _head = {
                    no: Extension.ToThaiNumber(no.toString()),
                    posMasterNo:
                      node.posMasterNo == null
                        ? ""
                        : Extension.ToThaiNumber(node.posMasterNo.toString()),
                    posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                    positionName: Extension.ToThaiNumber(node.positionName.toString()),
                    posType: Extension.ToThaiNumber(node.posType.toString()),
                    posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                    reason: Extension.ToThaiNumber(node.reason.toString()),
                  };
                  data.push(_head);
                } else {
                  if (
                    node.orgTreeShortName != _node.orgTreeShortName ||
                    node.orgTreeName != _node.orgTreeName
                  ) {
                    const head = {
                      posMasterNo:
                        node.orgTreeShortName == _node.orgTreeShortName
                          ? ""
                          : node.orgTreeShortName,
                      posExecutive:
                        node.orgTreeName == _node.orgTreeName
                          ? ""
                          : Extension.ToThaiNumber(node.orgTreeName.toString()),
                      positionName: "",
                      posType: "",
                      posLevel: "",
                      reason: "",
                    };
                    data.push(head);
                    _node == null;
                  }
                  const head = {
                    no: Extension.ToThaiNumber(no.toString()),
                    posMasterNo:
                      node.posMasterNo == null
                        ? ""
                        : Extension.ToThaiNumber(node.posMasterNo.toString()),
                    posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                    positionName: Extension.ToThaiNumber(node.positionName.toString()),
                    posType: Extension.ToThaiNumber(node.posType.toString()),
                    posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                    reason: Extension.ToThaiNumber(node.reason.toString()),
                  };
                  data.push(head);
                }
                no += 1;
                _node = node;
              }
            }),
        );
        _node = null;

        for (let orgChild2 of orgChild2Data.filter(
          (orgChild2) => orgChild2.orgChild1Id === orgChild1.id,
        )) {
          await Promise.all(
            orgChild2.posMasters
              .filter((x) => x.orgChild3Id == null)
              .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
              .map(async (posMaster) => {
                if (posMaster.orgChild3Id == null) {
                  const positionName = [
                    ...new Set(
                      posMaster.positions
                        .sort((a: any, b: any) => a.orderNo - b.orderNo)
                        .map((x) =>
                          x.positionArea ? `${x.positionName} (${x.positionArea})` : x.positionName,
                        ),
                    ),
                  ];
                  const posType = [
                    ...new Set(
                      posMaster.positions
                        .filter((x: any) => x.posType != null)
                        .map((x) => x.posType.posTypeName),
                    ),
                  ];
                  const posLevel = [
                    ...new Set(
                      posMaster.positions
                        .filter((x: any) => x.posLevel != null)
                        .map((x) => x.posLevel.posLevelName),
                    ),
                  ];
                  const posExecutive = [
                    ...new Set(
                      posMaster.positions
                        .filter((x: any) => x.posExecutive != null)
                        .map((x: any) =>
                          x.positionExecutiveField
                            ? `${x.posExecutive.posExecutiveName} (${x.positionExecutiveField})`
                            : x.posExecutive.posExecutiveName,
                        ),
                    ),
                  ];

                  let node = {
                    orgTreeName: orgChild2.orgChild2Name,
                    orgTreeShortName: orgChild2.orgChild2ShortName,
                    posMasterNo: posMaster.posMasterNo,
                    posExecutive: posExecutive.join(" หรือ "),
                    positionName: positionName.join(" หรือ "),
                    posType: posType.join(" หรือ "),
                    posLevel: posLevel.join(" หรือ "),
                    reason: posMaster.reason == null ? "" : posMaster.reason,
                  };
                  if (_node == null) {
                    const head = {
                      posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName.toString()),
                      posExecutive: Extension.ToThaiNumber(node.orgTreeName.toString()),
                      positionName: "",
                      posType: "",
                      posLevel: "",
                      reason: "",
                    };
                    data.push(head);
                    const _head = {
                      no: Extension.ToThaiNumber(no.toString()),
                      posMasterNo:
                        node.posMasterNo == null
                          ? ""
                          : Extension.ToThaiNumber(node.posMasterNo.toString()),
                      posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                      positionName: Extension.ToThaiNumber(node.positionName.toString()),
                      posType: Extension.ToThaiNumber(node.posType.toString()),
                      posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                      reason: Extension.ToThaiNumber(node.reason.toString()),
                    };
                    data.push(_head);
                  } else {
                    if (
                      node.orgTreeShortName != _node.orgTreeShortName ||
                      node.orgTreeName != _node.orgTreeName
                    ) {
                      const head = {
                        posMasterNo:
                          node.orgTreeShortName == _node.orgTreeShortName
                            ? ""
                            : node.orgTreeShortName,
                        posExecutive: node.orgTreeName == _node.orgTreeName ? "" : node.orgTreeName,
                        positionName: "",
                        posType: "",
                        posLevel: "",
                        reason: "",
                      };
                      data.push(head);
                      _node == null;
                    }
                    const head = {
                      no: Extension.ToThaiNumber(no.toString()),
                      posMasterNo:
                        node.posMasterNo == null
                          ? ""
                          : Extension.ToThaiNumber(node.posMasterNo.toString()),
                      posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                      positionName: Extension.ToThaiNumber(node.positionName.toString()),
                      posType: Extension.ToThaiNumber(node.posType.toString()),
                      posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                      reason: Extension.ToThaiNumber(node.reason.toString()),
                    };
                    data.push(head);
                  }
                  no += 1;
                  _node = node;
                }
              }),
          );
          _node = null;

          for (let orgChild3 of orgChild3Data.filter(
            (orgChild3) => orgChild3.orgChild2Id === orgChild2.id,
          )) {
            await Promise.all(
              orgChild3.posMasters
                .filter((x) => x.orgChild4Id == null)
                .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
                .map(async (posMaster) => {
                  if (posMaster.orgChild4Id == null) {
                    const positionName = [
                      ...new Set(
                        posMaster.positions
                          .sort((a: any, b: any) => a.orderNo - b.orderNo)
                          .map((x) =>
                            x.positionArea
                              ? `${x.positionName} (${x.positionArea})`
                              : x.positionName,
                          ),
                      ),
                    ];
                    const posType = [
                      ...new Set(
                        posMaster.positions
                          .filter((x: any) => x.posType != null)
                          .map((x) => x.posType.posTypeName),
                      ),
                    ];
                    const posLevel = [
                      ...new Set(
                        posMaster.positions
                          .filter((x: any) => x.posLevel != null)
                          .map((x) => x.posLevel.posLevelName),
                      ),
                    ];
                    const posExecutive = [
                      ...new Set(
                        posMaster.positions
                          .filter((x: any) => x.posExecutive != null)
                          .map((x: any) =>
                            x.positionExecutiveField
                              ? `${x.posExecutive.posExecutiveName} (${x.positionExecutiveField})`
                              : x.posExecutive.posExecutiveName,
                          ),
                      ),
                    ];

                    let node = {
                      orgTreeName: orgChild3.orgChild3Name,
                      orgTreeShortName: orgChild3.orgChild3ShortName,
                      posMasterNo: posMaster.posMasterNo,
                      positionName: positionName.join(" หรือ "),
                      posType: posType.join(" หรือ "),
                      posLevel: posLevel.join(" หรือ "),
                      posExecutive: posExecutive.join(" หรือ "),
                      reason: posMaster.reason == null ? "" : posMaster.reason,
                    };
                    if (_node == null) {
                      const head = {
                        posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName.toString()),
                        posExecutive: Extension.ToThaiNumber(node.orgTreeName.toString()),
                        positionName: "",
                        posType: "",
                        posLevel: "",
                        reason: "",
                      };
                      data.push(head);
                      const _head = {
                        no: Extension.ToThaiNumber(no.toString()),
                        posMasterNo:
                          node.posMasterNo == null
                            ? ""
                            : Extension.ToThaiNumber(node.posMasterNo.toString()),
                        posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                        positionName: Extension.ToThaiNumber(node.positionName.toString()),
                        posType: Extension.ToThaiNumber(node.posType.toString()),
                        posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                        reason: Extension.ToThaiNumber(node.reason.toString()),
                      };
                      data.push(_head);
                    } else {
                      if (
                        node.orgTreeShortName != _node.orgTreeShortName ||
                        node.orgTreeName != _node.orgTreeName
                      ) {
                        const head = {
                          posMasterNo:
                            node.orgTreeShortName == _node.orgTreeShortName
                              ? ""
                              : node.orgTreeShortName,
                          posExecutive:
                            node.orgTreeName == _node.orgTreeName ? "" : node.orgTreeName,
                          positionName: "",
                          posType: "",
                          posLevel: "",
                          reason: "",
                        };
                        data.push(head);
                        _node == null;
                      }
                      const head = {
                        no: Extension.ToThaiNumber(no.toString()),
                        posMasterNo:
                          node.posMasterNo == null
                            ? ""
                            : Extension.ToThaiNumber(node.posMasterNo.toString()),
                        posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                        positionName: Extension.ToThaiNumber(node.positionName.toString()),
                        posType: Extension.ToThaiNumber(node.posType.toString()),
                        posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                        reason: Extension.ToThaiNumber(node.reason.toString()),
                      };
                      data.push(head);
                    }
                    no += 1;
                    _node = node;
                  }
                }),
            );
            _node = null;

            for (let orgChild4 of orgChild4Data.filter(
              (orgChild4) => orgChild4.orgChild3Id === orgChild3.id,
            )) {
              await Promise.all(
                orgChild4.posMasters
                  .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
                  .map(async (posMaster) => {
                    const positionName = [
                      ...new Set(
                        posMaster.positions
                          .sort((a: any, b: any) => a.orderNo - b.orderNo)
                          .map((x) =>
                            x.positionArea
                              ? `${x.positionName} (${x.positionArea})`
                              : x.positionName,
                          ),
                      ),
                    ];
                    const posType = [
                      ...new Set(
                        posMaster.positions
                          .filter((x: any) => x.posType != null)
                          .map((x) => x.posType.posTypeName),
                      ),
                    ];
                    const posLevel = [
                      ...new Set(
                        posMaster.positions
                          .filter((x: any) => x.posLevel != null)
                          .map((x) => x.posLevel.posLevelName),
                      ),
                    ];
                    const posExecutive = [
                      ...new Set(
                        posMaster.positions
                          .filter((x: any) => x.posExecutive != null)
                          .map((x: any) =>
                            x.positionExecutiveField
                              ? `${x.posExecutive.posExecutiveName} (${x.positionExecutiveField})`
                              : x.posExecutive.posExecutiveName,
                          ),
                      ),
                    ];

                    let node = {
                      orgTreeName: orgChild4.orgChild4Name,
                      orgTreeShortName: orgChild4.orgChild4ShortName,
                      posMasterNo: posMaster.posMasterNo,
                      positionName: positionName.join(" หรือ "),
                      posType: posType.join(" หรือ "),
                      posLevel: posLevel.join(" หรือ "),
                      posExecutive: posExecutive.join(" หรือ "),
                      reason: posMaster.reason == null ? "" : posMaster.reason,
                    };
                    if (_node == null) {
                      const head = {
                        posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName.toString()),
                        posExecutive: Extension.ToThaiNumber(node.orgTreeName.toString()),
                        positionName: "",
                        posType: "",
                        posLevel: "",
                        reason: "",
                      };
                      data.push(head);
                      const _head = {
                        no: Extension.ToThaiNumber(no.toString()),
                        posMasterNo:
                          node.posMasterNo == null
                            ? ""
                            : Extension.ToThaiNumber(node.posMasterNo.toString()),
                        posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                        positionName: Extension.ToThaiNumber(node.positionName.toString()),
                        posType: Extension.ToThaiNumber(node.posType.toString()),
                        posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                        reason: Extension.ToThaiNumber(node.reason.toString()),
                      };
                      data.push(_head);
                    } else {
                      if (
                        node.orgTreeShortName != _node.orgTreeShortName ||
                        node.orgTreeName != _node.orgTreeName
                      ) {
                        const head = {
                          posMasterNo:
                            node.orgTreeShortName == _node.orgTreeShortName
                              ? ""
                              : node.orgTreeShortName,
                          posExecutive:
                            node.orgTreeName == _node.orgTreeName ? "" : node.orgTreeName,
                          positionName: "",
                          posType: "",
                          posLevel: "",
                          reason: "",
                        };
                        data.push(head);
                        _node == null;
                      }
                      const head = {
                        no: Extension.ToThaiNumber(no.toString()),
                        posMasterNo:
                          node.posMasterNo == null
                            ? ""
                            : Extension.ToThaiNumber(node.posMasterNo.toString()),
                        posExecutive: Extension.ToThaiNumber(node.posExecutive.toString()),
                        positionName: Extension.ToThaiNumber(node.positionName.toString()),
                        posType: Extension.ToThaiNumber(node.posType.toString()),
                        posLevel: Extension.ToThaiNumber(node.posLevel.toString()),
                        reason: Extension.ToThaiNumber(node.reason.toString()),
                      };
                      data.push(head);
                    }
                    no += 1;
                    _node = node;
                  }),
              );
              _node = null;
            }
          }
        }
      }
    }

    return new HttpSuccess({
      template: "report1",
      reportName: "report1",
      data: { org: orgName, data },
    });
  }

  /**
   * API Report2
   *
   * @summary Report2
   *
   */
  @Post("report2")
  async NewReport2(
    @Body()
    reqBody: {
      node: number;
      nodeId: string;
    },
  ) {
    // @Get("report2/{rootId}")
    // async findReport2(@Path() rootId: string) {
    // const orgRevision = await this.orgRevisionRepository.findOne({
    //   where: { orgRevisionIsDraft: true, orgRevisionIsCurrent: false },
    //   relations: ["orgRoots"],
    // });
    // if (!orgRevision) {
    //   throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
    // }
    // (async () => {
    let nodeId: string = reqBody.nodeId ? reqBody.nodeId : "";
    let node: number = reqBody.node ? reqBody.node : 0;
    if (nodeId === "" || node < 0 || node > 4) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
    }
    // ดึงแค่ rootId ก่อน ถ้าลูกค้า confirm ค่อยปรับ
    switch (node) {
      case 0: {
        const orgRoot = await this.orgRootRepository.findOne({
          select: ["id"],
          where: { id: nodeId },
        });
        if (!orgRoot) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
        nodeId = orgRoot.id;
        break;
      }
      case 1: {
        const orgChild1 = await this.child1Repository.findOne({
          select: ["id", "orgRootId"],
          where: { id: nodeId },
        });
        if (!orgChild1) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
        nodeId = orgChild1.orgRootId;
        break;
      }
      case 2: {
        const orgChild2 = await this.child2Repository.findOne({
          select: ["id", "orgRootId"],
          where: { id: nodeId },
        });
        if (!orgChild2) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
        nodeId = orgChild2.orgRootId;
        break;
      }
      case 3: {
        const orgChild3 = await this.child3Repository.findOne({
          select: ["id", "orgRootId"],
          where: { id: nodeId },
        });
        if (!orgChild3) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
        nodeId = orgChild3.orgRootId;
        break;
      }
      case 4: {
        const orgChild4 = await this.child4Repository.findOne({
          select: ["id", "orgRootId"],
          where: { id: nodeId },
        });
        if (!orgChild4) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
        nodeId = orgChild4.orgRootId;
        break;
      }
      default:
        throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
    }
    // Step 1: ดึงข้อมูล OrgRoot พื้นฐาน
    const orgRootData = await this.orgRootRepository
      .createQueryBuilder("orgRoot")
      .select([
        "orgRoot.id",
        "orgRoot.orgRootName",
        "orgRoot.orgRootShortName",
        "orgRoot.orgRootOrder",
      ])
      .where("orgRoot.id = :nodeId", { nodeId })
      .orderBy("orgRoot.orgRootOrder", "ASC")
      .getMany();

    if (!orgRootData || orgRootData.length === 0) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลองค์กร");
    }

    // Step 2: ดึงข้อมูล PosMasters ที่เกี่ยวข้องเท่านั้น
    const posMastersData = await this.posMasterRepository
      .createQueryBuilder("posMaster")
      .select([
        "posMaster.id",
        "posMaster.posMasterOrder",
        "posMaster.isSit",
        "posMaster.posMasterNo",
        "posMaster.ancestorDNA",
        "posMaster.reason",
        "posMaster.orgRootId",
        "posMaster.orgChild1Id",
        "posMaster.current_holderId",
        "posMaster.next_holderId",
      ])
      .where("posMaster.orgRootId = :nodeId", { nodeId })
      .andWhere("posMaster.orgChild1Id IS NULL") // เฉพาะ root level
      .orderBy("posMaster.posMasterOrder", "ASC")
      .addOrderBy("posMaster.posMasterCreatedAt", "ASC")
      .getMany();

    // Step 3: ดึงข้อมูล Profiles ที่ใช้จริงเท่านั้น
    const profileIds = [
      ...new Set([
        ...posMastersData.map((pm: any) => pm.current_holderId).filter(Boolean),
        ...posMastersData.map((pm: any) => pm.next_holderId).filter(Boolean),
      ]),
    ];

    let profilesData: any[] = [];
    if (profileIds.length > 0) {
      profilesData = await this.profileRepository
        .createQueryBuilder("profile")
        .select([
          "profile.id",
          "profile.prefix",
          "profile.firstName",
          "profile.lastName",
          "profile.position",
          "profile.posTypeId",
          "profile.posLevelId",
        ])
        .where("profile.id IN (:...profileIds)", { profileIds })
        .getMany();
    }

    // Step 4: ดึงข้อมูล Education ล่าสุดของแต่ละ Profile
    let educationsData: any[] = [];
    if (profileIds.length > 0) {
      educationsData = await this.profileEducationRepository
        .createQueryBuilder("pe")
        .select(["pe.profileId", "pe.finishDate", "pe.degree", "pe.level", "pe.isDeleted"])
        .where("pe.profileId IN (:...profileIds)", { profileIds })
        .andWhere("pe.isDeleted = :isDeleted", { isDeleted: false })
        .andWhere(
          `(pe.profileId, COALESCE(pe.finishDate, '1900-01-01'), pe.level) IN (
          SELECT pe2.profileId, 
                 COALESCE(MAX(pe2.finishDate), '1900-01-01'),
                 CASE 
                   WHEN MAX(pe2.finishDate) IS NOT NULL THEN 
                     (SELECT pe3.level FROM profileEducation pe3 
                      WHERE pe3.profileId = pe2.profileId 
                      AND pe3.finishDate = MAX(pe2.finishDate) LIMIT 1)
                   ELSE MAX(pe2.level)
                 END
          FROM profileEducation pe2 
          WHERE pe2.profileId IN (:...profileIds)
          GROUP BY pe2.profileId
        )`,
          { profileIds },
        )
        .getMany();
    }

    // Step 5: ดึงข้อมูล Salary ล่าสุดของแต่ละ Profile
    let salariesData: any[] = [];
    if (profileIds.length > 0) {
      salariesData = await this.profileSalaryRepository
        .createQueryBuilder("ps")
        .select(["ps.profileId", "ps.commandDateAffect", "ps.amount"])
        .where("ps.profileId IN (:...profileIds)", { profileIds })
        .andWhere(
          `(ps.profileId, ps.commandDateAffect) IN (
          SELECT ps2.profileId, MAX(ps2.commandDateAffect) 
          FROM profileSalary ps2 
          WHERE ps2.profileId IN (:...profileIds)
          GROUP BY ps2.profileId
        )`,
          { profileIds },
        )
        .getMany();
    }

    // Step 6: ดึงข้อมูล Positions ที่เกี่ยวข้อง
    const posMasterIds = posMastersData.map((pm: any) => pm.id);
    let positionsData: any[] = [];
    if (posMasterIds.length > 0) {
      positionsData = await this.positionRepository
        .createQueryBuilder("position")
        .leftJoinAndSelect("position.posType", "posType")
        .leftJoinAndSelect("position.posLevel", "posLevel")
        .leftJoinAndSelect("position.posExecutive", "posExecutive")
        .select([
          "position.id",
          "position.positionName",
          "position.positionIsSelected",
          "position.posMasterId",
          "posType.id",
          "posType.posTypeName",
          "posLevel.id",
          "posLevel.posLevelName",
          "posExecutive.id",
          "posExecutive.posExecutiveName",
        ])
        .where("position.posMasterId IN (:...posMasterIds)", { posMasterIds })
        .getMany();
    }

    // Step 7: Combine ข้อมูลกลับเหมือนเดิม
    for (let orgRoot of orgRootData) {
      orgRoot.posMasters = posMastersData.filter((pm: any) => pm.orgRootId === orgRoot.id);

      for (let posMaster of orgRoot.posMasters) {
        // Attach current_holder
        if (posMaster.current_holderId) {
          posMaster.current_holder = profilesData.find(
            (p: any) => p.id === posMaster.current_holderId,
          );
          if (posMaster.current_holder) {
            posMaster.current_holder.profileEducations = educationsData.filter(
              (ed: any) => ed.profileId === posMaster.current_holderId,
            );
            posMaster.current_holder.profileSalary = salariesData.filter(
              (sal: any) => sal.profileId === posMaster.current_holderId,
            );
          }
        }

        // Attach next_holder
        if (posMaster.next_holderId) {
          posMaster.next_holder = profilesData.find((p: any) => p.id === posMaster.next_holderId);
          if (posMaster.next_holder) {
            posMaster.next_holder.profileEducations = educationsData.filter(
              (ed: any) => ed.profileId === posMaster.next_holderId,
            );
            posMaster.next_holder.profileSalary = salariesData.filter(
              (sal: any) => sal.profileId === posMaster.next_holderId,
            );
          }
        }

        // Attach positions
        posMaster.positions = positionsData.filter((pos: any) => pos.posMasterId === posMaster.id);
      }
    }

    if (!orgRootData || orgRootData.length === 0) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลองค์กร");
    }

    const orgName = orgRootData[0].orgRootName ?? "";
    const orgRootIds = orgRootData.map((orgRoot) => orgRoot.id) || null;

    // Step 8: ปรับปรุง orgChild1Data - ใช้ optimized approach
    const orgChild1Data = await this.child1Repository
      .createQueryBuilder("orgChild1")
      .select([
        "orgChild1.id",
        "orgChild1.orgRootId",
        "orgChild1.orgChild1Name",
        "orgChild1.orgChild1ShortName",
        "orgChild1.orgChild1Order",
      ])
      .where("orgChild1.orgRootId IN (:...orgRootIds)", { orgRootIds })
      .orderBy("orgChild1.orgChild1Order", "ASC")
      .getMany();

    // ดึงข้อมูล PosMasters สำหรับ orgChild1
    const orgChild1Ids = orgChild1Data.map((orgChild1) => orgChild1.id);
    let child1PosMasters: any[] = [];
    if (orgChild1Ids.length > 0) {
      child1PosMasters = await this.posMasterRepository
        .createQueryBuilder("posMaster")
        .select([
          "posMaster.id",
          "posMaster.posMasterOrder",
          "posMaster.isSit",
          "posMaster.posMasterNo",
          "posMaster.ancestorDNA",
          "posMaster.reason",
          "posMaster.orgChild1Id",
          "posMaster.orgChild2Id",
          "posMaster.current_holderId",
          "posMaster.next_holderId",
        ])
        .where("posMaster.orgChild1Id IN (:...orgChild1Ids)", { orgChild1Ids })
        .andWhere("posMaster.orgChild2Id IS NULL") // เฉพาะ child1 level
        .orderBy("posMaster.posMasterOrder", "ASC")
        .addOrderBy("posMaster.posMasterCreatedAt", "ASC")
        .getMany();
    }

    // รวบรวม Profile IDs สำหรับ child1
    const child1ProfileIds =
      child1PosMasters.length > 0
        ? [
            ...new Set([
              ...child1PosMasters.map((pm: any) => pm.current_holderId).filter(Boolean),
              ...child1PosMasters.map((pm: any) => pm.next_holderId).filter(Boolean),
            ]),
          ]
        : [];

    // ดึงข้อมูล Profiles, Education, Salary, Positions สำหรับ child1
    let child1Profiles: any[] = [];
    let child1Educations: any[] = [];
    let child1Salaries: any[] = [];
    let child1Positions: any[] = [];

    if (child1ProfileIds.length > 0) {
      [child1Profiles, child1Educations, child1Salaries] = await Promise.all([
        this.profileRepository
          .createQueryBuilder("profile")
          .select([
            "profile.id",
            "profile.prefix",
            "profile.firstName",
            "profile.lastName",
            "profile.position",
            "profile.posTypeId",
            "profile.posLevelId",
          ])
          .where("profile.id IN (:...child1ProfileIds)", { child1ProfileIds })
          .getMany(),

        this.profileEducationRepository
          .createQueryBuilder("pe")
          .select(["pe.profileId", "pe.finishDate", "pe.degree", "pe.level", "pe.isDeleted"])
          .where("pe.profileId IN (:...child1ProfileIds)", { child1ProfileIds })
          .andWhere("pe.isDeleted = :isDeleted", { isDeleted: false })
          .andWhere(
            `(pe.profileId, COALESCE(pe.finishDate, '1900-01-01'), pe.level) IN (
            SELECT pe2.profileId, 
                   COALESCE(MAX(pe2.finishDate), '1900-01-01'),
                   CASE 
                     WHEN MAX(pe2.finishDate) IS NOT NULL THEN 
                       (SELECT pe3.level FROM profileEducation pe3 
                        WHERE pe3.profileId = pe2.profileId 
                        AND pe3.finishDate = MAX(pe2.finishDate) LIMIT 1)
                     ELSE MAX(pe2.level)
                   END
            FROM profileEducation pe2 
            WHERE pe2.profileId IN (:...child1ProfileIds)
            GROUP BY pe2.profileId
          )`,
            { child1ProfileIds },
          )
          .getMany(),

        this.profileSalaryRepository
          .createQueryBuilder("ps")
          .select(["ps.profileId", "ps.commandDateAffect", "ps.amount"])
          .where("ps.profileId IN (:...child1ProfileIds)", { child1ProfileIds })
          .andWhere(
            `(ps.profileId, ps.commandDateAffect) IN (
            SELECT ps2.profileId, MAX(ps2.commandDateAffect) 
            FROM profileSalary ps2 
            WHERE ps2.profileId IN (:...child1ProfileIds)
            GROUP BY ps2.profileId
          )`,
            { child1ProfileIds },
          )
          .getMany(),
      ]);
    }

    if (child1PosMasters.length > 0) {
      const child1PosMasterIds = child1PosMasters.map((pm: any) => pm.id);
      child1Positions = await this.positionRepository
        .createQueryBuilder("position")
        .leftJoinAndSelect("position.posType", "posType")
        .leftJoinAndSelect("position.posLevel", "posLevel")
        .leftJoinAndSelect("position.posExecutive", "posExecutive")
        .select([
          "position.id",
          "position.positionName",
          "position.positionIsSelected",
          "position.posMasterId",
          "posType.id",
          "posType.posTypeName",
          "posLevel.id",
          "posLevel.posLevelName",
          "posExecutive.id",
          "posExecutive.posExecutiveName",
        ])
        .where("position.posMasterId IN (:...child1PosMasterIds)", { child1PosMasterIds })
        .getMany();
    }

    // Combine ข้อมูล orgChild1
    for (let orgChild1 of orgChild1Data) {
      orgChild1.posMasters = child1PosMasters.filter((pm: any) => pm.orgChild1Id === orgChild1.id);

      for (let posMaster of orgChild1.posMasters) {
        if (posMaster.current_holderId) {
          posMaster.current_holder = child1Profiles.find(
            (p: any) => p.id === posMaster.current_holderId,
          );
          if (posMaster.current_holder) {
            posMaster.current_holder.profileEducations = child1Educations.filter(
              (ed: any) => ed.profileId === posMaster.current_holderId,
            );
            posMaster.current_holder.profileSalary = child1Salaries.filter(
              (sal: any) => sal.profileId === posMaster.current_holderId,
            );
          }
        }

        if (posMaster.next_holderId) {
          posMaster.next_holder = child1Profiles.find((p: any) => p.id === posMaster.next_holderId);
          if (posMaster.next_holder) {
            posMaster.next_holder.profileEducations = child1Educations.filter(
              (ed: any) => ed.profileId === posMaster.next_holderId,
            );
            posMaster.next_holder.profileSalary = child1Salaries.filter(
              (sal: any) => sal.profileId === posMaster.next_holderId,
            );
          }
        }

        posMaster.positions = child1Positions.filter(
          (pos: any) => pos.posMasterId === posMaster.id,
        );
      }
    }

    // Step 9: ปรับปรุง orgChild2Data
    const originalOrgChild1Ids =
      orgChild1Data.length > 0 ? orgChild1Data.map((orgChild1) => orgChild1.id) : [];
    const orgChild2Data = await this.child2Repository
      .createQueryBuilder("orgChild2")
      .select([
        "orgChild2.id",
        "orgChild2.orgChild1Id",
        "orgChild2.orgChild2Name",
        "orgChild2.orgChild2ShortName",
        "orgChild2.orgChild2Order",
      ])
      .where(
        originalOrgChild1Ids.length > 0
          ? "orgChild2.orgChild1Id IN (:...originalOrgChild1Ids)"
          : "1=0",
        {
          originalOrgChild1Ids,
        },
      )
      .orderBy("orgChild2.orgChild2Order", "ASC")
      .getMany();

    // ดึงข้อมูล PosMasters สำหรับ orgChild2
    const orgChild2Ids = orgChild2Data.map((orgChild2) => orgChild2.id);
    let child2PosMasters: any[] = [];
    if (orgChild2Ids.length > 0) {
      child2PosMasters = await this.posMasterRepository
        .createQueryBuilder("posMaster")
        .select([
          "posMaster.id",
          "posMaster.posMasterOrder",
          "posMaster.isSit",
          "posMaster.posMasterNo",
          "posMaster.ancestorDNA",
          "posMaster.reason",
          "posMaster.orgChild2Id",
          "posMaster.orgChild3Id",
          "posMaster.current_holderId",
          "posMaster.next_holderId",
        ])
        .where("posMaster.orgChild2Id IN (:...orgChild2Ids)", { orgChild2Ids })
        .andWhere("posMaster.orgChild3Id IS NULL") // เฉพาะ child2 level
        .orderBy("posMaster.posMasterOrder", "ASC")
        .addOrderBy("posMaster.posMasterCreatedAt", "ASC")
        .getMany();
    }

    // รวบรวม Profile IDs สำหรับ child2
    const child2ProfileIds =
      child2PosMasters.length > 0
        ? [
            ...new Set([
              ...child2PosMasters.map((pm: any) => pm.current_holderId).filter(Boolean),
              ...child2PosMasters.map((pm: any) => pm.next_holderId).filter(Boolean),
            ]),
          ]
        : [];

    // ดึงข้อมูล Profiles, Education, Salary, Positions สำหรับ child2
    let child2Profiles: any[] = [];
    let child2Educations: any[] = [];
    let child2Salaries: any[] = [];
    let child2Positions: any[] = [];

    if (child2ProfileIds.length > 0) {
      [child2Profiles, child2Educations, child2Salaries] = await Promise.all([
        this.profileRepository
          .createQueryBuilder("profile")
          .select([
            "profile.id",
            "profile.prefix",
            "profile.firstName",
            "profile.lastName",
            "profile.position",
            "profile.posTypeId",
            "profile.posLevelId",
          ])
          .where("profile.id IN (:...child2ProfileIds)", { child2ProfileIds })
          .getMany(),

        this.profileEducationRepository
          .createQueryBuilder("pe")
          .select(["pe.profileId", "pe.finishDate", "pe.degree", "pe.level", "pe.isDeleted"])
          .where("pe.profileId IN (:...child2ProfileIds)", { child2ProfileIds })
          .andWhere("pe.isDeleted = :isDeleted", { isDeleted: false })
          .andWhere(
            `(pe.profileId, COALESCE(pe.finishDate, '1900-01-01'), pe.level) IN (
            SELECT pe2.profileId, 
                   COALESCE(MAX(pe2.finishDate), '1900-01-01'),
                   CASE 
                     WHEN MAX(pe2.finishDate) IS NOT NULL THEN 
                       (SELECT pe3.level FROM profileEducation pe3 
                        WHERE pe3.profileId = pe2.profileId 
                        AND pe3.finishDate = MAX(pe2.finishDate) LIMIT 1)
                     ELSE MAX(pe2.level)
                   END
            FROM profileEducation pe2 
            WHERE pe2.profileId IN (:...child2ProfileIds)
            GROUP BY pe2.profileId
          )`,
            { child2ProfileIds },
          )
          .getMany(),

        this.profileSalaryRepository
          .createQueryBuilder("ps")
          .select(["ps.profileId", "ps.commandDateAffect", "ps.amount"])
          .where("ps.profileId IN (:...child2ProfileIds)", { child2ProfileIds })
          .andWhere(
            `(ps.profileId, ps.commandDateAffect) IN (
            SELECT ps2.profileId, MAX(ps2.commandDateAffect) 
            FROM profileSalary ps2 
            WHERE ps2.profileId IN (:...child2ProfileIds)
            GROUP BY ps2.profileId
          )`,
            { child2ProfileIds },
          )
          .getMany(),
      ]);
    }

    if (child2PosMasters.length > 0) {
      const child2PosMasterIds = child2PosMasters.map((pm: any) => pm.id);
      child2Positions = await this.positionRepository
        .createQueryBuilder("position")
        .leftJoinAndSelect("position.posType", "posType")
        .leftJoinAndSelect("position.posLevel", "posLevel")
        .leftJoinAndSelect("position.posExecutive", "posExecutive")
        .select([
          "position.id",
          "position.positionName",
          "position.positionIsSelected",
          "position.posMasterId",
          "posType.id",
          "posType.posTypeName",
          "posLevel.id",
          "posLevel.posLevelName",
          "posExecutive.id",
          "posExecutive.posExecutiveName",
        ])
        .where("position.posMasterId IN (:...child2PosMasterIds)", { child2PosMasterIds })
        .getMany();
    }

    // Combine ข้อมูล orgChild2
    for (let orgChild2 of orgChild2Data) {
      orgChild2.posMasters = child2PosMasters.filter((pm: any) => pm.orgChild2Id === orgChild2.id);

      for (let posMaster of orgChild2.posMasters) {
        if (posMaster.current_holderId) {
          posMaster.current_holder = child2Profiles.find(
            (p: any) => p.id === posMaster.current_holderId,
          );
          if (posMaster.current_holder) {
            posMaster.current_holder.profileEducations = child2Educations.filter(
              (ed: any) => ed.profileId === posMaster.current_holderId,
            );
            posMaster.current_holder.profileSalary = child2Salaries.filter(
              (sal: any) => sal.profileId === posMaster.current_holderId,
            );
          }
        }

        if (posMaster.next_holderId) {
          posMaster.next_holder = child2Profiles.find((p: any) => p.id === posMaster.next_holderId);
          if (posMaster.next_holder) {
            posMaster.next_holder.profileEducations = child2Educations.filter(
              (ed: any) => ed.profileId === posMaster.next_holderId,
            );
            posMaster.next_holder.profileSalary = child2Salaries.filter(
              (sal: any) => sal.profileId === posMaster.next_holderId,
            );
          }
        }

        posMaster.positions = child2Positions.filter(
          (pos: any) => pos.posMasterId === posMaster.id,
        );
      }
    }

    // Step 10: ปรับปรุง orgChild3Data
    const originalOrgChild2Ids =
      orgChild2Data.length > 0 ? orgChild2Data.map((orgChild2) => orgChild2.id) : [];
    const orgChild3Data = await this.child3Repository
      .createQueryBuilder("orgChild3")
      .select([
        "orgChild3.id",
        "orgChild3.orgChild2Id",
        "orgChild3.orgChild3Name",
        "orgChild3.orgChild3ShortName",
        "orgChild3.orgChild3Order",
      ])
      .where(
        originalOrgChild2Ids.length > 0
          ? "orgChild3.orgChild2Id IN (:...originalOrgChild2Ids)"
          : "1=0",
        {
          originalOrgChild2Ids,
        },
      )
      .orderBy("orgChild3.orgChild3Order", "ASC")
      .getMany();

    // ดึงข้อมูล PosMasters สำหรับ orgChild3
    const orgChild3Ids = orgChild3Data.map((orgChild3) => orgChild3.id);
    let child3PosMasters: any[] = [];
    if (orgChild3Ids.length > 0) {
      child3PosMasters = await this.posMasterRepository
        .createQueryBuilder("posMaster")
        .select([
          "posMaster.id",
          "posMaster.posMasterOrder",
          "posMaster.isSit",
          "posMaster.posMasterNo",
          "posMaster.ancestorDNA",
          "posMaster.reason",
          "posMaster.orgChild3Id",
          "posMaster.orgChild4Id",
          "posMaster.current_holderId",
          "posMaster.next_holderId",
        ])
        .where("posMaster.orgChild3Id IN (:...orgChild3Ids)", { orgChild3Ids })
        .andWhere("posMaster.orgChild4Id IS NULL") // เฉพาะ child3 level
        .orderBy("posMaster.posMasterOrder", "ASC")
        .addOrderBy("posMaster.posMasterCreatedAt", "ASC")
        .getMany();
    }

    // รวบรวม Profile IDs สำหรับ child3
    const child3ProfileIds =
      child3PosMasters.length > 0
        ? [
            ...new Set([
              ...child3PosMasters.map((pm: any) => pm.current_holderId).filter(Boolean),
              ...child3PosMasters.map((pm: any) => pm.next_holderId).filter(Boolean),
            ]),
          ]
        : [];

    // ดึงข้อมูล Profiles, Education, Salary, Positions สำหรับ child3
    let child3Profiles: any[] = [];
    let child3Educations: any[] = [];
    let child3Salaries: any[] = [];
    let child3Positions: any[] = [];

    if (child3ProfileIds.length > 0) {
      [child3Profiles, child3Educations, child3Salaries] = await Promise.all([
        this.profileRepository
          .createQueryBuilder("profile")
          .select([
            "profile.id",
            "profile.prefix",
            "profile.firstName",
            "profile.lastName",
            "profile.position",
            "profile.posTypeId",
            "profile.posLevelId",
          ])
          .where("profile.id IN (:...child3ProfileIds)", { child3ProfileIds })
          .getMany(),

        this.profileEducationRepository
          .createQueryBuilder("pe")
          .select(["pe.profileId", "pe.finishDate", "pe.degree", "pe.level", "pe.isDeleted"])
          .where("pe.profileId IN (:...child3ProfileIds)", { child3ProfileIds })
          .andWhere("pe.isDeleted = :isDeleted", { isDeleted: false })
          .andWhere(
            `(pe.profileId, COALESCE(pe.finishDate, '1900-01-01'), pe.level) IN (
            SELECT pe2.profileId, 
                   COALESCE(MAX(pe2.finishDate), '1900-01-01'),
                   CASE 
                     WHEN MAX(pe2.finishDate) IS NOT NULL THEN 
                       (SELECT pe3.level FROM profileEducation pe3 
                        WHERE pe3.profileId = pe2.profileId 
                        AND pe3.finishDate = MAX(pe2.finishDate) LIMIT 1)
                     ELSE MAX(pe2.level)
                   END
            FROM profileEducation pe2 
            WHERE pe2.profileId IN (:...child3ProfileIds)
            GROUP BY pe2.profileId
          )`,
            { child3ProfileIds },
          )
          .getMany(),

        this.profileSalaryRepository
          .createQueryBuilder("ps")
          .select(["ps.profileId", "ps.commandDateAffect", "ps.amount"])
          .where("ps.profileId IN (:...child3ProfileIds)", { child3ProfileIds })
          .andWhere(
            `(ps.profileId, ps.commandDateAffect) IN (
            SELECT ps2.profileId, MAX(ps2.commandDateAffect) 
            FROM profileSalary ps2 
            WHERE ps2.profileId IN (:...child3ProfileIds)
            GROUP BY ps2.profileId
          )`,
            { child3ProfileIds },
          )
          .getMany(),
      ]);
    }

    if (child3PosMasters.length > 0) {
      const child3PosMasterIds = child3PosMasters.map((pm: any) => pm.id);
      child3Positions = await this.positionRepository
        .createQueryBuilder("position")
        .leftJoinAndSelect("position.posType", "posType")
        .leftJoinAndSelect("position.posLevel", "posLevel")
        .leftJoinAndSelect("position.posExecutive", "posExecutive")
        .select([
          "position.id",
          "position.positionName",
          "position.positionIsSelected",
          "position.posMasterId",
          "posType.id",
          "posType.posTypeName",
          "posLevel.id",
          "posLevel.posLevelName",
          "posExecutive.id",
          "posExecutive.posExecutiveName",
        ])
        .where("position.posMasterId IN (:...child3PosMasterIds)", { child3PosMasterIds })
        .getMany();
    }

    // Combine ข้อมูล orgChild3
    for (let orgChild3 of orgChild3Data) {
      orgChild3.posMasters = child3PosMasters.filter((pm: any) => pm.orgChild3Id === orgChild3.id);

      for (let posMaster of orgChild3.posMasters) {
        if (posMaster.current_holderId) {
          posMaster.current_holder = child3Profiles.find(
            (p: any) => p.id === posMaster.current_holderId,
          );
          if (posMaster.current_holder) {
            posMaster.current_holder.profileEducations = child3Educations.filter(
              (ed: any) => ed.profileId === posMaster.current_holderId,
            );
            posMaster.current_holder.profileSalary = child3Salaries.filter(
              (sal: any) => sal.profileId === posMaster.current_holderId,
            );
          }
        }

        if (posMaster.next_holderId) {
          posMaster.next_holder = child3Profiles.find((p: any) => p.id === posMaster.next_holderId);
          if (posMaster.next_holder) {
            posMaster.next_holder.profileEducations = child3Educations.filter(
              (ed: any) => ed.profileId === posMaster.next_holderId,
            );
            posMaster.next_holder.profileSalary = child3Salaries.filter(
              (sal: any) => sal.profileId === posMaster.next_holderId,
            );
          }
        }

        posMaster.positions = child3Positions.filter(
          (pos: any) => pos.posMasterId === posMaster.id,
        );
      }
    }

    // Step 11: ปรับปรุง orgChild4Data
    const originalOrgChild3Ids =
      orgChild3Data.length > 0 ? orgChild3Data.map((orgChild3) => orgChild3.id) : [];
    const orgChild4Data = await this.child4Repository
      .createQueryBuilder("orgChild4")
      .select([
        "orgChild4.id",
        "orgChild4.orgChild3Id",
        "orgChild4.orgChild4Name",
        "orgChild4.orgChild4ShortName",
        "orgChild4.orgChild4Order",
      ])
      .where(
        originalOrgChild3Ids.length > 0
          ? "orgChild4.orgChild3Id IN (:...originalOrgChild3Ids)"
          : "1=0",
        {
          originalOrgChild3Ids,
        },
      )
      .orderBy("orgChild4.orgChild4Order", "ASC")
      .getMany();

    // ดึงข้อมูล PosMasters สำหรับ orgChild4
    const orgChild4Ids = orgChild4Data.map((orgChild4) => orgChild4.id);
    let child4PosMasters: any[] = [];
    if (orgChild4Ids.length > 0) {
      child4PosMasters = await this.posMasterRepository
        .createQueryBuilder("posMaster")
        .select([
          "posMaster.id",
          "posMaster.posMasterOrder",
          "posMaster.isSit",
          "posMaster.posMasterNo",
          "posMaster.ancestorDNA",
          "posMaster.reason",
          "posMaster.orgChild4Id",
          "posMaster.current_holderId",
          "posMaster.next_holderId",
        ])
        .where("posMaster.orgChild4Id IN (:...orgChild4Ids)", { orgChild4Ids })
        .orderBy("posMaster.posMasterOrder", "ASC")
        .addOrderBy("posMaster.posMasterCreatedAt", "ASC")
        .getMany();
    }

    // รวบรวม Profile IDs สำหรับ child4
    const child4ProfileIds =
      child4PosMasters.length > 0
        ? [
            ...new Set([
              ...child4PosMasters.map((pm: any) => pm.current_holderId).filter(Boolean),
              ...child4PosMasters.map((pm: any) => pm.next_holderId).filter(Boolean),
            ]),
          ]
        : [];

    // ดึงข้อมูล Profiles, Education, Salary, Positions สำหรับ child4
    let child4Profiles: any[] = [];
    let child4Educations: any[] = [];
    let child4Salaries: any[] = [];
    let child4Positions: any[] = [];

    if (child4ProfileIds.length > 0) {
      [child4Profiles, child4Educations, child4Salaries] = await Promise.all([
        this.profileRepository
          .createQueryBuilder("profile")
          .select([
            "profile.id",
            "profile.prefix",
            "profile.firstName",
            "profile.lastName",
            "profile.position",
            "profile.posTypeId",
            "profile.posLevelId",
          ])
          .where("profile.id IN (:...child4ProfileIds)", { child4ProfileIds })
          .getMany(),

        this.profileEducationRepository
          .createQueryBuilder("pe")
          .select(["pe.profileId", "pe.finishDate", "pe.degree", "pe.level", "pe.isDeleted"])
          .where("pe.profileId IN (:...child4ProfileIds)", { child4ProfileIds })
          .andWhere("pe.isDeleted = :isDeleted", { isDeleted: false })
          .andWhere(
            `(pe.profileId, COALESCE(pe.finishDate, '1900-01-01'), pe.level) IN (
            SELECT pe2.profileId, 
                   COALESCE(MAX(pe2.finishDate), '1900-01-01'),
                   CASE 
                     WHEN MAX(pe2.finishDate) IS NOT NULL THEN 
                       (SELECT pe3.level FROM profileEducation pe3 
                        WHERE pe3.profileId = pe2.profileId 
                        AND pe3.finishDate = MAX(pe2.finishDate) LIMIT 1)
                     ELSE MAX(pe2.level)
                   END
            FROM profileEducation pe2 
            WHERE pe2.profileId IN (:...child4ProfileIds)
            GROUP BY pe2.profileId
          )`,
            { child4ProfileIds },
          )
          .getMany(),

        this.profileSalaryRepository
          .createQueryBuilder("ps")
          .select(["ps.profileId", "ps.commandDateAffect", "ps.amount"])
          .where("ps.profileId IN (:...child4ProfileIds)", { child4ProfileIds })
          .andWhere(
            `(ps.profileId, ps.commandDateAffect) IN (
            SELECT ps2.profileId, MAX(ps2.commandDateAffect) 
            FROM profileSalary ps2 
            WHERE ps2.profileId IN (:...child4ProfileIds)
            GROUP BY ps2.profileId
          )`,
            { child4ProfileIds },
          )
          .getMany(),
      ]);
    }

    if (child4PosMasters.length > 0) {
      const child4PosMasterIds = child4PosMasters.map((pm: any) => pm.id);
      child4Positions = await this.positionRepository
        .createQueryBuilder("position")
        .leftJoinAndSelect("position.posType", "posType")
        .leftJoinAndSelect("position.posLevel", "posLevel")
        .leftJoinAndSelect("position.posExecutive", "posExecutive")
        .select([
          "position.id",
          "position.positionName",
          "position.positionIsSelected",
          "position.posMasterId",
          "posType.id",
          "posType.posTypeName",
          "posLevel.id",
          "posLevel.posLevelName",
          "posExecutive.id",
          "posExecutive.posExecutiveName",
        ])
        .where("position.posMasterId IN (:...child4PosMasterIds)", { child4PosMasterIds })
        .getMany();
    }

    // Combine ข้อมูล orgChild4
    for (let orgChild4 of orgChild4Data) {
      orgChild4.posMasters = child4PosMasters.filter((pm: any) => pm.orgChild4Id === orgChild4.id);

      for (let posMaster of orgChild4.posMasters) {
        if (posMaster.current_holderId) {
          posMaster.current_holder = child4Profiles.find(
            (p: any) => p.id === posMaster.current_holderId,
          );
          if (posMaster.current_holder) {
            posMaster.current_holder.profileEducations = child4Educations.filter(
              (ed: any) => ed.profileId === posMaster.current_holderId,
            );
            posMaster.current_holder.profileSalary = child4Salaries.filter(
              (sal: any) => sal.profileId === posMaster.current_holderId,
            );
          }
        }

        if (posMaster.next_holderId) {
          posMaster.next_holder = child4Profiles.find((p: any) => p.id === posMaster.next_holderId);
          if (posMaster.next_holder) {
            posMaster.next_holder.profileEducations = child4Educations.filter(
              (ed: any) => ed.profileId === posMaster.next_holderId,
            );
            posMaster.next_holder.profileSalary = child4Salaries.filter(
              (sal: any) => sal.profileId === posMaster.next_holderId,
            );
          }
        }

        posMaster.positions = child4Positions.filter(
          (pos: any) => pos.posMasterId === posMaster.id,
        );
      }
    }

    let orgRevisionActive: any = await this.orgRevisionRepository
      .createQueryBuilder("orgRevision")
      .select([
        "orgRevision.id",
        "orgRevision.orgRevisionIsCurrent",
        "orgRevision.orgRevisionIsDraft",
        "orgRevision.createdAt",
      ])
      .leftJoinAndSelect("orgRevision.posMasters", "posMasters")
      .leftJoinAndSelect("posMasters.positions", "positions")
      .leftJoinAndSelect("positions.posType", "posType")
      .leftJoinAndSelect("positions.posLevel", "posLevel")
      .leftJoinAndSelect("positions.posExecutive", "posExecutive")
      .addSelect([
        "posMasters.posMasterOrder",
        "posMasters.posMasterNo",
        "posMasters.ancestorDNA",
        "posMasters.orgRevisionId",
      ])
      .addSelect(["positions.positionName", "positions.positionIsSelected"])
      .addSelect(["posType.posTypeName"])
      .addSelect(["posLevel.posLevelName"])
      .addSelect(["posExecutive.posExecutiveName"])
      .where("orgRevision.orgRevisionIsCurrent = :isCurrent", { isCurrent: true })
      .andWhere("orgRevision.orgRevisionIsDraft = :isDraft", { isDraft: false })
      .getOne();

    if (orgRevisionActive == null) {
      const _orgRevisionActive = await this.orgRevisionRepository
        .createQueryBuilder("orgRevision")
        .select([
          "orgRevision.id",
          "orgRevision.orgRevisionIsCurrent",
          "orgRevision.orgRevisionIsDraft",
          "orgRevision.createdAt",
        ])
        .leftJoinAndSelect("orgRevision.posMasters", "posMasters")
        .leftJoinAndSelect("posMasters.positions", "positions")
        .leftJoinAndSelect("positions.posType", "posType")
        .leftJoinAndSelect("positions.posLevel", "posLevel")
        .leftJoinAndSelect("positions.posExecutive", "posExecutive")
        .addSelect([
          "posMasters.posMasterOrder",
          "posMasters.posMasterNo",
          "posMasters.ancestorDNA",
          "posMasters.orgRevisionId",
        ])
        .addSelect(["positions.positionName", "positions.positionIsSelected"])
        .addSelect(["posType.posTypeName"])
        .addSelect(["posLevel.posLevelName"])
        .addSelect(["posExecutive.posExecutiveName"])
        .orderBy("orgRevision.createdAt", "DESC")
        .skip(1)
        .take(1)
        .getMany();
      if (_orgRevisionActive.length > 0) orgRevisionActive = _orgRevisionActive[0];
    }

    let data = new Array();
    let _node: any;
    let no = 1;

    for (let orgRoot of orgRootData) {
      const posMastersFiltered = orgRoot.posMasters.sort(
        (a, b) => a.posMasterOrder - b.posMasterOrder,
      );

      for (let posMaster of posMastersFiltered) {
        if (posMaster.orgChild1Id == null) {
          // Use temporary arrays to reduce memory allocation
          const posNames = posMaster.positions.map((x) => x.positionName);
          const positionName = [...new Set(posNames)];

          const typeNames = posMaster.positions
            .filter((x: any) => x.posType != null)
            .map((x) => x.posType.posTypeName);
          const posType = [...new Set(typeNames)];

          const levelNames = posMaster.positions
            .filter((x: any) => x.posLevel != null)
            .map((x) => x.posLevel.posLevelName);
          const posLevel = [...new Set(levelNames)];

          const execNames = posMaster.positions
            .filter((x: any) => x.posExecutive != null)
            .map((x) => x.posExecutive.posExecutiveName);
          const posExecutive = [...new Set(execNames)];
          let positionMasterProfileOld: any = null;
          if (posMaster.next_holder != null && posMaster.next_holder.current_holders) {
            positionMasterProfileOld = posMaster.next_holder.current_holders.find(
              (x) => x.orgRevisionId == orgRevisionActive.id,
            );
          }

          let positionMasterOld: any = null;
          let profilePositionName: any = [];
          let profilePosType: any = [];
          let profilePosLevel: any = [];
          let profilePosExecutive: any = [];
          if (
            posMaster.ancestorDNA != null &&
            posMaster.ancestorDNA != "" &&
            orgRevisionActive &&
            orgRevisionActive.posMasters
          ) {
            positionMasterOld = orgRevisionActive.posMasters.find(
              (x: any) =>
                x.orgRevisionId == orgRevisionActive.id && x.ancestorDNA == posMaster.ancestorDNA,
            );
            if (positionMasterOld && positionMasterOld.positions) {
              profilePositionName = [
                ...new Set(positionMasterOld.positions.map((x: any) => x.positionName)),
              ];
              profilePosType = [
                ...new Set(
                  positionMasterOld.positions
                    .filter((x: any) => x.posType != null)
                    .map((x: any) => x.posType.posTypeName),
                ),
              ];
              profilePosLevel = [
                ...new Set(
                  positionMasterOld.positions
                    .filter((x: any) => x.posLevel != null)
                    .map((x: any) => x.posLevel.posLevelName),
                ),
              ];
              profilePosExecutive = [
                ...new Set(
                  positionMasterOld.positions
                    .filter((x: any) => x.posExecutive != null)
                    .map((x: any) => x.posExecutive.posExecutiveName),
                ),
              ];
            }
          }
          let education: any = "";
          if (
            posMaster.next_holder != null &&
            posMaster.next_holder.profileEducations != null &&
            posMaster.next_holder.profileEducations.length > 0
          ) {
            let _education: any = posMaster.next_holder.profileEducations.sort(
              (a, b) =>
                (b.finishDate == null ? 0 : b.finishDate.getTime()) -
                (a.finishDate == null ? 0 : a.finishDate.getTime()),
            );
            if (_education.length > 0) {
              education = _education[0];
            }
          } else {
            if (
              posMaster.current_holder != null &&
              posMaster.current_holder.profileEducations != null &&
              posMaster.current_holder.profileEducations.length > 0
            ) {
              let _education: any = posMaster.current_holder.profileEducations.sort(
                (a, b) =>
                  (b.finishDate == null ? 0 : b.finishDate.getTime()) -
                  (a.finishDate == null ? 0 : a.finishDate.getTime()),
              );
              if (_education.length > 0) {
                education = _education[0];
              }
            }
          }
          let salary: any = "";
          if (
            posMaster.next_holder != null &&
            posMaster.next_holder.profileSalary != null &&
            posMaster.next_holder.profileSalary.length > 0
          ) {
            let _salary: any = posMaster.next_holder.profileSalary.sort(
              (a, b) =>
                (b.commandDateAffect == null ? 0 : b.commandDateAffect.getTime()) -
                (a.commandDateAffect == null ? 0 : a.commandDateAffect.getTime()),
            );
            if (_salary.length > 0) {
              salary = _salary[0];
            }
          } else {
            if (
              posMaster.current_holder != null &&
              posMaster.current_holder.profileSalary != null &&
              posMaster.current_holder.profileSalary.length > 0
            ) {
              let _salary: any = posMaster.current_holder.profileSalary.sort(
                (a, b) =>
                  (b.commandDateAffect == null ? 0 : b.commandDateAffect.getTime()) -
                  (a.commandDateAffect == null ? 0 : a.commandDateAffect.getTime()),
              );
              if (_salary.length > 0) {
                salary = _salary[0];
              }
            }
          }
          if (positionMasterProfileOld == null && posMaster.next_holder != null 
            && posMaster.next_holder.current_holders == null
          ) {
            positionMasterProfileOld = positionMasterOld
          }
          let node = {
            posMasterOrder: posMaster.posMasterOrder, //
            isSit: posMaster.isSit, //
            orgTreeName: orgRoot.orgRootName,
            orgTreeShortName: orgRoot.orgRootShortName,
            posMasterNo: posMaster.posMasterNo,
            positionName:
              posMaster.next_holder == null
                ? positionName.join(" หรือ ")
                : posMaster.isSit == false
                  ? posMaster.positions.find((x: any) => x.positionIsSelected == true)?.positionName
                  : posMaster.next_holder.position,
            posType:
              posMaster.next_holder == null
                ? posType.join(" หรือ ")
                : posMaster.isSit == false
                  ? posMaster.positions.find((x: any) => x.positionIsSelected == true)?.posType
                      ?.posTypeName
                  : posMaster.next_holder.posType == null
                    ? "-"
                    : posMaster.next_holder.posType.posTypeName,
            posLevel:
              posMaster.next_holder == null
                ? posLevel.join(" หรือ ")
                : posMaster.isSit == false
                  ? posMaster.positions.find((x: any) => x.positionIsSelected == true)?.posLevel
                      ?.posLevelName
                  : posMaster.next_holder.posLevel == null
                    ? "-"
                    : posMaster.next_holder.posLevel.posLevelName,
            posExecutive:
              posMaster.next_holder == null
                ? posExecutive.join(" หรือ ")
                : posMaster.isSit == false
                  ? posMaster.positions.find((x: any) => x.positionIsSelected == true)?.posExecutive
                      ?.posExecutiveName
                  : positionMasterProfileOld == null
                    ? "-"
                    : positionMasterProfileOld.positions.find(
                        (x: any) => x.positionIsSelected == true,
                      )?.posExecutive?.posExecutiveName,

            profileOrgName:
              posMaster.next_holder == null
                ? orgRoot.orgRootName
                : positionMasterProfileOld == null
                  ? "-"
                  : positionMasterProfileOld.orgChild4 != null
                    ? positionMasterProfileOld.orgChild4.orgChild4Name
                    : positionMasterProfileOld.orgChild3 != null
                      ? positionMasterProfileOld.orgChild3.orgChild3Name
                      : positionMasterProfileOld.orgChild2 != null
                        ? positionMasterProfileOld.orgChild2.orgChild2Name
                        : positionMasterProfileOld.orgChild1 != null
                          ? positionMasterProfileOld.orgChild1.orgChild1Name
                          : positionMasterProfileOld.orgRoot != null
                            ? positionMasterProfileOld.orgRoot.orgRootName
                            : "-",
            profileOrgShortName:
              posMaster.next_holder == null
                ? orgRoot.orgRootShortName
                : positionMasterProfileOld == null
                  ? "-"
                  : positionMasterProfileOld.orgChild4 != null
                    ? positionMasterProfileOld.orgChild4.orgChild4ShortName
                    : positionMasterProfileOld.orgChild3 != null
                      ? positionMasterProfileOld.orgChild3.orgChild3ShortName
                      : positionMasterProfileOld.orgChild2 != null
                        ? positionMasterProfileOld.orgChild2.orgChild2ShortName
                        : positionMasterProfileOld.orgChild1 != null
                          ? positionMasterProfileOld.orgChild1.orgChild1ShortName
                          : positionMasterProfileOld.orgRoot != null
                            ? positionMasterProfileOld.orgRoot.orgRootShortName
                            : "-",
            profileFullname:
              posMaster.next_holder == null
                ? posMaster.current_holder == null
                  ? "- ว่าง -"
                  : `${posMaster.current_holder.prefix}${posMaster.current_holder.firstName} ${posMaster.current_holder.lastName}`
                : `${posMaster.next_holder.prefix}${posMaster.next_holder.firstName} ${posMaster.next_holder.lastName}`,
            profilePosMasterNo:
              posMaster.next_holder == null
                ? positionMasterOld == null
                  ? "-"
                  : positionMasterOld.posMasterNo
                : positionMasterProfileOld == null
                  ? "-"
                  : positionMasterProfileOld.posMasterNo,
            profilePositionName:
              posMaster.next_holder == null
                ? positionMasterOld == null
                  ? positionName.join(" หรือ ")
                  : profilePositionName.join(" หรือ ")
                : posMaster.next_holder.position,
            profilePosType:
              posMaster.next_holder == null
                ? positionMasterOld == null
                  ? posType.join(" หรือ ")
                  : profilePosType.join(" หรือ ")
                : positionMasterProfileOld == null
                  ? "-"
                  // : posMaster.next_holder.posType.posTypeName,
                  : positionMasterProfileOld.positions.find(
                        (x: any) => x.positionIsSelected == true,
                      )?.posType?.posTypeName,
            profilePosLevel:
              posMaster.next_holder == null
                ? positionMasterOld == null
                  ? posLevel.join(" หรือ ")
                  : profilePosLevel.join(" หรือ ")
                : positionMasterProfileOld == null
                  ? "-"
                  // : posMaster.next_holder.posLevel.posLevelName,
                  : positionMasterProfileOld.positions.find(
                        (x: any) => x.positionIsSelected == true,
                      )?.posLevel?.posLevelName,
            profilePosExecutive:
              posMaster.next_holder == null
                ? positionMasterOld == null
                  ? posExecutive.join(" หรือ ")
                  : profilePosExecutive.join(" หรือ ")
                : positionMasterProfileOld == null
                  ? "-"
                  : positionMasterProfileOld.positions.find(
                      (x: any) => x.positionIsSelected == true,
                    )?.posExecutive?.posExecutiveName,
            education: education == "" ? "" : education.degree,
            salary: salary == "" ? "" : salary.amount,
            reason: posMaster.reason,
          };
          if (_node == null) {
            const head = {
              posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName.toString()),
              profileFullname: 
                posMaster.next_holder == null 
                  ? Extension.ToThaiNumber(node.profileOrgName.toString())
                  : Extension.ToThaiNumber(node.orgTreeName.toString()),
              posExecutive: Extension.ToThaiNumber(node.orgTreeName.toString()),
              positionName: "",
              posType: "",
              posLevel: "",
              profilePosMasterNo: 
                posMaster.next_holder == null 
                  ? Extension.ToThaiNumber(node.profileOrgShortName.toString())
                  : Extension.ToThaiNumber(node.orgTreeShortName.toString()),
              profilePosExecutive: "",
              profilePositionName: "",
              profilePosType: "",
              profilePosLevel: "",
              education: "",
              salary: "",
              reason: "",
            };
            data.push(head);
            const _head = {
              no: Extension.ToThaiNumber(no.toString()),
              posMasterNo:
                node.posMasterNo == null ? "" : Extension.ToThaiNumber(node.posMasterNo.toString()),
              profileFullname:
                node.profileFullname == null
                  ? ""
                  : Extension.ToThaiNumber(node.profileFullname.toString()),
              posExecutive:
                node.posExecutive == null
                  ? ""
                  : Extension.ToThaiNumber(node.posExecutive.toString()),
              positionName:
                node.positionName == null
                  ? ""
                  : Extension.ToThaiNumber(node.positionName.toString()),
              posType: node.posType == null ? "" : Extension.ToThaiNumber(node.posType.toString()),
              posLevel:
                node.posLevel == null ? "" : Extension.ToThaiNumber(node.posLevel.toString()),
              profilePosMasterNo: Extension.ToThaiNumber(node.profilePosMasterNo.toString()),
              profilePosExecutive:
                node.profilePosExecutive == null
                  ? ""
                  : Extension.ToThaiNumber(node.profilePosExecutive.toString()),
              profilePositionName:
                node.profilePositionName == null
                  ? ""
                  : Extension.ToThaiNumber(node.profilePositionName.toString()),
              profilePosType:
                node.profilePosType == null
                  ? ""
                  : Extension.ToThaiNumber(node.profilePosType.toString()),
              profilePosLevel:
                node.profilePosLevel == null
                  ? ""
                  : Extension.ToThaiNumber(node.profilePosLevel.toString()),
              education:
                node.education == null ? "" : Extension.ToThaiNumber(node.education.toString()),
              salary: node.salary ? Extension.ToThaiNumber(node.salary.toLocaleString()) : "",
              reason: node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
            };
            data.push(_head);
          } else {
            if (
              node.orgTreeShortName != _node.orgTreeShortName ||
              node.orgTreeName != _node.orgTreeName ||
              node.profileOrgShortName != _node.profileOrgShortName ||
              node.profileOrgName != _node.profileOrgName
            ) {
              const head = {
                posMasterNo:
                  node.orgTreeShortName == _node.orgTreeShortName ? "" : node.orgTreeShortName,
                profileFullname:
                  node.profileOrgName == _node.profileOrgName ? "" : node.profileOrgName,
                posExecutive: node.orgTreeName == _node.orgTreeName ? "" : node.orgTreeName,
                positionName: "",
                posType: "",
                posLevel: "",
                profilePosMasterNo:
                  node.profileOrgShortName == _node.profileOrgShortName
                    ? ""
                    : node.profileOrgShortName,
                profilePosExecutive: "",
                profilePositionName: "",
                profilePosType: "",
                profilePosLevel: "",
                education: "",
                salary: "",
                reason: "",
              };
              data.push(head);
              _node == null;
            }
            const head = {
              no: Extension.ToThaiNumber(no.toString()),
              posMasterNo:
                node.posMasterNo == null ? "" : Extension.ToThaiNumber(node.posMasterNo.toString()),
              profileFullname:
                node.profileFullname == null
                  ? ""
                  : Extension.ToThaiNumber(node.profileFullname.toString()),
              posExecutive:
                node.posExecutive == null
                  ? ""
                  : Extension.ToThaiNumber(node.posExecutive.toString()),
              positionName:
                node.positionName == null
                  ? ""
                  : Extension.ToThaiNumber(node.positionName.toString()),
              posType: node.posType == null ? "" : Extension.ToThaiNumber(node.posType.toString()),
              posLevel:
                node.posLevel == null ? "" : Extension.ToThaiNumber(node.posLevel.toString()),
              profilePosMasterNo: Extension.ToThaiNumber(node.profilePosMasterNo.toString()),
              profilePosExecutive:
                node.profilePosExecutive == null
                  ? ""
                  : Extension.ToThaiNumber(node.profilePosExecutive.toString()),
              profilePositionName:
                node.profilePositionName == null
                  ? ""
                  : Extension.ToThaiNumber(node.profilePositionName.toString()),
              profilePosType:
                node.profilePosType == null
                  ? ""
                  : Extension.ToThaiNumber(node.profilePosType.toString()),
              profilePosLevel:
                node.profilePosLevel == null
                  ? ""
                  : Extension.ToThaiNumber(node.profilePosLevel.toString()),
              education:
                node.education == null ? "" : Extension.ToThaiNumber(node.education.toString()),
              salary: node.salary ? Extension.ToThaiNumber(node.salary.toLocaleString()) : "",
              reason: node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
            };
            data.push(head);
          }
          no += 1;
          _node = node;
        }
      }
      _node = null;

      for (let orgChild1 of orgChild1Data.filter(
        (orgChild1) => orgChild1.orgRootId === orgRoot.id,
      )) {
        const posMastersFiltered1 = orgChild1.posMasters.sort(
          (a, b) => a.posMasterOrder - b.posMasterOrder,
        );
        for (let posMaster of posMastersFiltered1) {
          if (posMaster.orgChild2Id == null) {
            const positionName = [...new Set(posMaster.positions.map((x) => x.positionName))];
            const posType = [
              ...new Set(
                posMaster.positions
                  .filter((x: any) => x.posType != null)
                  .map((x) => x.posType.posTypeName),
              ),
            ];
            const posLevel = [
              ...new Set(
                posMaster.positions
                  .filter((x: any) => x.posLevel != null)
                  .map((x) => x.posLevel.posLevelName),
              ),
            ];
            const posExecutive = [
              ...new Set(
                posMaster.positions
                  .filter((x: any) => x.posExecutive != null)
                  .map((x) => x.posExecutive.posExecutiveName),
              ),
            ];
            let positionMasterProfileOld: any = null;
            if (posMaster.next_holder != null && posMaster.next_holder.current_holders) {
              positionMasterProfileOld = posMaster.next_holder.current_holders.find(
                (x) => x.orgRevisionId == orgRevisionActive.id,
              );
            }

            let positionMasterOld: any = null;
            let profilePositionName: any = [];
            let profilePosType: any = [];
            let profilePosLevel: any = [];
            let profilePosExecutive: any = [];
            if (
              posMaster.ancestorDNA != null &&
              posMaster.ancestorDNA != "" &&
              orgRevisionActive &&
              orgRevisionActive.posMasters
            ) {
              positionMasterOld = orgRevisionActive.posMasters.find(
                (x: any) =>
                  x.orgRevisionId == orgRevisionActive.id && x.ancestorDNA == posMaster.ancestorDNA,
              );
              if (positionMasterOld && positionMasterOld.positions) {
                profilePositionName = [
                  ...new Set(positionMasterOld.positions.map((x: any) => x.positionName)),
                ];
                profilePosType = [
                  ...new Set(
                    positionMasterOld.positions
                      .filter((x: any) => x.posType != null)
                      .map((x: any) => x.posType.posTypeName),
                  ),
                ];
                profilePosLevel = [
                  ...new Set(
                    positionMasterOld.positions
                      .filter((x: any) => x.posLevel != null)
                      .map((x: any) => x.posLevel.posLevelName),
                  ),
                ];
                profilePosExecutive = [
                  ...new Set(
                    positionMasterOld.positions
                      .filter((x: any) => x.posExecutive != null)
                      .map((x: any) => x.posExecutive.posExecutiveName),
                  ),
                ];
              }
            }
            let education: any = "";
            if (
              posMaster.next_holder != null &&
              posMaster.next_holder.profileEducations != null &&
              posMaster.next_holder.profileEducations.length > 0
            ) {
              let _education: any = posMaster.next_holder.profileEducations.sort(
                (a, b) =>
                  (b.finishDate == null ? 0 : b.finishDate.getTime()) -
                  (a.finishDate == null ? 0 : a.finishDate.getTime()),
              );
              if (_education.length > 0) {
                education = _education[0];
              }
            } else {
              if (
                posMaster.current_holder != null &&
                posMaster.current_holder.profileEducations != null &&
                posMaster.current_holder.profileEducations.length > 0
              ) {
                let _education: any = posMaster.current_holder.profileEducations.sort(
                  (a, b) =>
                    (b.finishDate == null ? 0 : b.finishDate.getTime()) -
                    (a.finishDate == null ? 0 : a.finishDate.getTime()),
                );
                if (_education.length > 0) {
                  education = _education[0];
                }
              }
            }
            let salary: any = "";
            if (
              posMaster.next_holder != null &&
              posMaster.next_holder.profileSalary != null &&
              posMaster.next_holder.profileSalary.length > 0
            ) {
              let _salary: any = posMaster.next_holder.profileSalary.sort(
                (a, b) =>
                  (b.commandDateAffect == null ? 0 : b.commandDateAffect.getTime()) -
                  (a.commandDateAffect == null ? 0 : a.commandDateAffect.getTime()),
              );
              if (_salary.length > 0) {
                salary = _salary[0];
              }
            } else {
              if (
                posMaster.current_holder != null &&
                posMaster.current_holder.profileSalary != null &&
                posMaster.current_holder.profileSalary.length > 0
              ) {
                let _salary: any = posMaster.current_holder.profileSalary.sort(
                  (a, b) =>
                    (b.commandDateAffect == null ? 0 : b.commandDateAffect.getTime()) -
                    (a.commandDateAffect == null ? 0 : a.commandDateAffect.getTime()),
                );
                if (_salary.length > 0) {
                  salary = _salary[0];
                }
              }
            }
            if (positionMasterProfileOld == null && posMaster.next_holder != null 
              && posMaster.next_holder.current_holders == null
            ) {
              positionMasterProfileOld = positionMasterOld
            }
            let node = {
              posMasterOrder: posMaster.posMasterOrder, //
              isSit: posMaster.isSit, //
              orgTreeName: orgChild1.orgChild1Name,
              orgTreeShortName: orgChild1.orgChild1ShortName,
              posMasterNo: posMaster.posMasterNo,
              positionName:
                posMaster.next_holder == null
                  ? positionName.join(" หรือ ")
                  : posMaster.isSit == false
                    ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                        ?.positionName
                    : posMaster.next_holder.position,
              posType:
                posMaster.next_holder == null
                  ? posType.join(" หรือ ")
                  : posMaster.isSit == false
                    ? posMaster.positions.find((x: any) => x.positionIsSelected == true)?.posType
                        ?.posTypeName
                    : posMaster.next_holder.posType == null
                      ? "-"
                      : posMaster.next_holder.posType.posTypeName,
              posLevel:
                posMaster.next_holder == null
                  ? posLevel.join(" หรือ ")
                  : posMaster.isSit == false
                    ? posMaster.positions.find((x: any) => x.positionIsSelected == true)?.posLevel
                        ?.posLevelName
                    : posMaster.next_holder.posLevel == null
                      ? "-"
                      : posMaster.next_holder.posLevel.posLevelName,
              posExecutive:
                posMaster.next_holder == null
                  ? posExecutive.join(" หรือ ")
                  : posMaster.isSit == false
                    ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                        ?.posExecutive?.posExecutiveName
                    : positionMasterProfileOld == null
                      ? "-"
                      : positionMasterProfileOld.positions.find(
                          (x: any) => x.positionIsSelected == true,
                        )?.posExecutive?.posExecutiveName,

              profileOrgName:
                posMaster.next_holder == null
                  ? orgChild1.orgChild1Name
                  : positionMasterProfileOld == null
                    ? "-"
                    : positionMasterProfileOld.orgChild4 != null
                      ? positionMasterProfileOld.orgChild4.orgChild4Name
                      : positionMasterProfileOld.orgChild3 != null
                        ? positionMasterProfileOld.orgChild3.orgChild3Name
                        : positionMasterProfileOld.orgChild2 != null
                          ? positionMasterProfileOld.orgChild2.orgChild2Name
                          : positionMasterProfileOld.orgChild1 != null
                            ? positionMasterProfileOld.orgChild1.orgChild1Name
                            : positionMasterProfileOld.orgRoot != null
                              ? positionMasterProfileOld.orgRoot.orgRootName
                              : "-",
              profileOrgShortName:
                posMaster.next_holder == null
                  ? orgChild1.orgChild1ShortName
                  : positionMasterProfileOld == null
                    ? "-"
                    : positionMasterProfileOld.orgChild4 != null
                      ? positionMasterProfileOld.orgChild4.orgChild4ShortName
                      : positionMasterProfileOld.orgChild3 != null
                        ? positionMasterProfileOld.orgChild3.orgChild3ShortName
                        : positionMasterProfileOld.orgChild2 != null
                          ? positionMasterProfileOld.orgChild2.orgChild2ShortName
                          : positionMasterProfileOld.orgChild1 != null
                            ? positionMasterProfileOld.orgChild1.orgChild1ShortName
                            : positionMasterProfileOld.orgRoot != null
                              ? positionMasterProfileOld.orgRoot.orgRootShortName
                              : "-",
              profileFullname:
                posMaster.next_holder == null
                  ? posMaster.current_holder == null
                    ? "- ว่าง -"
                    : `${posMaster.current_holder.prefix}${posMaster.current_holder.firstName} ${posMaster.current_holder.lastName}`
                  : `${posMaster.next_holder.prefix}${posMaster.next_holder.firstName} ${posMaster.next_holder.lastName}`,
              profilePosMasterNo:
                posMaster.next_holder == null
                  ? positionMasterOld == null
                    ? "-"
                    : positionMasterOld.posMasterNo
                  : positionMasterProfileOld == null
                    ? "-"
                    : positionMasterProfileOld.posMasterNo,
              profilePositionName:
                posMaster.next_holder == null
                  ? positionMasterOld == null
                    ? positionName.join(" หรือ ")
                    : profilePositionName.join(" หรือ ")
                  : posMaster.next_holder.position,
              profilePosType:
                posMaster.next_holder == null
                  ? positionMasterOld == null
                    ? posType.join(" หรือ ")
                    : profilePosType.join(" หรือ ")
                  : positionMasterProfileOld == null
                    ? "-"
                    // : posMaster.next_holder.posType.posTypeName,
                    : positionMasterProfileOld.positions.find(
                          (x: any) => x.positionIsSelected == true,
                        )?.posType?.posTypeName,
              profilePosLevel:
                posMaster.next_holder == null
                  ? positionMasterOld == null
                    ? posLevel.join(" หรือ ")
                    : profilePosLevel.join(" หรือ ")
                  : positionMasterProfileOld == null
                    ? "-"
                    // : posMaster.next_holder.posLevel.posLevelName,
                    : positionMasterProfileOld.positions.find(
                          (x: any) => x.positionIsSelected == true,
                        )?.posLevel?.posLevelName,
              profilePosExecutive:
                posMaster.next_holder == null
                  ? positionMasterOld == null
                    ? posExecutive.join(" หรือ ")
                    : profilePosExecutive.join(" หรือ ")
                  : positionMasterProfileOld == null
                    ? "-"
                    : positionMasterProfileOld.positions.find(
                        (x: any) => x.positionIsSelected == true,
                      )?.posExecutive?.posExecutiveName,
              education: education == "" ? "" : education.degree,
              salary: salary == "" ? "" : salary.amount,
              reason: posMaster.reason,
            };
            if (_node == null) {
              const head = {
                posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName.toString()),
                profileFullname: 
                  posMaster.next_holder == null 
                    ? Extension.ToThaiNumber(node.profileOrgName.toString())
                    : Extension.ToThaiNumber(node.orgTreeName.toString()),
                posExecutive: Extension.ToThaiNumber(node.orgTreeName.toString()),
                positionName: "",
                posType: "",
                posLevel: "",
                profilePosMasterNo: 
                  posMaster.next_holder == null 
                    ? Extension.ToThaiNumber(node.profileOrgShortName.toString())
                    : Extension.ToThaiNumber(node.orgTreeShortName.toString()),
                profilePosExecutive: "",
                profilePositionName: "",
                profilePosType: "",
                profilePosLevel: "",
                education: "",
                salary: "",
                reason: "",
              };
              data.push(head);
              const _head = {
                no: Extension.ToThaiNumber(no.toString()),
                posMasterNo:
                  node.posMasterNo == null
                    ? ""
                    : Extension.ToThaiNumber(node.posMasterNo.toString()),
                profileFullname:
                  node.profileFullname == null
                    ? ""
                    : Extension.ToThaiNumber(node.profileFullname.toString()),
                posExecutive:
                  node.posExecutive == null
                    ? ""
                    : Extension.ToThaiNumber(node.posExecutive.toString()),
                positionName:
                  node.positionName == null
                    ? ""
                    : Extension.ToThaiNumber(node.positionName.toString()),
                posType:
                  node.posType == null ? "" : Extension.ToThaiNumber(node.posType.toString()),
                posLevel:
                  node.posLevel == null ? "" : Extension.ToThaiNumber(node.posLevel.toString()),
                profilePosMasterNo: Extension.ToThaiNumber(node.profilePosMasterNo.toString()),
                profilePosExecutive:
                  node.profilePosExecutive == null
                    ? ""
                    : Extension.ToThaiNumber(node.profilePosExecutive.toString()),
                profilePositionName:
                  node.profilePositionName == null
                    ? ""
                    : Extension.ToThaiNumber(node.profilePositionName.toString()),
                profilePosType:
                  node.profilePosType == null
                    ? ""
                    : Extension.ToThaiNumber(node.profilePosType.toString()),
                profilePosLevel:
                  node.profilePosLevel == null
                    ? ""
                    : Extension.ToThaiNumber(node.profilePosLevel.toString()),
                education:
                  node.education == null ? "" : Extension.ToThaiNumber(node.education.toString()),
                salary: node.salary ? Extension.ToThaiNumber(node.salary.toLocaleString()) : "",
                reason: node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
              };
              data.push(_head);
            } else {
              if (
                node.orgTreeShortName != _node.orgTreeShortName ||
                node.orgTreeName != _node.orgTreeName ||
                node.profileOrgShortName != _node.profileOrgShortName ||
                node.profileOrgName != _node.profileOrgName
              ) {
                const head = {
                  posMasterNo:
                    node.orgTreeShortName == _node.orgTreeShortName ? "" : node.orgTreeShortName,
                  profileFullname:
                    node.profileOrgName == _node.profileOrgName ? "" : node.profileOrgName,
                  posExecutive: node.orgTreeName == _node.orgTreeName ? "" : node.orgTreeName,
                  positionName: "",
                  posType: "",
                  posLevel: "",
                  profilePosMasterNo:
                    node.profileOrgShortName == _node.profileOrgShortName
                      ? ""
                      : node.profileOrgShortName,
                  profilePosExecutive: "",
                  profilePositionName: "",
                  profilePosType: "",
                  profilePosLevel: "",
                  education: "",
                  salary: "",
                  reason: "",
                };
                data.push(head);
                _node == null;
              }
              const head = {
                no: Extension.ToThaiNumber(no.toString()),
                posMasterNo:
                  node.posMasterNo == null
                    ? ""
                    : Extension.ToThaiNumber(node.posMasterNo.toString()),
                profileFullname:
                  node.profileFullname == null
                    ? ""
                    : Extension.ToThaiNumber(node.profileFullname.toString()),
                posExecutive:
                  node.posExecutive == null
                    ? ""
                    : Extension.ToThaiNumber(node.posExecutive.toString()),
                positionName:
                  node.positionName == null
                    ? ""
                    : Extension.ToThaiNumber(node.positionName.toString()),
                posType:
                  node.posType == null ? "" : Extension.ToThaiNumber(node.posType.toString()),
                posLevel:
                  node.posLevel == null ? "" : Extension.ToThaiNumber(node.posLevel.toString()),
                profilePosMasterNo: Extension.ToThaiNumber(node.profilePosMasterNo.toString()),
                profilePosExecutive:
                  node.profilePosExecutive == null
                    ? ""
                    : Extension.ToThaiNumber(node.profilePosExecutive.toString()),
                profilePositionName:
                  node.profilePositionName == null
                    ? ""
                    : Extension.ToThaiNumber(node.profilePositionName.toString()),
                profilePosType:
                  node.profilePosType == null
                    ? ""
                    : Extension.ToThaiNumber(node.profilePosType.toString()),
                profilePosLevel:
                  node.profilePosLevel == null
                    ? ""
                    : Extension.ToThaiNumber(node.profilePosLevel.toString()),
                education:
                  node.education == null ? "" : Extension.ToThaiNumber(node.education.toString()),
                salary: node.salary ? Extension.ToThaiNumber(node.salary.toLocaleString()) : "",
                reason: node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
              };
              data.push(head);
            }
            no += 1;
            _node = node;
          }
        }
        _node = null;

        for (let orgChild2 of orgChild2Data.filter(
          (orgChild2) => orgChild2.orgChild1Id === orgChild1.id,
        )) {
          const posMastersFiltered2 = orgChild2.posMasters.sort(
            (a, b) => a.posMasterOrder - b.posMasterOrder,
          );
          for (let posMaster of posMastersFiltered2) {
            if (posMaster.orgChild3Id == null) {
              const positionName = [...new Set(posMaster.positions.map((x) => x.positionName))];
              const posType = [
                ...new Set(
                  posMaster.positions
                    .filter((x: any) => x.posType != null)
                    .map((x) => x.posType.posTypeName),
                ),
              ];
              const posLevel = [
                ...new Set(
                  posMaster.positions
                    .filter((x: any) => x.posLevel != null)
                    .map((x) => x.posLevel.posLevelName),
                ),
              ];
              const posExecutive = [
                ...new Set(
                  posMaster.positions
                    .filter((x: any) => x.posExecutive != null)
                    .map((x) => x.posExecutive.posExecutiveName),
                ),
              ];
              let positionMasterProfileOld: any = null;
              if (posMaster.next_holder != null && posMaster.next_holder.current_holders) {
                positionMasterProfileOld = posMaster.next_holder.current_holders.find(
                  (x) => x.orgRevisionId == orgRevisionActive.id,
                );
              }

              let positionMasterOld: any = null;
              let profilePositionName: any = [];
              let profilePosType: any = [];
              let profilePosLevel: any = [];
              let profilePosExecutive: any = [];
              if (
                posMaster.ancestorDNA != null &&
                posMaster.ancestorDNA != "" &&
                orgRevisionActive &&
                orgRevisionActive.posMasters
              ) {
                positionMasterOld = orgRevisionActive.posMasters.find(
                  (x: any) =>
                    x.orgRevisionId == orgRevisionActive.id &&
                    x.ancestorDNA == posMaster.ancestorDNA,
                );
                if (positionMasterOld && positionMasterOld.positions) {
                  profilePositionName = [
                    ...new Set(positionMasterOld.positions.map((x: any) => x.positionName)),
                  ];
                  profilePosType = [
                    ...new Set(
                      positionMasterOld.positions
                        .filter((x: any) => x.posType != null)
                        .map((x: any) => x.posType.posTypeName),
                    ),
                  ];
                  profilePosLevel = [
                    ...new Set(
                      positionMasterOld.positions
                        .filter((x: any) => x.posLevel != null)
                        .map((x: any) => x.posLevel.posLevelName),
                    ),
                  ];
                  profilePosExecutive = [
                    ...new Set(
                      positionMasterOld.positions
                        .filter((x: any) => x.posExecutive != null)
                        .map((x: any) => x.posExecutive.posExecutiveName),
                    ),
                  ];
                }
              }
              let education: any = "";
              if (
                posMaster.next_holder != null &&
                posMaster.next_holder.profileEducations != null &&
                posMaster.next_holder.profileEducations.length > 0
              ) {
                let _education: any = posMaster.next_holder.profileEducations.sort(
                  (a, b) =>
                    (b.finishDate == null ? 0 : b.finishDate.getTime()) -
                    (a.finishDate == null ? 0 : a.finishDate.getTime()),
                );
                if (_education.length > 0) {
                  education = _education[0];
                }
              } else {
                if (
                  posMaster.current_holder != null &&
                  posMaster.current_holder.profileEducations != null &&
                  posMaster.current_holder.profileEducations.length > 0
                ) {
                  let _education: any = posMaster.current_holder.profileEducations.sort(
                    (a, b) =>
                      (b.finishDate == null ? 0 : b.finishDate.getTime()) -
                      (a.finishDate == null ? 0 : a.finishDate.getTime()),
                  );
                  if (_education.length > 0) {
                    education = _education[0];
                  }
                }
              }
              let salary: any = "";
              if (
                posMaster.next_holder != null &&
                posMaster.next_holder.profileSalary != null &&
                posMaster.next_holder.profileSalary.length > 0
              ) {
                let _salary: any = posMaster.next_holder.profileSalary.sort(
                  (a, b) =>
                    (b.commandDateAffect == null ? 0 : b.commandDateAffect.getTime()) -
                    (a.commandDateAffect == null ? 0 : a.commandDateAffect.getTime()),
                );
                if (_salary.length > 0) {
                  salary = _salary[0];
                }
              } else {
                if (
                  posMaster.current_holder != null &&
                  posMaster.current_holder.profileSalary != null &&
                  posMaster.current_holder.profileSalary.length > 0
                ) {
                  let _salary: any = posMaster.current_holder.profileSalary.sort(
                    (a, b) =>
                      (b.commandDateAffect == null ? 0 : b.commandDateAffect.getTime()) -
                      (a.commandDateAffect == null ? 0 : a.commandDateAffect.getTime()),
                  );
                  if (_salary.length > 0) {
                    salary = _salary[0];
                  }
                }
              }
              if (positionMasterProfileOld == null && posMaster.next_holder != null 
                && posMaster.next_holder.current_holders == null
              ) {
                positionMasterProfileOld = positionMasterOld
              }
              let node = {
                posMasterOrder: posMaster.posMasterOrder, //
                isSit: posMaster.isSit, //
                orgTreeName: orgChild2.orgChild2Name,
                orgTreeShortName: orgChild2.orgChild2ShortName,
                posMasterNo: posMaster.posMasterNo,
                positionName:
                  posMaster.next_holder == null
                    ? positionName.join(" หรือ ")
                    : posMaster.isSit == false
                      ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                          ?.positionName
                      : posMaster.next_holder.position,
                posType:
                  posMaster.next_holder == null
                    ? posType.join(" หรือ ")
                    : posMaster.isSit == false
                      ? posMaster.positions.find((x: any) => x.positionIsSelected == true)?.posType
                          ?.posTypeName
                      : posMaster.next_holder.posType == null
                        ? "-"
                        : posMaster.next_holder.posType.posTypeName,
                posLevel:
                  posMaster.next_holder == null
                    ? posLevel.join(" หรือ ")
                    : posMaster.isSit == false
                      ? posMaster.positions.find((x: any) => x.positionIsSelected == true)?.posLevel
                          ?.posLevelName
                      : posMaster.next_holder.posLevel == null
                        ? "-"
                        : posMaster.next_holder.posLevel.posLevelName,
                posExecutive:
                  posMaster.next_holder == null
                    ? posExecutive.join(" หรือ ")
                    : posMaster.isSit == false
                      ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                          ?.posExecutive?.posExecutiveName
                      : positionMasterProfileOld == null
                        ? "-"
                        : positionMasterProfileOld.positions.find(
                            (x: any) => x.positionIsSelected == true,
                          )?.posExecutive?.posExecutiveName,

                profileOrgName:
                  posMaster.next_holder == null
                    ? orgChild2.orgChild2Name
                    : positionMasterProfileOld == null
                      ? "-"
                      : positionMasterProfileOld.orgChild4 != null
                        ? positionMasterProfileOld.orgChild4.orgChild4Name
                        : positionMasterProfileOld.orgChild3 != null
                          ? positionMasterProfileOld.orgChild3.orgChild3Name
                          : positionMasterProfileOld.orgChild2 != null
                            ? positionMasterProfileOld.orgChild2.orgChild2Name
                            : positionMasterProfileOld.orgChild1 != null
                              ? positionMasterProfileOld.orgChild1.orgChild1Name
                              : positionMasterProfileOld.orgRoot != null
                                ? positionMasterProfileOld.orgRoot.orgRootName
                                : "-",
                profileOrgShortName:
                  posMaster.next_holder == null
                    ? orgChild2.orgChild2ShortName
                    : positionMasterProfileOld == null
                      ? "-"
                      : positionMasterProfileOld.orgChild4 != null
                        ? positionMasterProfileOld.orgChild4.orgChild4ShortName
                        : positionMasterProfileOld.orgChild3 != null
                          ? positionMasterProfileOld.orgChild3.orgChild3ShortName
                          : positionMasterProfileOld.orgChild2 != null
                            ? positionMasterProfileOld.orgChild2.orgChild2ShortName
                            : positionMasterProfileOld.orgChild1 != null
                              ? positionMasterProfileOld.orgChild1.orgChild1ShortName
                              : positionMasterProfileOld.orgRoot != null
                                ? positionMasterProfileOld.orgRoot.orgRootShortName
                                : "-",
                profileFullname:
                  posMaster.next_holder == null
                    ? posMaster.current_holder == null
                      ? "- ว่าง -"
                      : `${posMaster.current_holder.prefix}${posMaster.current_holder.firstName} ${posMaster.current_holder.lastName}`
                    : `${posMaster.next_holder.prefix}${posMaster.next_holder.firstName} ${posMaster.next_holder.lastName}`,
                profilePosMasterNo:
                  posMaster.next_holder == null
                    ? positionMasterOld == null
                      ? "-"
                      : positionMasterOld.posMasterNo
                    : positionMasterProfileOld == null
                      ? "-"
                      : positionMasterProfileOld.posMasterNo,
                profilePositionName:
                  posMaster.next_holder == null
                    ? positionMasterOld == null
                      ? positionName.join(" หรือ ")
                      : profilePositionName.join(" หรือ ")
                    : posMaster.next_holder.position,
                profilePosType:
                  posMaster.next_holder == null
                    ? positionMasterOld == null
                      ? posType.join(" หรือ ")
                      : profilePosType.join(" หรือ ")
                    : positionMasterProfileOld == null
                      ? "-"
                      // : posMaster.next_holder.posType.posTypeName,
                      : positionMasterProfileOld.positions.find(
                            (x: any) => x.positionIsSelected == true,
                          )?.posType?.posTypeName,
                profilePosLevel:
                  posMaster.next_holder == null
                    ? positionMasterOld == null
                      ? posLevel.join(" หรือ ")
                      : profilePosLevel.join(" หรือ ")
                    : positionMasterProfileOld == null
                      ? "-"
                      // : posMaster.next_holder.posLevel.posLevelName,
                      : positionMasterProfileOld.positions.find(
                            (x: any) => x.positionIsSelected == true,
                          )?.posLevel?.posLevelName,
                profilePosExecutive:
                  posMaster.next_holder == null
                    ? positionMasterOld == null
                      ? posExecutive.join(" หรือ ")
                      : profilePosExecutive.join(" หรือ ")
                    : positionMasterProfileOld == null
                      ? "-"
                      : positionMasterProfileOld.positions.find(
                          (x: any) => x.positionIsSelected == true,
                        )?.posExecutive?.posExecutiveName,
                education: education == "" ? "" : education.degree,
                salary: salary == "" ? "" : salary.amount,
                reason: posMaster.reason,
              };
              if (_node == null) {
                const head = {
                  posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName.toString()),
                  profileFullname: 
                    posMaster.next_holder == null 
                      ? Extension.ToThaiNumber(node.profileOrgName.toString())
                      : Extension.ToThaiNumber(node.orgTreeName.toString()),
                  posExecutive: Extension.ToThaiNumber(node.orgTreeName.toString()),
                  positionName: "",
                  posType: "",
                  posLevel: "",
                  profilePosMasterNo: 
                    posMaster.next_holder == null 
                      ? Extension.ToThaiNumber(node.profileOrgShortName.toString())
                      : Extension.ToThaiNumber(node.orgTreeShortName.toString()),
                  profilePosExecutive: "",
                  profilePositionName: "",
                  profilePosType: "",
                  profilePosLevel: "",
                  education: "",
                  salary: "",
                  reason: "",
                };
                data.push(head);
                const _head = {
                  no: Extension.ToThaiNumber(no.toString()),
                  posMasterNo:
                    node.posMasterNo == null
                      ? ""
                      : Extension.ToThaiNumber(node.posMasterNo.toString()),
                  profileFullname:
                    node.profileFullname == null
                      ? ""
                      : Extension.ToThaiNumber(node.profileFullname.toString()),
                  posExecutive:
                    node.posExecutive == null
                      ? ""
                      : Extension.ToThaiNumber(node.posExecutive.toString()),
                  positionName:
                    node.positionName == null
                      ? ""
                      : Extension.ToThaiNumber(node.positionName.toString()),
                  posType:
                    node.posType == null ? "" : Extension.ToThaiNumber(node.posType.toString()),
                  posLevel:
                    node.posLevel == null ? "" : Extension.ToThaiNumber(node.posLevel.toString()),
                  profilePosMasterNo: Extension.ToThaiNumber(node.profilePosMasterNo.toString()),
                  profilePosExecutive:
                    node.profilePosExecutive == null
                      ? ""
                      : Extension.ToThaiNumber(node.profilePosExecutive.toString()),
                  profilePositionName:
                    node.profilePositionName == null
                      ? ""
                      : Extension.ToThaiNumber(node.profilePositionName.toString()),
                  profilePosType:
                    node.profilePosType == null
                      ? ""
                      : Extension.ToThaiNumber(node.profilePosType.toString()),
                  profilePosLevel:
                    node.profilePosLevel == null
                      ? ""
                      : Extension.ToThaiNumber(node.profilePosLevel.toString()),
                  education:
                    node.education == null ? "" : Extension.ToThaiNumber(node.education.toString()),
                  salary: node.salary ? Extension.ToThaiNumber(node.salary.toLocaleString()) : "",
                  reason: node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
                };
                data.push(_head);
              } else {
                if (
                  node.orgTreeShortName != _node.orgTreeShortName ||
                  node.orgTreeName != _node.orgTreeName ||
                  node.profileOrgShortName != _node.profileOrgShortName ||
                  node.profileOrgName != _node.profileOrgName
                ) {
                  const head = {
                    posMasterNo:
                      node.orgTreeShortName == _node.orgTreeShortName ? "" : node.orgTreeShortName,
                    profileFullname:
                      node.profileOrgName == _node.profileOrgName ? "" : node.profileOrgName,
                    posExecutive: node.orgTreeName == _node.orgTreeName ? "" : node.orgTreeName,
                    positionName: "",
                    posType: "",
                    posLevel: "",
                    profilePosMasterNo:
                      node.profileOrgShortName == _node.profileOrgShortName
                        ? ""
                        : node.profileOrgShortName,
                    profilePosExecutive: "",
                    profilePositionName: "",
                    profilePosType: "",
                    profilePosLevel: "",
                    education: "",
                    salary: "",
                    reason: "",
                  };
                  data.push(head);
                  _node == null;
                }
                const head = {
                  no: Extension.ToThaiNumber(no.toString()),
                  posMasterNo:
                    node.posMasterNo == null
                      ? ""
                      : Extension.ToThaiNumber(node.posMasterNo.toString()),
                  profileFullname:
                    node.profileFullname == null
                      ? ""
                      : Extension.ToThaiNumber(node.profileFullname.toString()),
                  posExecutive:
                    node.posExecutive == null
                      ? ""
                      : Extension.ToThaiNumber(node.posExecutive.toString()),
                  positionName:
                    node.positionName == null
                      ? ""
                      : Extension.ToThaiNumber(node.positionName.toString()),
                  posType:
                    node.posType == null ? "" : Extension.ToThaiNumber(node.posType.toString()),
                  posLevel:
                    node.posLevel == null ? "" : Extension.ToThaiNumber(node.posLevel.toString()),
                  profilePosMasterNo: Extension.ToThaiNumber(node.profilePosMasterNo.toString()),
                  profilePosExecutive:
                    node.profilePosExecutive == null
                      ? ""
                      : Extension.ToThaiNumber(node.profilePosExecutive.toString()),
                  profilePositionName:
                    node.profilePositionName == null
                      ? ""
                      : Extension.ToThaiNumber(node.profilePositionName.toString()),
                  profilePosType:
                    node.profilePosType == null
                      ? ""
                      : Extension.ToThaiNumber(node.profilePosType.toString()),
                  profilePosLevel:
                    node.profilePosLevel == null
                      ? ""
                      : Extension.ToThaiNumber(node.profilePosLevel.toString()),
                  education:
                    node.education == null ? "" : Extension.ToThaiNumber(node.education.toString()),
                  salary: node.salary ? Extension.ToThaiNumber(node.salary.toLocaleString()) : "",
                  reason: node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
                };
                data.push(head);
              }
              no += 1;
              _node = node;
            }
          }
          _node = null;

          for (let orgChild3 of orgChild3Data.filter(
            (orgChild3) => orgChild3.orgChild2Id === orgChild2.id,
          )) {
            const posMastersFiltered3 = orgChild3.posMasters.sort(
              (a, b) => a.posMasterOrder - b.posMasterOrder,
            );
            for (let posMaster of posMastersFiltered3) {
              if (posMaster.orgChild4Id == null) {
                console.log(posMaster);
                const positionName = [...new Set(posMaster.positions.map((x) => x.positionName))];
                const posType = [
                  ...new Set(
                    posMaster.positions
                      .filter((x: any) => x.posType != null)
                      .map((x) => x.posType.posTypeName),
                  ),
                ];
                const posLevel = [
                  ...new Set(
                    posMaster.positions
                      .filter((x: any) => x.posLevel != null)
                      .map((x) => x.posLevel.posLevelName),
                  ),
                ];
                const posExecutive = [
                  ...new Set(
                    posMaster.positions
                      .filter((x: any) => x.posExecutive != null)
                      .map((x) => x.posExecutive.posExecutiveName),
                  ),
                ];
                let positionMasterProfileOld: any = null;
                if (posMaster.next_holder != null && posMaster.next_holder.current_holders) {
                  positionMasterProfileOld = posMaster.next_holder.current_holders.find(
                    (x) => x.orgRevisionId == orgRevisionActive.id,
                  );
                }

                let positionMasterOld: any = null;
                let profilePositionName: any = [];
                let profilePosType: any = [];
                let profilePosLevel: any = [];
                let profilePosExecutive: any = [];
                if (
                  posMaster.ancestorDNA != null &&
                  posMaster.ancestorDNA != "" &&
                  orgRevisionActive &&
                  orgRevisionActive.posMasters
                ) {
                  positionMasterOld = orgRevisionActive.posMasters.find(
                    (x: any) =>
                      x.orgRevisionId == orgRevisionActive.id &&
                      x.ancestorDNA == posMaster.ancestorDNA,
                  );
                  if (positionMasterOld && positionMasterOld.positions) {
                    profilePositionName = [
                      ...new Set(positionMasterOld.positions.map((x: any) => x.positionName)),
                    ];
                    profilePosType = [
                      ...new Set(
                        positionMasterOld.positions
                          .filter((x: any) => x.posType != null)
                          .map((x: any) => x.posType.posTypeName),
                      ),
                    ];
                    profilePosLevel = [
                      ...new Set(
                        positionMasterOld.positions
                          .filter((x: any) => x.posLevel != null)
                          .map((x: any) => x.posLevel.posLevelName),
                      ),
                    ];
                    profilePosExecutive = [
                      ...new Set(
                        positionMasterOld.positions
                          .filter((x: any) => x.posExecutive != null)
                          .map((x: any) => x.posExecutive.posExecutiveName),
                      ),
                    ];
                  }
                }
                let education: any = "";
                if (
                  posMaster.next_holder != null &&
                  posMaster.next_holder.profileEducations != null &&
                  posMaster.next_holder.profileEducations.length > 0
                ) {
                  let _education: any = posMaster.next_holder.profileEducations.sort(
                    (a, b) =>
                      (b.finishDate == null ? 0 : b.finishDate.getTime()) -
                      (a.finishDate == null ? 0 : a.finishDate.getTime()),
                  );
                  if (_education.length > 0) {
                    education = _education[0];
                  }
                } else {
                  if (
                    posMaster.current_holder != null &&
                    posMaster.current_holder.profileEducations != null &&
                    posMaster.current_holder.profileEducations.length > 0
                  ) {
                    let _education: any = posMaster.current_holder.profileEducations.sort(
                      (a, b) =>
                        (b.finishDate == null ? 0 : b.finishDate.getTime()) -
                        (a.finishDate == null ? 0 : a.finishDate.getTime()),
                    );
                    if (_education.length > 0) {
                      education = _education[0];
                    }
                  }
                }
                let salary: any = "";
                if (
                  posMaster.next_holder != null &&
                  posMaster.next_holder.profileSalary != null &&
                  posMaster.next_holder.profileSalary.length > 0
                ) {
                  let _salary: any = posMaster.next_holder.profileSalary.sort(
                    (a, b) =>
                      (b.commandDateAffect == null ? 0 : b.commandDateAffect.getTime()) -
                      (a.commandDateAffect == null ? 0 : a.commandDateAffect.getTime()),
                  );
                  if (_salary.length > 0) {
                    salary = _salary[0];
                  }
                } else {
                  if (
                    posMaster.current_holder != null &&
                    posMaster.current_holder.profileSalary != null &&
                    posMaster.current_holder.profileSalary.length > 0
                  ) {
                    let _salary: any = posMaster.current_holder.profileSalary.sort(
                      (a, b) =>
                        (b.commandDateAffect == null ? 0 : b.commandDateAffect.getTime()) -
                        (a.commandDateAffect == null ? 0 : a.commandDateAffect.getTime()),
                    );
                    if (_salary.length > 0) {
                      salary = _salary[0];
                    }
                  }
                }
                if (positionMasterProfileOld == null && posMaster.next_holder != null 
                  && posMaster.next_holder.current_holders == null
                ) {
                  positionMasterProfileOld = positionMasterOld
                }
                let node = {
                  posMasterOrder: posMaster.posMasterOrder, //
                  isSit: posMaster.isSit, //
                  orgTreeName: orgChild3.orgChild3Name,
                  orgTreeShortName: orgChild3.orgChild3ShortName,
                  posMasterNo: posMaster.posMasterNo,
                  positionName:
                    posMaster.next_holder == null
                      ? positionName.join(" หรือ ")
                      : posMaster.isSit == false
                        ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                            ?.positionName
                        : posMaster.next_holder.position,
                  posType:
                    posMaster.next_holder == null
                      ? posType.join(" หรือ ")
                      : posMaster.isSit == false
                        ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                            ?.posType?.posTypeName
                        : posMaster.next_holder.posType == null
                          ? "-"
                          : posMaster.next_holder.posType.posTypeName,
                  posLevel:
                    posMaster.next_holder == null
                      ? posLevel.join(" หรือ ")
                      : posMaster.isSit == false
                        ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                            ?.posLevel?.posLevelName
                        : posMaster.next_holder.posLevel == null
                          ? "-"
                          : posMaster.next_holder.posLevel.posLevelName,
                  posExecutive:
                    posMaster.next_holder == null
                      ? posExecutive.join(" หรือ ")
                      : posMaster.isSit == false
                        ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                            ?.posExecutive?.posExecutiveName
                        : positionMasterProfileOld == null
                          ? "-"
                          : positionMasterProfileOld.positions.find(
                              (x: any) => x.positionIsSelected == true,
                            )?.posExecutive?.posExecutiveName,

                  profileOrgName:
                    posMaster.next_holder == null
                      ? orgChild3.orgChild3Name
                      : positionMasterProfileOld == null
                        ? "-"
                        : positionMasterProfileOld.orgChild4 != null
                          ? positionMasterProfileOld.orgChild4.orgChild4Name
                          : positionMasterProfileOld.orgChild3 != null
                            ? positionMasterProfileOld.orgChild3.orgChild3Name
                            : positionMasterProfileOld.orgChild2 != null
                              ? positionMasterProfileOld.orgChild2.orgChild2Name
                              : positionMasterProfileOld.orgChild1 != null
                                ? positionMasterProfileOld.orgChild1.orgChild1Name
                                : positionMasterProfileOld.orgRoot != null
                                  ? positionMasterProfileOld.orgRoot.orgRootName
                                  : "-",
                  profileOrgShortName:
                    posMaster.next_holder == null
                      ? orgChild3.orgChild3ShortName
                      : positionMasterProfileOld == null
                        ? "-"
                        : positionMasterProfileOld.orgChild4 != null
                          ? positionMasterProfileOld.orgChild4.orgChild4ShortName
                          : positionMasterProfileOld.orgChild3 != null
                            ? positionMasterProfileOld.orgChild3.orgChild3ShortName
                            : positionMasterProfileOld.orgChild2 != null
                              ? positionMasterProfileOld.orgChild2.orgChild2ShortName
                              : positionMasterProfileOld.orgChild1 != null
                                ? positionMasterProfileOld.orgChild1.orgChild1ShortName
                                : positionMasterProfileOld.orgRoot != null
                                  ? positionMasterProfileOld.orgRoot.orgRootShortName
                                  : "-",
                  profileFullname:
                    posMaster.next_holder == null
                      ? posMaster.current_holder == null
                        ? "- ว่าง -"
                        : `${posMaster.current_holder.prefix}${posMaster.current_holder.firstName} ${posMaster.current_holder.lastName}`
                      : `${posMaster.next_holder.prefix}${posMaster.next_holder.firstName} ${posMaster.next_holder.lastName}`,
                  profilePosMasterNo:
                    posMaster.next_holder == null
                      ? positionMasterOld == null
                        ? "-"
                        : positionMasterOld.posMasterNo
                      : positionMasterProfileOld == null
                        ? "-"
                        : positionMasterProfileOld.posMasterNo,
                  profilePositionName:
                    posMaster.next_holder == null
                      ? positionMasterOld == null
                        ? positionName.join(" หรือ ")
                        : profilePositionName.join(" หรือ ")
                      : posMaster.next_holder.position,
                  profilePosType:
                    posMaster.next_holder == null
                      ? positionMasterOld == null
                        ? posType.join(" หรือ ")
                        : profilePosType.join(" หรือ ")
                      : positionMasterProfileOld == null
                        ? "-"
                        // : posMaster.next_holder.posType.posTypeName,
                        : positionMasterProfileOld.positions.find(
                              (x: any) => x.positionIsSelected == true,
                            )?.posType?.posTypeName,
                  profilePosLevel:
                    posMaster.next_holder == null
                      ? positionMasterOld == null
                        ? posLevel.join(" หรือ ")
                        : profilePosLevel.join(" หรือ ")
                      : positionMasterProfileOld == null
                        ? "-"
                        // : posMaster.next_holder.posLevel.posLevelName,
                        : positionMasterProfileOld.positions.find(
                              (x: any) => x.positionIsSelected == true,
                            )?.posLevel?.posLevelName,
                  profilePosExecutive:
                    posMaster.next_holder == null
                      ? positionMasterOld == null
                        ? posExecutive.join(" หรือ ")
                        : profilePosExecutive.join(" หรือ ")
                      : positionMasterProfileOld == null
                        ? "-"
                        : positionMasterProfileOld.positions.find(
                            (x: any) => x.positionIsSelected == true,
                          )?.posExecutive?.posExecutiveName,
                  education: education == "" ? "" : education.degree,
                  salary: salary == "" ? "" : salary.amount,
                  reason: posMaster.reason,
                };
                if (_node == null) {
                  const head = {
                    posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName.toString()),
                    profileFullname: 
                      posMaster.next_holder == null 
                        ? Extension.ToThaiNumber(node.profileOrgName.toString())
                        : Extension.ToThaiNumber(node.orgTreeName.toString()),
                    posExecutive: Extension.ToThaiNumber(node.orgTreeName.toString()),
                    positionName: "",
                    posType: "",
                    posLevel: "",
                    profilePosMasterNo: 
                      posMaster.next_holder == null 
                        ? Extension.ToThaiNumber(node.profileOrgShortName.toString())
                        : Extension.ToThaiNumber(node.orgTreeShortName.toString()),
                    profilePosExecutive: "",
                    profilePositionName: "",
                    profilePosType: "",
                    profilePosLevel: "",
                    education: "",
                    salary: "",
                    reason: "",
                  };
                  data.push(head);
                  const _head = {
                    no: Extension.ToThaiNumber(no.toString()),
                    posMasterNo:
                      node.posMasterNo == null
                        ? ""
                        : Extension.ToThaiNumber(node.posMasterNo.toString()),
                    profileFullname:
                      node.profileFullname == null
                        ? ""
                        : Extension.ToThaiNumber(node.profileFullname.toString()),
                    posExecutive:
                      node.posExecutive == null
                        ? ""
                        : Extension.ToThaiNumber(node.posExecutive.toString()),
                    positionName:
                      node.positionName == null
                        ? ""
                        : Extension.ToThaiNumber(node.positionName.toString()),
                    posType:
                      node.posType == null ? "" : Extension.ToThaiNumber(node.posType.toString()),
                    posLevel:
                      node.posLevel == null ? "" : Extension.ToThaiNumber(node.posLevel.toString()),
                    profilePosMasterNo: Extension.ToThaiNumber(node.profilePosMasterNo.toString()),
                    profilePosExecutive:
                      node.profilePosExecutive == null
                        ? ""
                        : Extension.ToThaiNumber(node.profilePosExecutive.toString()),
                    profilePositionName:
                      node.profilePositionName == null
                        ? ""
                        : Extension.ToThaiNumber(node.profilePositionName.toString()),
                    profilePosType:
                      node.profilePosType == null
                        ? ""
                        : Extension.ToThaiNumber(node.profilePosType.toString()),
                    profilePosLevel:
                      node.profilePosLevel == null
                        ? ""
                        : Extension.ToThaiNumber(node.profilePosLevel.toString()),
                    education:
                      node.education == null
                        ? ""
                        : Extension.ToThaiNumber(node.education.toString()),
                    salary: node.salary ? Extension.ToThaiNumber(node.salary.toLocaleString()) : "",
                    reason:
                      node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
                  };
                  data.push(_head);
                } else {
                  if (
                    node.orgTreeShortName != _node.orgTreeShortName ||
                    node.orgTreeName != _node.orgTreeName ||
                    node.profileOrgShortName != _node.profileOrgShortName ||
                    node.profileOrgName != _node.profileOrgName
                  ) {
                    const head = {
                      posMasterNo:
                        node.orgTreeShortName == _node.orgTreeShortName
                          ? ""
                          : node.orgTreeShortName,
                      profileFullname:
                        node.profileOrgName == _node.profileOrgName ? "" : node.profileOrgName,
                      posExecutive: node.orgTreeName == _node.orgTreeName ? "" : node.orgTreeName,
                      positionName: "",
                      posType: "",
                      posLevel: "",
                      profilePosMasterNo:
                        node.profileOrgShortName == _node.profileOrgShortName
                          ? ""
                          : node.profileOrgShortName,
                      profilePosExecutive: "",
                      profilePositionName: "",
                      profilePosType: "",
                      profilePosLevel: "",
                      education: "",
                      salary: "",
                      reason: "",
                    };
                    data.push(head);
                    _node == null;
                  }
                  const head = {
                    no: Extension.ToThaiNumber(no.toString()),
                    posMasterNo:
                      node.posMasterNo == null
                        ? ""
                        : Extension.ToThaiNumber(node.posMasterNo.toString()),
                    profileFullname:
                      node.profileFullname == null
                        ? ""
                        : Extension.ToThaiNumber(node.profileFullname.toString()),
                    posExecutive:
                      node.posExecutive == null
                        ? ""
                        : Extension.ToThaiNumber(node.posExecutive.toString()),
                    positionName:
                      node.positionName == null
                        ? ""
                        : Extension.ToThaiNumber(node.positionName.toString()),
                    posType:
                      node.posType == null ? "" : Extension.ToThaiNumber(node.posType.toString()),
                    posLevel:
                      node.posLevel == null ? "" : Extension.ToThaiNumber(node.posLevel.toString()),
                    profilePosMasterNo: Extension.ToThaiNumber(node.profilePosMasterNo.toString()),
                    profilePosExecutive:
                      node.profilePosExecutive == null
                        ? ""
                        : Extension.ToThaiNumber(node.profilePosExecutive.toString()),
                    profilePositionName:
                      node.profilePositionName == null
                        ? ""
                        : Extension.ToThaiNumber(node.profilePositionName.toString()),
                    profilePosType:
                      node.profilePosType == null
                        ? ""
                        : Extension.ToThaiNumber(node.profilePosType.toString()),
                    profilePosLevel:
                      node.profilePosLevel == null
                        ? ""
                        : Extension.ToThaiNumber(node.profilePosLevel.toString()),
                    education:
                      node.education == null
                        ? ""
                        : Extension.ToThaiNumber(node.education.toString()),
                    salary: node.salary ? Extension.ToThaiNumber(node.salary.toLocaleString()) : "",
                    reason:
                      node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
                  };
                  data.push(head);
                }
                no += 1;
                _node = node;
              }
            }
            console.log("Processing orgChild4");
            _node = null;

            for (let orgChild4 of orgChild4Data.filter(
              (orgChild4) => orgChild4.orgChild3Id === orgChild3.id,
            )) {
              const posMastersFiltered4 = orgChild4.posMasters.sort(
                (a, b) => a.posMasterOrder - b.posMasterOrder,
              );
              for (let posMaster of posMastersFiltered4) {
                const positionName = [...new Set(posMaster.positions.map((x) => x.positionName))];
                const posType = [
                  ...new Set(
                    posMaster.positions
                      .filter((x: any) => x.posType != null)
                      .map((x) => x.posType.posTypeName),
                  ),
                ];
                const posLevel = [
                  ...new Set(
                    posMaster.positions
                      .filter((x: any) => x.posLevel != null)
                      .map((x) => x.posLevel.posLevelName),
                  ),
                ];
                const posExecutive = [
                  ...new Set(
                    posMaster.positions
                      .filter((x: any) => x.posExecutive != null)
                      .map((x) => x.posExecutive.posExecutiveName),
                  ),
                ];
                let positionMasterProfileOld: any = null;
                if (posMaster.next_holder != null && posMaster.next_holder.current_holders) {
                  positionMasterProfileOld = posMaster.next_holder.current_holders.find(
                    (x) => x.orgRevisionId == orgRevisionActive.id,
                  );
                }

                let positionMasterOld: any = null;
                let profilePositionName: any = [];
                let profilePosType: any = [];
                let profilePosLevel: any = [];
                let profilePosExecutive: any = [];
                if (
                  posMaster.ancestorDNA != null &&
                  posMaster.ancestorDNA != "" &&
                  orgRevisionActive &&
                  orgRevisionActive.posMasters
                ) {
                  positionMasterOld = orgRevisionActive.posMasters.find(
                    (x: any) =>
                      x.orgRevisionId == orgRevisionActive.id &&
                      x.ancestorDNA == posMaster.ancestorDNA,
                  );
                  if (positionMasterOld && positionMasterOld.positions) {
                    profilePositionName = [
                      ...new Set(positionMasterOld.positions.map((x: any) => x.positionName)),
                    ];
                    profilePosType = [
                      ...new Set(
                        positionMasterOld.positions
                          .filter((x: any) => x.posType != null)
                          .map((x: any) => x.posType.posTypeName),
                      ),
                    ];
                    profilePosLevel = [
                      ...new Set(
                        positionMasterOld.positions
                          .filter((x: any) => x.posLevel != null)
                          .map((x: any) => x.posLevel.posLevelName),
                      ),
                    ];
                    profilePosExecutive = [
                      ...new Set(
                        positionMasterOld.positions
                          .filter((x: any) => x.posExecutive != null)
                          .map((x: any) => x.posExecutive.posExecutiveName),
                      ),
                    ];
                  }
                }
                let education: any = "";
                if (
                  posMaster.next_holder != null &&
                  posMaster.next_holder.profileEducations != null &&
                  posMaster.next_holder.profileEducations.length > 0
                ) {
                  let _education: any = posMaster.next_holder.profileEducations.sort(
                    (a, b) =>
                      (b.finishDate == null ? 0 : b.finishDate.getTime()) -
                      (a.finishDate == null ? 0 : a.finishDate.getTime()),
                  );
                  if (_education.length > 0) {
                    education = _education[0];
                  }
                } else {
                  if (
                    posMaster.current_holder != null &&
                    posMaster.current_holder.profileEducations != null &&
                    posMaster.current_holder.profileEducations.length > 0
                  ) {
                    let _education: any = posMaster.current_holder.profileEducations.sort(
                      (a, b) =>
                        (b.finishDate == null ? 0 : b.finishDate.getTime()) -
                        (a.finishDate == null ? 0 : a.finishDate.getTime()),
                    );
                    if (_education.length > 0) {
                      education = _education[0];
                    }
                  }
                }
                let salary: any = "";
                if (
                  posMaster.next_holder != null &&
                  posMaster.next_holder.profileSalary != null &&
                  posMaster.next_holder.profileSalary.length > 0
                ) {
                  let _salary: any = posMaster.next_holder.profileSalary.sort(
                    (a, b) =>
                      (b.commandDateAffect == null ? 0 : b.commandDateAffect.getTime()) -
                      (a.commandDateAffect == null ? 0 : a.commandDateAffect.getTime()),
                  );
                  if (_salary.length > 0) {
                    salary = _salary[0];
                  }
                } else {
                  if (
                    posMaster.current_holder != null &&
                    posMaster.current_holder.profileSalary != null &&
                    posMaster.current_holder.profileSalary.length > 0
                  ) {
                    let _salary: any = posMaster.current_holder.profileSalary.sort(
                      (a, b) =>
                        (b.commandDateAffect == null ? 0 : b.commandDateAffect.getTime()) -
                        (a.commandDateAffect == null ? 0 : a.commandDateAffect.getTime()),
                    );
                    if (_salary.length > 0) {
                      salary = _salary[0];
                    }
                  }
                }
                if (positionMasterProfileOld == null && posMaster.next_holder != null 
                  && posMaster.next_holder.current_holders == null
                ) {
                  positionMasterProfileOld = positionMasterOld
                }
                let node = {
                  posMasterOrder: posMaster.posMasterOrder, //
                  isSit: posMaster.isSit, //
                  orgTreeName: orgChild4.orgChild4Name,
                  orgTreeShortName: orgChild4.orgChild4ShortName,
                  posMasterNo: posMaster.posMasterNo,
                  positionName:
                    posMaster.next_holder == null
                      ? positionName.join(" หรือ ")
                      : posMaster.isSit == false
                        ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                            ?.positionName
                        : posMaster.next_holder.position,
                  posType:
                    posMaster.next_holder == null
                      ? posType.join(" หรือ ")
                      : posMaster.isSit == false
                        ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                            ?.posType?.posTypeName
                        : posMaster.next_holder.posType == null
                          ? "-"
                          : posMaster.next_holder.posType.posTypeName,
                  posLevel:
                    posMaster.next_holder == null
                      ? posLevel.join(" หรือ ")
                      : posMaster.isSit == false
                        ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                            ?.posLevel?.posLevelName
                        : posMaster.next_holder.posLevel == null
                          ? "-"
                          : posMaster.next_holder.posLevel.posLevelName,
                  posExecutive:
                    posMaster.next_holder == null
                      ? posExecutive.join(" หรือ ")
                      : posMaster.isSit == false
                        ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                            ?.posExecutive?.posExecutiveName
                        : positionMasterProfileOld == null
                          ? "-"
                          : positionMasterProfileOld.positions.find(
                              (x: any) => x.positionIsSelected == true,
                            )?.posExecutive?.posExecutiveName,

                  profileOrgName:
                    posMaster.next_holder == null
                      ? orgChild4.orgChild4Name
                      : positionMasterProfileOld == null
                        ? "-"
                        : positionMasterProfileOld.orgChild4 != null
                          ? positionMasterProfileOld.orgChild4.orgChild4Name
                          : positionMasterProfileOld.orgChild3 != null
                            ? positionMasterProfileOld.orgChild3.orgChild3Name
                            : positionMasterProfileOld.orgChild2 != null
                              ? positionMasterProfileOld.orgChild2.orgChild2Name
                              : positionMasterProfileOld.orgChild1 != null
                                ? positionMasterProfileOld.orgChild1.orgChild1Name
                                : positionMasterProfileOld.orgRoot != null
                                  ? positionMasterProfileOld.orgRoot.orgRootName
                                  : "-",
                  profileOrgShortName:
                    posMaster.next_holder == null
                      ? orgChild4.orgChild4ShortName
                      : positionMasterProfileOld == null
                        ? "-"
                        : positionMasterProfileOld.orgChild4 != null
                          ? positionMasterProfileOld.orgChild4.orgChild4ShortName
                          : positionMasterProfileOld.orgChild3 != null
                            ? positionMasterProfileOld.orgChild3.orgChild3ShortName
                            : positionMasterProfileOld.orgChild2 != null
                              ? positionMasterProfileOld.orgChild2.orgChild2ShortName
                              : positionMasterProfileOld.orgChild1 != null
                                ? positionMasterProfileOld.orgChild1.orgChild1ShortName
                                : positionMasterProfileOld.orgRoot != null
                                  ? positionMasterProfileOld.orgRoot.orgRootShortName
                                  : "-",
                  profileFullname:
                    posMaster.next_holder == null
                      ? posMaster.current_holder == null
                        ? "- ว่าง -"
                        : `${posMaster.current_holder.prefix}${posMaster.current_holder.firstName} ${posMaster.current_holder.lastName}`
                      : `${posMaster.next_holder.prefix}${posMaster.next_holder.firstName} ${posMaster.next_holder.lastName}`,
                  profilePosMasterNo:
                    posMaster.next_holder == null
                      ? positionMasterOld == null
                        ? "-"
                        : positionMasterOld.posMasterNo
                      : positionMasterProfileOld == null
                        ? "-"
                        : positionMasterProfileOld.posMasterNo,
                  profilePositionName:
                    posMaster.next_holder == null
                      ? positionMasterOld == null
                        ? positionName.join(" หรือ ")
                        : profilePositionName.join(" หรือ ")
                      : posMaster.next_holder.position,
                  profilePosType:
                    posMaster.next_holder == null
                      ? positionMasterOld == null
                        ? posType.join(" หรือ ")
                        : profilePosType.join(" หรือ ")
                      : positionMasterProfileOld == null
                        ? "-"
                        // : posMaster.next_holder.posType.posTypeName,
                        : positionMasterProfileOld.positions.find(
                              (x: any) => x.positionIsSelected == true,
                            )?.posType?.posTypeName,
                  profilePosLevel:
                    posMaster.next_holder == null
                      ? positionMasterOld == null
                        ? posLevel.join(" หรือ ")
                        : profilePosLevel.join(" หรือ ")
                      : positionMasterProfileOld == null
                        ? "-"
                        // : posMaster.next_holder.posLevel.posLevelName,
                        : positionMasterProfileOld.positions.find(
                              (x: any) => x.positionIsSelected == true,
                            )?.posLevel?.posLevelName,
                  profilePosExecutive:
                    posMaster.next_holder == null
                      ? positionMasterOld == null
                        ? posExecutive.join(" หรือ ")
                        : profilePosExecutive.join(" หรือ ")
                      : positionMasterProfileOld == null
                        ? "-"
                        : positionMasterProfileOld.positions.find(
                            (x: any) => x.positionIsSelected == true,
                          )?.posExecutive?.posExecutiveName,
                  education: education == "" ? "" : education.degree,
                  salary: salary == "" ? "" : salary.amount,
                  reason: posMaster.reason,
                };
                if (_node == null) {
                  const head = {
                    posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName.toString()),
                    profileFullname: 
                      posMaster.next_holder == null 
                        ? Extension.ToThaiNumber(node.profileOrgName.toString())
                        : Extension.ToThaiNumber(node.orgTreeName.toString()),
                    posExecutive: Extension.ToThaiNumber(node.orgTreeName.toString()),
                    positionName: "",
                    posType: "",
                    posLevel: "",
                    profilePosMasterNo: 
                      posMaster.next_holder == null 
                        ? Extension.ToThaiNumber(node.profileOrgShortName.toString())
                        : Extension.ToThaiNumber(node.orgTreeShortName.toString()),
                    profilePosExecutive: "",
                    profilePositionName: "",
                    profilePosType: "",
                    profilePosLevel: "",
                    education: "",
                    salary: "",
                    reason: "",
                  };
                  data.push(head);
                  const _head = {
                    no: Extension.ToThaiNumber(no.toString()),
                    posMasterNo:
                      node.posMasterNo == null
                        ? ""
                        : Extension.ToThaiNumber(node.posMasterNo.toString()),
                    profileFullname:
                      node.profileFullname == null
                        ? ""
                        : Extension.ToThaiNumber(node.profileFullname.toString()),
                    posExecutive:
                      node.posExecutive == null
                        ? ""
                        : Extension.ToThaiNumber(node.posExecutive.toString()),
                    positionName:
                      node.positionName == null
                        ? ""
                        : Extension.ToThaiNumber(node.positionName.toString()),
                    posType:
                      node.posType == null ? "" : Extension.ToThaiNumber(node.posType.toString()),
                    posLevel:
                      node.posLevel == null ? "" : Extension.ToThaiNumber(node.posLevel.toString()),
                    profilePosMasterNo: Extension.ToThaiNumber(node.profilePosMasterNo.toString()),
                    profilePosExecutive:
                      node.profilePosExecutive == null
                        ? ""
                        : Extension.ToThaiNumber(node.profilePosExecutive.toString()),
                    profilePositionName:
                      node.profilePositionName == null
                        ? ""
                        : Extension.ToThaiNumber(node.profilePositionName.toString()),
                    profilePosType:
                      node.profilePosType == null
                        ? ""
                        : Extension.ToThaiNumber(node.profilePosType.toString()),
                    profilePosLevel:
                      node.profilePosLevel == null
                        ? ""
                        : Extension.ToThaiNumber(node.profilePosLevel.toString()),
                    education:
                      node.education == null
                        ? ""
                        : Extension.ToThaiNumber(node.education.toString()),
                    salary: node.salary ? Extension.ToThaiNumber(node.salary.toLocaleString()) : "",
                    reason:
                      node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
                  };
                  data.push(_head);
                } else {
                  if (
                    node.orgTreeShortName != _node.orgTreeShortName ||
                    node.orgTreeName != _node.orgTreeName ||
                    node.profileOrgShortName != _node.profileOrgShortName ||
                    node.profileOrgName != _node.profileOrgName
                  ) {
                    const head = {
                      posMasterNo:
                        node.orgTreeShortName == _node.orgTreeShortName
                          ? ""
                          : node.orgTreeShortName,
                      profileFullname:
                        node.profileOrgName == _node.profileOrgName ? "" : node.profileOrgName,
                      posExecutive: node.orgTreeName == _node.orgTreeName ? "" : node.orgTreeName,
                      positionName: "",
                      posType: "",
                      posLevel: "",
                      profilePosMasterNo:
                        node.profileOrgShortName == _node.profileOrgShortName
                          ? ""
                          : node.profileOrgShortName,
                      profilePosExecutive: "",
                      profilePositionName: "",
                      profilePosType: "",
                      profilePosLevel: "",
                      education: "",
                      salary: "",
                      reason: "",
                    };
                    data.push(head);
                    _node == null;
                  }
                  const head = {
                    no: Extension.ToThaiNumber(no.toString()),
                    posMasterNo:
                      node.posMasterNo == null
                        ? ""
                        : Extension.ToThaiNumber(node.posMasterNo.toString()),
                    profileFullname:
                      node.profileFullname == null
                        ? ""
                        : Extension.ToThaiNumber(node.profileFullname.toString()),
                    posExecutive:
                      node.posExecutive == null
                        ? ""
                        : Extension.ToThaiNumber(node.posExecutive.toString()),
                    positionName:
                      node.positionName == null
                        ? ""
                        : Extension.ToThaiNumber(node.positionName.toString()),
                    posType:
                      node.posType == null ? "" : Extension.ToThaiNumber(node.posType.toString()),
                    posLevel:
                      node.posLevel == null ? "" : Extension.ToThaiNumber(node.posLevel.toString()),
                    profilePosMasterNo: Extension.ToThaiNumber(node.profilePosMasterNo.toString()),
                    profilePosExecutive:
                      node.profilePosExecutive == null
                        ? ""
                        : Extension.ToThaiNumber(node.profilePosExecutive.toString()),
                    profilePositionName:
                      node.profilePositionName == null
                        ? ""
                        : Extension.ToThaiNumber(node.profilePositionName.toString()),
                    profilePosType:
                      node.profilePosType == null
                        ? ""
                        : Extension.ToThaiNumber(node.profilePosType.toString()),
                    profilePosLevel:
                      node.profilePosLevel == null
                        ? ""
                        : Extension.ToThaiNumber(node.profilePosLevel.toString()),
                    education:
                      node.education == null
                        ? ""
                        : Extension.ToThaiNumber(node.education.toString()),
                    salary: node.salary ? Extension.ToThaiNumber(node.salary.toLocaleString()) : "",
                    reason:
                      node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
                  };
                  data.push(head);
                }
                no += 1;
                _node = node;
              }
              _node = null;
            } // End for orgChild4
          } // End for orgChild3
        } // End for orgChild2
      } // End for orgChild1
    } // End for orgRoot

    //   const metaData = { template: "report2", reportName: "report2", data: { data } };
    //   sendWebSocket(metaData);
    // })();

    return new HttpSuccess({
      template: "report2",
      reportName: "report2",
      data: { org: orgName, data },
    });
  }

  /**
   * API Report2
   *
   * @summary Report2
   *
   */
  @Get("report2-history/{rootId}")
  async findReport2History(@Path() rootId: string) {
    const orgRootData = await this.orgRootRepository.find({
      where: {
        id: rootId,
      },
      order: { orgRootOrder: "ASC" },
      relations: [
        "orgRevision",
        "posMasters",
        "posMasters.orgRoot",
        "posMasters.orgChild1",
        "posMasters.orgChild2",
        "posMasters.orgChild3",
        "posMasters.orgChild4",
        "posMasters.current_holder",
        "posMasters.current_holder.posLevel",
        "posMasters.current_holder.posType",
        "posMasters.current_holder.profileSalary",
        "posMasters.current_holder.profileEducations",
        "posMasters.current_holder.current_holders",
        "posMasters.current_holder.current_holders.positions",
        "posMasters.current_holder.current_holders.orgRoot",
        "posMasters.current_holder.current_holders.orgChild1",
        "posMasters.current_holder.current_holders.orgChild2",
        "posMasters.current_holder.current_holders.orgChild3",
        "posMasters.current_holder.current_holders.orgChild4",
        "posMasters.positions",
        "posMasters.positions.posLevel",
        "posMasters.positions.posType",
        "posMasters.positions.posExecutive",
      ],
    });

    const orgRootIds = orgRootData.map((orgRoot) => orgRoot.id) || null;
    const orgChild1Data = await this.child1Repository.find({
      where: {
        orgRootId: In(orgRootIds),
      },
      order: { orgChild1Order: "ASC" },
      relations: [
        "posMasters",
        "posMasters.current_holder",
        "posMasters.current_holder.profileSalary",
        "posMasters.current_holder.profileEducations",
        "posMasters.positions",
      ],
    });

    const orgChild1Ids = orgChild1Data.map((orgChild1) => orgChild1.id) || null;
    const orgChild2Data = await this.child2Repository.find({
      where: {
        orgChild1: In(orgChild1Ids),
      },
      order: { orgChild2Order: "ASC" },
      relations: [
        "posMasters",
        "posMasters.current_holder",
        "posMasters.current_holder.profileSalary",
        "posMasters.current_holder.profileEducations",
        "posMasters.positions",
      ],
    });

    const orgChild2Ids = orgChild2Data.map((orgChild2) => orgChild2.id) || null;
    const orgChild3Data = await this.child3Repository.find({
      where: {
        orgChild2: In(orgChild2Ids),
      },
      order: { orgChild3Order: "ASC" },
      relations: [
        "posMasters",
        "posMasters.current_holder",
        "posMasters.current_holder.profileSalary",
        "posMasters.current_holder.profileEducations",
        "posMasters.positions",
      ],
    });

    const orgChild3Ids = orgChild3Data.map((orgChild3) => orgChild3.id) || null;
    const orgChild4Data = await this.child4Repository.find({
      where: {
        orgChild3: In(orgChild3Ids),
      },
      order: { orgChild4Order: "ASC" },
      relations: [
        "posMasters",
        "posMasters.current_holder",
        "posMasters.current_holder.profileSalary",
        "posMasters.current_holder.profileEducations",
        "posMasters.positions",
      ],
    });

    if (orgRootData.length <= 0) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบโครงสร้าง");
    const _orgRevisionActive = await this.orgRevisionRepository.find({
      where: { createdAt: LessThan(orgRootData[0]?.createdAt ?? new Date()) },
      order: { createdAt: "DESC" },
      skip: 1,
      take: 2,
      relations: [
        "posMasters",
        "posMasters.positions",
        "posMasters.positions.posLevel",
        "posMasters.positions.posType",
        "posMasters.positions.posExecutive",
      ],
    });
    if (_orgRevisionActive.length <= 0) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลประวัติโครงสร้าง");
    }
    let orgRevisionActive = _orgRevisionActive[0];

    let data = new Array();
    let _node: any;
    let no = 1;
    for (let orgRoot of orgRootData) {
      await Promise.all(
        orgRoot.posMasters
          .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
          .map(async (posMaster) => {
            if (posMaster.orgChild1Id == null) {
              const positionName = [...new Set(posMaster.positions.map((x) => x.positionName))];
              const posType = [
                ...new Set(
                  posMaster.positions
                    .filter((x: any) => x.posType != null)
                    .map((x) => x.posType.posTypeName),
                ),
              ];
              const posLevel = [
                ...new Set(
                  posMaster.positions
                    .filter((x: any) => x.posLevel != null)
                    .map((x) => x.posLevel.posLevelName),
                ),
              ];
              const posExecutive = [
                ...new Set(
                  posMaster.positions
                    .filter((x: any) => x.posExecutive != null)
                    .map((x) => x.posExecutive.posExecutiveName),
                ),
              ];
              let positionMasterProfileOld: any = null;
              if (posMaster.current_holder != null) {
                positionMasterProfileOld = posMaster.current_holder.current_holders.find(
                  (x) => x.orgRevisionId == orgRevisionActive.id,
                );
              }

              let positionMasterOld: any = null;
              let profilePositionName: any = [];
              let profilePosType: any = [];
              let profilePosLevel: any = [];
              let profilePosExecutive: any = [];
              if (posMaster.ancestorDNA != null && posMaster.ancestorDNA != "") {
                positionMasterOld = orgRevisionActive.posMasters.find(
                  (x: any) =>
                    x.orgRevisionId == orgRevisionActive.id &&
                    x.ancestorDNA == posMaster.ancestorDNA,
                );
                profilePositionName = [
                  ...new Set(positionMasterOld.positions.map((x: any) => x.positionName)),
                ];
                profilePosType = [
                  ...new Set(
                    positionMasterOld.positions
                      .filter((x: any) => x.posType != null)
                      .map((x: any) => x.posType.posTypeName),
                  ),
                ];
                profilePosLevel = [
                  ...new Set(
                    positionMasterOld.positions
                      .filter((x: any) => x.posLevel != null)
                      .map((x: any) => x.posLevel.posLevelName),
                  ),
                ];
                profilePosExecutive = [
                  ...new Set(
                    positionMasterOld.positions
                      .filter((x: any) => x.posExecutive != null)
                      .map((x: any) => x.posExecutive.posExecutiveName),
                  ),
                ];
              }
              let education: any = "";
              if (
                posMaster.current_holder != null &&
                posMaster.current_holder.profileEducations != null &&
                posMaster.current_holder.profileEducations.length > 0
              ) {
                let _education: any = posMaster.current_holder.profileEducations
                  .filter((x) => x.isEducation == true || x.isUse == true)
                  .sort((a, b) => {
                    // (b.finishDate == null ? 0 : b.finishDate.getTime()) -
                    // (a.finishDate == null ? 0 : a.finishDate.getTime()),
                    if (a.isEducation !== b.isEducation) {
                      return a.isEducation ? -1 : 1;
                    }
                    return b.level - a.level;
                  });
                if (_education.length > 0) {
                  // education = _education[0];
                  education = _education.map((e: any) => e.degree).join(", ");
                }
              }
              let salary: any = "";
              if (
                posMaster.current_holder != null &&
                posMaster.current_holder.profileSalary != null &&
                posMaster.current_holder.profileSalary.length > 0
              ) {
                let _salary: any = posMaster.current_holder.profileSalary.sort(
                  (a, b) =>
                    (b.commandDateAffect == null ? 0 : b.commandDateAffect.getTime()) -
                    (a.commandDateAffect == null ? 0 : a.commandDateAffect.getTime()),
                );
                if (_salary.length > 0) {
                  salary = _salary[0];
                }
              }

              let node = {
                posMasterOrder: posMaster.posMasterOrder, //
                isSit: posMaster.isSit, //
                orgTreeName: orgRoot.orgRootName,
                orgTreeShortName: orgRoot.orgRootShortName,
                posMasterNo: posMaster.posMasterNo,
                positionName:
                  posMaster.current_holder == null
                    ? positionName.join(" หรือ ")
                    : posMaster.isSit == false
                      ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                          ?.positionName
                      : posMaster.current_holder.position,
                posType:
                  posMaster.current_holder == null
                    ? posType.join(" หรือ ")
                    : posMaster.isSit == false
                      ? posMaster.positions.find((x: any) => x.positionIsSelected == true)?.posType
                          ?.posTypeName
                      : posMaster.current_holder.posType == null
                        ? "-"
                        : posMaster.current_holder.posType.posTypeName,
                posLevel:
                  posMaster.current_holder == null
                    ? posLevel.join(" หรือ ")
                    : posMaster.isSit == false
                      ? posMaster.positions.find((x: any) => x.positionIsSelected == true)?.posLevel
                          ?.posLevelName
                      : posMaster.current_holder.posLevel == null
                        ? "-"
                        : posMaster.current_holder.posLevel.posLevelName,
                posExecutive:
                  posMaster.current_holder == null
                    ? posExecutive.join(" หรือ ")
                    : posMaster.isSit == false
                      ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                          ?.posExecutive?.posExecutiveName
                      : positionMasterProfileOld == null
                        ? "-"
                        : positionMasterProfileOld.positions.find(
                            (x: any) => x.positionIsSelected == true,
                          )?.posExecutive?.posExecutiveName,

                profileOrgName:
                  posMaster.current_holder == null
                    ? orgRoot.orgRootName
                    : positionMasterProfileOld == null
                      ? "-"
                      : positionMasterProfileOld.orgChild4 != null
                        ? positionMasterProfileOld.orgChild4.orgChild4Name
                        : positionMasterProfileOld.orgChild3 != null
                          ? positionMasterProfileOld.orgChild3.orgChild3Name
                          : positionMasterProfileOld.orgChild2 != null
                            ? positionMasterProfileOld.orgChild2.orgChild2Name
                            : positionMasterProfileOld.orgChild1 != null
                              ? positionMasterProfileOld.orgChild1.orgChild1Name
                              : positionMasterProfileOld.orgRoot != null
                                ? positionMasterProfileOld.orgRoot.orgRootName
                                : "-",
                profileOrgShortName:
                  posMaster.current_holder == null
                    ? orgRoot.orgRootShortName
                    : positionMasterProfileOld == null
                      ? "-"
                      : positionMasterProfileOld.orgChild4 != null
                        ? positionMasterProfileOld.orgChild4.orgChild4ShortName
                        : positionMasterProfileOld.orgChild3 != null
                          ? positionMasterProfileOld.orgChild3.orgChild3ShortName
                          : positionMasterProfileOld.orgChild2 != null
                            ? positionMasterProfileOld.orgChild2.orgChild2ShortName
                            : positionMasterProfileOld.orgChild1 != null
                              ? positionMasterProfileOld.orgChild1.orgChild1ShortName
                              : positionMasterProfileOld.orgRoot != null
                                ? positionMasterProfileOld.orgRoot.orgRootShortName
                                : "-",
                profileFullname:
                  posMaster.current_holder == null
                    ? "- ว่าง -"
                    : `${posMaster.current_holder.prefix}${posMaster.current_holder.firstName} ${posMaster.current_holder.lastName}`,
                profilePosMasterNo:
                  posMaster.current_holder == null
                    ? positionMasterOld == null
                      ? "-"
                      : positionMasterOld.posMasterNo
                    : positionMasterProfileOld == null
                      ? "-"
                      : positionMasterProfileOld.posMasterNo,
                profilePositionName:
                  posMaster.current_holder == null
                    ? positionMasterOld == null
                      ? positionName.join(" หรือ ")
                      : profilePositionName.join(" หรือ ")
                    : posMaster.current_holder.position,
                profilePosType:
                  posMaster.current_holder == null
                    ? positionMasterOld == null
                      ? posType.join(" หรือ ")
                      : profilePosType.join(" หรือ ")
                    : posMaster.current_holder.posType == null
                      ? "-"
                      : posMaster.current_holder.posType.posTypeName,
                profilePosLevel:
                  posMaster.current_holder == null
                    ? positionMasterOld == null
                      ? posLevel.join(" หรือ ")
                      : profilePosLevel.join(" หรือ ")
                    : posMaster.current_holder.posLevel == null
                      ? "-"
                      : posMaster.current_holder.posLevel.posLevelName,
                profilePosExecutive:
                  posMaster.current_holder == null
                    ? positionMasterOld == null
                      ? posExecutive.join(" หรือ ")
                      : profilePosExecutive.join(" หรือ ")
                    : positionMasterProfileOld == null
                      ? "-"
                      : positionMasterProfileOld.positions.find(
                          (x: any) => x.positionIsSelected == true,
                        )?.posExecutive?.posExecutiveName,
                education: education == "" ? "" : education,
                salary: salary == "" ? "" : salary.amount,
                reason: posMaster.reason,
              };
              if (_node == null) {
                const head = {
                  posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName.toString()),
                  profileFullname: Extension.ToThaiNumber(node.profileOrgName.toString()),
                  posExecutive: Extension.ToThaiNumber(node.orgTreeName.toString()),
                  positionName: "",
                  posType: "",
                  posLevel: "",
                  profilePosMasterNo: Extension.ToThaiNumber(node.profileOrgShortName.toString()),
                  profilePosExecutive: "",
                  profilePositionName: "",
                  profilePosType: "",
                  profilePosLevel: "",
                  education: "",
                  salary: "",
                  reason: "",
                };
                data.push(head);
                const _head = {
                  no: Extension.ToThaiNumber(no.toString()),
                  posMasterNo:
                    node.posMasterNo == null
                      ? ""
                      : Extension.ToThaiNumber(node.posMasterNo.toString()),
                  profileFullname:
                    node.profileFullname == null
                      ? ""
                      : Extension.ToThaiNumber(node.profileFullname.toString()),
                  posExecutive:
                    node.posExecutive == null
                      ? ""
                      : Extension.ToThaiNumber(node.posExecutive.toString()),
                  positionName:
                    node.positionName == null
                      ? ""
                      : Extension.ToThaiNumber(node.positionName.toString()),
                  posType:
                    node.posType == null ? "" : Extension.ToThaiNumber(node.posType.toString()),
                  posLevel:
                    node.posLevel == null ? "" : Extension.ToThaiNumber(node.posLevel.toString()),
                  profilePosMasterNo: Extension.ToThaiNumber(node.profilePosMasterNo.toString()),
                  profilePosExecutive:
                    node.profilePosExecutive == null
                      ? ""
                      : Extension.ToThaiNumber(node.profilePosExecutive.toString()),
                  profilePositionName:
                    node.profilePositionName == null
                      ? ""
                      : Extension.ToThaiNumber(node.profilePositionName.toString()),
                  profilePosType:
                    node.profilePosType == null
                      ? ""
                      : Extension.ToThaiNumber(node.profilePosType.toString()),
                  profilePosLevel:
                    node.profilePosLevel == null
                      ? ""
                      : Extension.ToThaiNumber(node.profilePosLevel.toString()),
                  education:
                    node.education == null ? "" : Extension.ToThaiNumber(node.education.toString()),
                  salary: node.salary ? Extension.ToThaiNumber(node.salary.toLocaleString()) : "",
                  reason: node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
                };
                data.push(_head);
              } else {
                if (
                  node.orgTreeShortName != _node.orgTreeShortName ||
                  node.orgTreeName != _node.orgTreeName ||
                  node.profileOrgShortName != _node.profileOrgShortName ||
                  node.profileOrgName != _node.profileOrgName
                ) {
                  const head = {
                    posMasterNo:
                      node.orgTreeShortName == _node.orgTreeShortName ? "" : node.orgTreeShortName,
                    profileFullname:
                      node.profileOrgName == _node.profileOrgName ? "" : node.profileOrgName,
                    posExecutive: node.orgTreeName == _node.orgTreeName ? "" : node.orgTreeName,
                    positionName: "",
                    posType: "",
                    posLevel: "",
                    profilePosMasterNo:
                      node.profileOrgShortName == _node.profileOrgShortName
                        ? ""
                        : node.profileOrgShortName,
                    profilePosExecutive: "",
                    profilePositionName: "",
                    profilePosType: "",
                    profilePosLevel: "",
                    education: "",
                    salary: "",
                    reason: "",
                  };
                  data.push(head);
                  _node == null;
                }
                const head = {
                  no: Extension.ToThaiNumber(no.toString()),
                  posMasterNo:
                    node.posMasterNo == null
                      ? ""
                      : Extension.ToThaiNumber(node.posMasterNo.toString()),
                  profileFullname:
                    node.profileFullname == null
                      ? ""
                      : Extension.ToThaiNumber(node.profileFullname.toString()),
                  posExecutive:
                    node.posExecutive == null
                      ? ""
                      : Extension.ToThaiNumber(node.posExecutive.toString()),
                  positionName:
                    node.positionName == null
                      ? ""
                      : Extension.ToThaiNumber(node.positionName.toString()),
                  posType:
                    node.posType == null ? "" : Extension.ToThaiNumber(node.posType.toString()),
                  posLevel:
                    node.posLevel == null ? "" : Extension.ToThaiNumber(node.posLevel.toString()),
                  profilePosMasterNo: Extension.ToThaiNumber(node.profilePosMasterNo.toString()),
                  profilePosExecutive:
                    node.profilePosExecutive == null
                      ? ""
                      : Extension.ToThaiNumber(node.profilePosExecutive.toString()),
                  profilePositionName:
                    node.profilePositionName == null
                      ? ""
                      : Extension.ToThaiNumber(node.profilePositionName.toString()),
                  profilePosType:
                    node.profilePosType == null
                      ? ""
                      : Extension.ToThaiNumber(node.profilePosType.toString()),
                  profilePosLevel:
                    node.profilePosLevel == null
                      ? ""
                      : Extension.ToThaiNumber(node.profilePosLevel.toString()),
                  education:
                    node.education == null ? "" : Extension.ToThaiNumber(node.education.toString()),
                  salary: node.salary ? Extension.ToThaiNumber(node.salary.toLocaleString()) : "",
                  reason: node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
                };
                data.push(head);
              }
              no += 1;
              _node = node;
            }
          }),
      );
      _node = null;

      for (let orgChild1 of orgChild1Data.filter(
        (orgChild1) => orgChild1.orgRootId === orgRoot.id,
      )) {
        await Promise.all(
          orgChild1.posMasters
            .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
            .map(async (posMaster) => {
              if (posMaster.orgChild2Id == null) {
                const positionName = [...new Set(posMaster.positions.map((x) => x.positionName))];
                const posType = [
                  ...new Set(
                    posMaster.positions
                      .filter((x: any) => x.posType != null)
                      .map((x) => x.posType.posTypeName),
                  ),
                ];
                const posLevel = [
                  ...new Set(
                    posMaster.positions
                      .filter((x: any) => x.posLevel != null)
                      .map((x) => x.posLevel.posLevelName),
                  ),
                ];
                const posExecutive = [
                  ...new Set(
                    posMaster.positions
                      .filter((x: any) => x.posExecutive != null)
                      .map((x) => x.posExecutive.posExecutiveName),
                  ),
                ];
                let positionMasterProfileOld: any = null;
                if (posMaster.current_holder != null) {
                  positionMasterProfileOld = posMaster.current_holder.current_holders.find(
                    (x) => x.orgRevisionId == orgRevisionActive.id,
                  );
                }

                let positionMasterOld: any = null;
                let profilePositionName: any = [];
                let profilePosType: any = [];
                let profilePosLevel: any = [];
                let profilePosExecutive: any = [];
                if (posMaster.ancestorDNA != null && posMaster.ancestorDNA != "") {
                  positionMasterOld = orgRevisionActive.posMasters.find(
                    (x: any) =>
                      x.orgRevisionId == orgRevisionActive.id &&
                      x.ancestorDNA == posMaster.ancestorDNA,
                  );
                  profilePositionName = [
                    ...new Set(positionMasterOld.positions.map((x: any) => x.positionName)),
                  ];
                  profilePosType = [
                    ...new Set(
                      positionMasterOld.positions
                        .filter((x: any) => x.posType != null)
                        .map((x: any) => x.posType.posTypeName),
                    ),
                  ];
                  profilePosLevel = [
                    ...new Set(
                      positionMasterOld.positions
                        .filter((x: any) => x.posLevel != null)
                        .map((x: any) => x.posLevel.posLevelName),
                    ),
                  ];
                  profilePosExecutive = [
                    ...new Set(
                      positionMasterOld.positions
                        .filter((x: any) => x.posExecutive != null)
                        .map((x: any) => x.posExecutive.posExecutiveName),
                    ),
                  ];
                }
                let education: any = "";
                if (
                  posMaster.current_holder != null &&
                  posMaster.current_holder.profileEducations != null &&
                  posMaster.current_holder.profileEducations.length > 0
                ) {
                  let _education: any = posMaster.current_holder.profileEducations
                    .filter((x) => x.isEducation == true || x.isUse == true)
                    .sort((a, b) => {
                      if (a.isEducation !== b.isEducation) {
                        return a.isEducation ? -1 : 1;
                      }
                      return b.level - a.level;
                    });
                  if (_education.length > 0) {
                    education = _education.map((e: any) => e.degree).join(", ");
                  }
                }
                let salary: any = "";
                if (
                  posMaster.current_holder != null &&
                  posMaster.current_holder.profileSalary != null &&
                  posMaster.current_holder.profileSalary.length > 0
                ) {
                  let _salary: any = posMaster.current_holder.profileSalary.sort(
                    (a, b) =>
                      (b.commandDateAffect == null ? 0 : b.commandDateAffect.getTime()) -
                      (a.commandDateAffect == null ? 0 : a.commandDateAffect.getTime()),
                  );
                  if (_salary.length > 0) {
                    salary = _salary[0];
                  }
                }

                let node = {
                  posMasterOrder: posMaster.posMasterOrder, //
                  isSit: posMaster.isSit, //
                  orgTreeName: orgChild1.orgChild1Name,
                  orgTreeShortName: orgChild1.orgChild1ShortName,
                  posMasterNo: posMaster.posMasterNo,
                  positionName:
                    posMaster.current_holder == null
                      ? positionName.join(" หรือ ")
                      : posMaster.isSit == false
                        ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                            ?.positionName
                        : posMaster.current_holder.position,
                  posType:
                    posMaster.current_holder == null
                      ? posType.join(" หรือ ")
                      : posMaster.isSit == false
                        ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                            ?.posType?.posTypeName
                        : posMaster.current_holder.posType == null
                          ? "-"
                          : posMaster.current_holder.posType.posTypeName,
                  posLevel:
                    posMaster.current_holder == null
                      ? posLevel.join(" หรือ ")
                      : posMaster.isSit == false
                        ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                            ?.posLevel?.posLevelName
                        : posMaster.current_holder.posLevel == null
                          ? "-"
                          : posMaster.current_holder.posLevel.posLevelName,
                  posExecutive:
                    posMaster.current_holder == null
                      ? posExecutive.join(" หรือ ")
                      : posMaster.isSit == false
                        ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                            ?.posExecutive?.posExecutiveName
                        : positionMasterProfileOld == null
                          ? "-"
                          : positionMasterProfileOld.positions.find(
                              (x: any) => x.positionIsSelected == true,
                            )?.posExecutive?.posExecutiveName,

                  profileOrgName:
                    posMaster.current_holder == null
                      ? orgChild1.orgChild1Name
                      : positionMasterProfileOld == null
                        ? "-"
                        : positionMasterProfileOld.orgChild4 != null
                          ? positionMasterProfileOld.orgChild4.orgChild4Name
                          : positionMasterProfileOld.orgChild3 != null
                            ? positionMasterProfileOld.orgChild3.orgChild3Name
                            : positionMasterProfileOld.orgChild2 != null
                              ? positionMasterProfileOld.orgChild2.orgChild2Name
                              : positionMasterProfileOld.orgChild1 != null
                                ? positionMasterProfileOld.orgChild1.orgChild1Name
                                : positionMasterProfileOld.orgRoot != null
                                  ? positionMasterProfileOld.orgRoot.orgRootName
                                  : "-",
                  profileOrgShortName:
                    posMaster.current_holder == null
                      ? orgChild1.orgChild1ShortName
                      : positionMasterProfileOld == null
                        ? "-"
                        : positionMasterProfileOld.orgChild4 != null
                          ? positionMasterProfileOld.orgChild4.orgChild4ShortName
                          : positionMasterProfileOld.orgChild3 != null
                            ? positionMasterProfileOld.orgChild3.orgChild3ShortName
                            : positionMasterProfileOld.orgChild2 != null
                              ? positionMasterProfileOld.orgChild2.orgChild2ShortName
                              : positionMasterProfileOld.orgChild1 != null
                                ? positionMasterProfileOld.orgChild1.orgChild1ShortName
                                : positionMasterProfileOld.orgRoot != null
                                  ? positionMasterProfileOld.orgRoot.orgRootShortName
                                  : "-",
                  profileFullname:
                    posMaster.current_holder == null
                      ? "- ว่าง -"
                      : `${posMaster.current_holder.prefix}${posMaster.current_holder.firstName} ${posMaster.current_holder.lastName}`,
                  profilePosMasterNo:
                    posMaster.current_holder == null
                      ? positionMasterOld == null
                        ? "-"
                        : positionMasterOld.posMasterNo
                      : positionMasterProfileOld == null
                        ? "-"
                        : positionMasterProfileOld.posMasterNo,
                  profilePositionName:
                    posMaster.current_holder == null
                      ? positionMasterOld == null
                        ? positionName.join(" หรือ ")
                        : profilePositionName.join(" หรือ ")
                      : posMaster.current_holder.position,
                  profilePosType:
                    posMaster.current_holder == null
                      ? positionMasterOld == null
                        ? posType.join(" หรือ ")
                        : profilePosType.join(" หรือ ")
                      : posMaster.current_holder.posType == null
                        ? "-"
                        : posMaster.current_holder.posType.posTypeName,
                  profilePosLevel:
                    posMaster.current_holder == null
                      ? positionMasterOld == null
                        ? posLevel.join(" หรือ ")
                        : profilePosLevel.join(" หรือ ")
                      : posMaster.current_holder.posLevel == null
                        ? "-"
                        : posMaster.current_holder.posLevel.posLevelName,
                  profilePosExecutive:
                    posMaster.current_holder == null
                      ? positionMasterOld == null
                        ? posExecutive.join(" หรือ ")
                        : profilePosExecutive.join(" หรือ ")
                      : positionMasterProfileOld == null
                        ? "-"
                        : positionMasterProfileOld.positions.find(
                            (x: any) => x.positionIsSelected == true,
                          )?.posExecutive?.posExecutiveName,
                  education: education == "" ? "" : education,
                  salary: salary == "" ? "" : salary.amount,
                  reason: posMaster.reason,
                };
                if (_node == null) {
                  const head = {
                    posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName.toString()),
                    profileFullname: Extension.ToThaiNumber(node.profileOrgName.toString()),
                    posExecutive: Extension.ToThaiNumber(node.orgTreeName.toString()),
                    positionName: "",
                    posType: "",
                    posLevel: "",
                    profilePosMasterNo: Extension.ToThaiNumber(node.profileOrgShortName.toString()),
                    profilePosExecutive: "",
                    profilePositionName: "",
                    profilePosType: "",
                    profilePosLevel: "",
                    education: "",
                    salary: "",
                    reason: "",
                  };
                  data.push(head);
                  const _head = {
                    no: Extension.ToThaiNumber(no.toString()),
                    posMasterNo:
                      node.posMasterNo == null
                        ? ""
                        : Extension.ToThaiNumber(node.posMasterNo.toString()),
                    profileFullname:
                      node.profileFullname == null
                        ? ""
                        : Extension.ToThaiNumber(node.profileFullname.toString()),
                    posExecutive:
                      node.posExecutive == null
                        ? ""
                        : Extension.ToThaiNumber(node.posExecutive.toString()),
                    positionName:
                      node.positionName == null
                        ? ""
                        : Extension.ToThaiNumber(node.positionName.toString()),
                    posType:
                      node.posType == null ? "" : Extension.ToThaiNumber(node.posType.toString()),
                    posLevel:
                      node.posLevel == null ? "" : Extension.ToThaiNumber(node.posLevel.toString()),
                    profilePosMasterNo: Extension.ToThaiNumber(node.profilePosMasterNo.toString()),
                    profilePosExecutive:
                      node.profilePosExecutive == null
                        ? ""
                        : Extension.ToThaiNumber(node.profilePosExecutive.toString()),
                    profilePositionName:
                      node.profilePositionName == null
                        ? ""
                        : Extension.ToThaiNumber(node.profilePositionName.toString()),
                    profilePosType:
                      node.profilePosType == null
                        ? ""
                        : Extension.ToThaiNumber(node.profilePosType.toString()),
                    profilePosLevel:
                      node.profilePosLevel == null
                        ? ""
                        : Extension.ToThaiNumber(node.profilePosLevel.toString()),
                    education:
                      node.education == null
                        ? ""
                        : Extension.ToThaiNumber(node.education.toString()),
                    salary: node.salary ? Extension.ToThaiNumber(node.salary.toLocaleString()) : "",
                    reason:
                      node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
                  };
                  data.push(_head);
                } else {
                  if (
                    node.orgTreeShortName != _node.orgTreeShortName ||
                    node.orgTreeName != _node.orgTreeName ||
                    node.profileOrgShortName != _node.profileOrgShortName ||
                    node.profileOrgName != _node.profileOrgName
                  ) {
                    const head = {
                      posMasterNo:
                        node.orgTreeShortName == _node.orgTreeShortName
                          ? ""
                          : node.orgTreeShortName,
                      profileFullname:
                        node.profileOrgName == _node.profileOrgName ? "" : node.profileOrgName,
                      posExecutive: node.orgTreeName == _node.orgTreeName ? "" : node.orgTreeName,
                      positionName: "",
                      posType: "",
                      posLevel: "",
                      profilePosMasterNo:
                        node.profileOrgShortName == _node.profileOrgShortName
                          ? ""
                          : node.profileOrgShortName,
                      profilePosExecutive: "",
                      profilePositionName: "",
                      profilePosType: "",
                      profilePosLevel: "",
                      education: "",
                      salary: "",
                      reason: "",
                    };
                    data.push(head);
                    _node == null;
                  }
                  const head = {
                    no: Extension.ToThaiNumber(no.toString()),
                    posMasterNo:
                      node.posMasterNo == null
                        ? ""
                        : Extension.ToThaiNumber(node.posMasterNo.toString()),
                    profileFullname:
                      node.profileFullname == null
                        ? ""
                        : Extension.ToThaiNumber(node.profileFullname.toString()),
                    posExecutive:
                      node.posExecutive == null
                        ? ""
                        : Extension.ToThaiNumber(node.posExecutive.toString()),
                    positionName:
                      node.positionName == null
                        ? ""
                        : Extension.ToThaiNumber(node.positionName.toString()),
                    posType:
                      node.posType == null ? "" : Extension.ToThaiNumber(node.posType.toString()),
                    posLevel:
                      node.posLevel == null ? "" : Extension.ToThaiNumber(node.posLevel.toString()),
                    profilePosMasterNo: Extension.ToThaiNumber(node.profilePosMasterNo.toString()),
                    profilePosExecutive:
                      node.profilePosExecutive == null
                        ? ""
                        : Extension.ToThaiNumber(node.profilePosExecutive.toString()),
                    profilePositionName:
                      node.profilePositionName == null
                        ? ""
                        : Extension.ToThaiNumber(node.profilePositionName.toString()),
                    profilePosType:
                      node.profilePosType == null
                        ? ""
                        : Extension.ToThaiNumber(node.profilePosType.toString()),
                    profilePosLevel:
                      node.profilePosLevel == null
                        ? ""
                        : Extension.ToThaiNumber(node.profilePosLevel.toString()),
                    education:
                      node.education == null
                        ? ""
                        : Extension.ToThaiNumber(node.education.toString()),
                    salary: node.salary ? Extension.ToThaiNumber(node.salary.toLocaleString()) : "",
                    reason:
                      node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
                  };
                  data.push(head);
                }
                no += 1;
                _node = node;
              }
            }),
        );
        _node = null;

        for (let orgChild2 of orgChild2Data.filter(
          (orgChild2) => orgChild2.orgChild1Id === orgChild1.id,
        )) {
          await Promise.all(
            orgChild2.posMasters
              .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
              .map(async (posMaster) => {
                if (posMaster.orgChild3Id == null) {
                  const positionName = [...new Set(posMaster.positions.map((x) => x.positionName))];
                  const posType = [
                    ...new Set(
                      posMaster.positions
                        .filter((x: any) => x.posType != null)
                        .map((x) => x.posType.posTypeName),
                    ),
                  ];
                  const posLevel = [
                    ...new Set(
                      posMaster.positions
                        .filter((x: any) => x.posLevel != null)
                        .map((x) => x.posLevel.posLevelName),
                    ),
                  ];
                  const posExecutive = [
                    ...new Set(
                      posMaster.positions
                        .filter((x: any) => x.posExecutive != null)
                        .map((x) => x.posExecutive.posExecutiveName),
                    ),
                  ];
                  let positionMasterProfileOld: any = null;
                  if (posMaster.current_holder != null) {
                    positionMasterProfileOld = posMaster.current_holder.current_holders.find(
                      (x) => x.orgRevisionId == orgRevisionActive.id,
                    );
                  }

                  let positionMasterOld: any = null;
                  let profilePositionName: any = [];
                  let profilePosType: any = [];
                  let profilePosLevel: any = [];
                  let profilePosExecutive: any = [];
                  if (posMaster.ancestorDNA != null && posMaster.ancestorDNA != "") {
                    positionMasterOld = orgRevisionActive.posMasters.find(
                      (x: any) =>
                        x.orgRevisionId == orgRevisionActive.id &&
                        x.ancestorDNA == posMaster.ancestorDNA,
                    );
                    profilePositionName = [
                      ...new Set(positionMasterOld.positions.map((x: any) => x.positionName)),
                    ];
                    profilePosType = [
                      ...new Set(
                        positionMasterOld.positions
                          .filter((x: any) => x.posType != null)
                          .map((x: any) => x.posType.posTypeName),
                      ),
                    ];
                    profilePosLevel = [
                      ...new Set(
                        positionMasterOld.positions
                          .filter((x: any) => x.posLevel != null)
                          .map((x: any) => x.posLevel.posLevelName),
                      ),
                    ];
                    profilePosExecutive = [
                      ...new Set(
                        positionMasterOld.positions
                          .filter((x: any) => x.posExecutive != null)
                          .map((x: any) => x.posExecutive.posExecutiveName),
                      ),
                    ];
                  }
                  let education: any = "";
                  if (
                    posMaster.current_holder != null &&
                    posMaster.current_holder.profileEducations != null &&
                    posMaster.current_holder.profileEducations.length > 0
                  ) {
                    let _education: any = posMaster.current_holder.profileEducations
                      .filter((x) => x.isEducation == true || x.isUse == true)
                      .sort((a, b) => {
                        if (a.isEducation !== b.isEducation) {
                          return a.isEducation ? -1 : 1;
                        }
                        return b.level - a.level;
                      });
                    if (_education.length > 0) {
                      education = _education.map((e: any) => e.degree).join(", ");
                    }
                  }
                  let salary: any = "";
                  if (
                    posMaster.current_holder != null &&
                    posMaster.current_holder.profileSalary != null &&
                    posMaster.current_holder.profileSalary.length > 0
                  ) {
                    let _salary: any = posMaster.current_holder.profileSalary.sort(
                      (a, b) =>
                        (b.commandDateAffect == null ? 0 : b.commandDateAffect.getTime()) -
                        (a.commandDateAffect == null ? 0 : a.commandDateAffect.getTime()),
                    );
                    if (_salary.length > 0) {
                      salary = _salary[0];
                    }
                  }

                  let node = {
                    posMasterOrder: posMaster.posMasterOrder, //
                    isSit: posMaster.isSit, //
                    orgTreeName: orgChild2.orgChild2Name,
                    orgTreeShortName: orgChild2.orgChild2ShortName,
                    posMasterNo: posMaster.posMasterNo,
                    positionName:
                      posMaster.current_holder == null
                        ? positionName.join(" หรือ ")
                        : posMaster.isSit == false
                          ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                              ?.positionName
                          : posMaster.current_holder.position,
                    posType:
                      posMaster.current_holder == null
                        ? posType.join(" หรือ ")
                        : posMaster.isSit == false
                          ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                              ?.posType?.posTypeName
                          : posMaster.current_holder.posType == null
                            ? "-"
                            : posMaster.current_holder.posType.posTypeName,
                    posLevel:
                      posMaster.current_holder == null
                        ? posLevel.join(" หรือ ")
                        : posMaster.isSit == false
                          ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                              ?.posLevel?.posLevelName
                          : posMaster.current_holder.posLevel == null
                            ? "-"
                            : posMaster.current_holder.posLevel.posLevelName,
                    posExecutive:
                      posMaster.current_holder == null
                        ? posExecutive.join(" หรือ ")
                        : posMaster.isSit == false
                          ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                              ?.posExecutive?.posExecutiveName
                          : positionMasterProfileOld == null
                            ? "-"
                            : positionMasterProfileOld.positions.find(
                                (x: any) => x.positionIsSelected == true,
                              )?.posExecutive?.posExecutiveName,

                    profileOrgName:
                      posMaster.current_holder == null
                        ? orgChild2.orgChild2Name
                        : positionMasterProfileOld == null
                          ? "-"
                          : positionMasterProfileOld.orgChild4 != null
                            ? positionMasterProfileOld.orgChild4.orgChild4Name
                            : positionMasterProfileOld.orgChild3 != null
                              ? positionMasterProfileOld.orgChild3.orgChild3Name
                              : positionMasterProfileOld.orgChild2 != null
                                ? positionMasterProfileOld.orgChild2.orgChild2Name
                                : positionMasterProfileOld.orgChild1 != null
                                  ? positionMasterProfileOld.orgChild1.orgChild1Name
                                  : positionMasterProfileOld.orgRoot != null
                                    ? positionMasterProfileOld.orgRoot.orgRootName
                                    : "-",
                    profileOrgShortName:
                      posMaster.current_holder == null
                        ? orgChild2.orgChild2ShortName
                        : positionMasterProfileOld == null
                          ? "-"
                          : positionMasterProfileOld.orgChild4 != null
                            ? positionMasterProfileOld.orgChild4.orgChild4ShortName
                            : positionMasterProfileOld.orgChild3 != null
                              ? positionMasterProfileOld.orgChild3.orgChild3ShortName
                              : positionMasterProfileOld.orgChild2 != null
                                ? positionMasterProfileOld.orgChild2.orgChild2ShortName
                                : positionMasterProfileOld.orgChild1 != null
                                  ? positionMasterProfileOld.orgChild1.orgChild1ShortName
                                  : positionMasterProfileOld.orgRoot != null
                                    ? positionMasterProfileOld.orgRoot.orgRootShortName
                                    : "-",
                    profileFullname:
                      posMaster.current_holder == null
                        ? "- ว่าง -"
                        : `${posMaster.current_holder.prefix}${posMaster.current_holder.firstName} ${posMaster.current_holder.lastName}`,
                    profilePosMasterNo:
                      posMaster.current_holder == null
                        ? positionMasterOld == null
                          ? "-"
                          : positionMasterOld.posMasterNo
                        : positionMasterProfileOld == null
                          ? "-"
                          : positionMasterProfileOld.posMasterNo,
                    profilePositionName:
                      posMaster.current_holder == null
                        ? positionMasterOld == null
                          ? positionName.join(" หรือ ")
                          : profilePositionName.join(" หรือ ")
                        : posMaster.current_holder.position,
                    profilePosType:
                      posMaster.current_holder == null
                        ? positionMasterOld == null
                          ? posType.join(" หรือ ")
                          : profilePosType.join(" หรือ ")
                        : posMaster.current_holder.posType == null
                          ? "-"
                          : posMaster.current_holder.posType.posTypeName,
                    profilePosLevel:
                      posMaster.current_holder == null
                        ? positionMasterOld == null
                          ? posLevel.join(" หรือ ")
                          : profilePosLevel.join(" หรือ ")
                        : posMaster.current_holder.posLevel == null
                          ? "-"
                          : posMaster.current_holder.posLevel.posLevelName,
                    profilePosExecutive:
                      posMaster.current_holder == null
                        ? positionMasterOld == null
                          ? posExecutive.join(" หรือ ")
                          : profilePosExecutive.join(" หรือ ")
                        : positionMasterProfileOld == null
                          ? "-"
                          : positionMasterProfileOld.positions.find(
                              (x: any) => x.positionIsSelected == true,
                            )?.posExecutive?.posExecutiveName,
                    education: education == "" ? "" : education,
                    salary: salary == "" ? "" : salary.amount,
                    reason: posMaster.reason,
                  };
                  if (_node == null) {
                    const head = {
                      posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName.toString()),
                      profileFullname: Extension.ToThaiNumber(node.profileOrgName.toString()),
                      posExecutive: Extension.ToThaiNumber(node.orgTreeName.toString()),
                      positionName: "",
                      posType: "",
                      posLevel: "",
                      profilePosMasterNo: Extension.ToThaiNumber(
                        node.profileOrgShortName.toString(),
                      ),
                      profilePosExecutive: "",
                      profilePositionName: "",
                      profilePosType: "",
                      profilePosLevel: "",
                      education: "",
                      salary: "",
                      reason: "",
                    };
                    data.push(head);
                    const _head = {
                      no: Extension.ToThaiNumber(no.toString()),
                      posMasterNo:
                        node.posMasterNo == null
                          ? ""
                          : Extension.ToThaiNumber(node.posMasterNo.toString()),
                      profileFullname:
                        node.profileFullname == null
                          ? ""
                          : Extension.ToThaiNumber(node.profileFullname.toString()),
                      posExecutive:
                        node.posExecutive == null
                          ? ""
                          : Extension.ToThaiNumber(node.posExecutive.toString()),
                      positionName:
                        node.positionName == null
                          ? ""
                          : Extension.ToThaiNumber(node.positionName.toString()),
                      posType:
                        node.posType == null ? "" : Extension.ToThaiNumber(node.posType.toString()),
                      posLevel:
                        node.posLevel == null
                          ? ""
                          : Extension.ToThaiNumber(node.posLevel.toString()),
                      profilePosMasterNo: Extension.ToThaiNumber(
                        node.profilePosMasterNo.toString(),
                      ),
                      profilePosExecutive:
                        node.profilePosExecutive == null
                          ? ""
                          : Extension.ToThaiNumber(node.profilePosExecutive.toString()),
                      profilePositionName:
                        node.profilePositionName == null
                          ? ""
                          : Extension.ToThaiNumber(node.profilePositionName.toString()),
                      profilePosType:
                        node.profilePosType == null
                          ? ""
                          : Extension.ToThaiNumber(node.profilePosType.toString()),
                      profilePosLevel:
                        node.profilePosLevel == null
                          ? ""
                          : Extension.ToThaiNumber(node.profilePosLevel.toString()),
                      education:
                        node.education == null
                          ? ""
                          : Extension.ToThaiNumber(node.education.toString()),
                      salary: node.salary
                        ? Extension.ToThaiNumber(node.salary.toLocaleString())
                        : "",
                      reason:
                        node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
                    };
                    data.push(_head);
                  } else {
                    if (
                      node.orgTreeShortName != _node.orgTreeShortName ||
                      node.orgTreeName != _node.orgTreeName ||
                      node.profileOrgShortName != _node.profileOrgShortName ||
                      node.profileOrgName != _node.profileOrgName
                    ) {
                      const head = {
                        posMasterNo:
                          node.orgTreeShortName == _node.orgTreeShortName
                            ? ""
                            : node.orgTreeShortName,
                        profileFullname:
                          node.profileOrgName == _node.profileOrgName ? "" : node.profileOrgName,
                        posExecutive: node.orgTreeName == _node.orgTreeName ? "" : node.orgTreeName,
                        positionName: "",
                        posType: "",
                        posLevel: "",
                        profilePosMasterNo:
                          node.profileOrgShortName == _node.profileOrgShortName
                            ? ""
                            : node.profileOrgShortName,
                        profilePosExecutive: "",
                        profilePositionName: "",
                        profilePosType: "",
                        profilePosLevel: "",
                        education: "",
                        salary: "",
                        reason: "",
                      };
                      data.push(head);
                      _node == null;
                    }
                    const head = {
                      no: Extension.ToThaiNumber(no.toString()),
                      posMasterNo:
                        node.posMasterNo == null
                          ? ""
                          : Extension.ToThaiNumber(node.posMasterNo.toString()),
                      profileFullname:
                        node.profileFullname == null
                          ? ""
                          : Extension.ToThaiNumber(node.profileFullname.toString()),
                      posExecutive:
                        node.posExecutive == null
                          ? ""
                          : Extension.ToThaiNumber(node.posExecutive.toString()),
                      positionName:
                        node.positionName == null
                          ? ""
                          : Extension.ToThaiNumber(node.positionName.toString()),
                      posType:
                        node.posType == null ? "" : Extension.ToThaiNumber(node.posType.toString()),
                      posLevel:
                        node.posLevel == null
                          ? ""
                          : Extension.ToThaiNumber(node.posLevel.toString()),
                      profilePosMasterNo: Extension.ToThaiNumber(
                        node.profilePosMasterNo.toString(),
                      ),
                      profilePosExecutive:
                        node.profilePosExecutive == null
                          ? ""
                          : Extension.ToThaiNumber(node.profilePosExecutive.toString()),
                      profilePositionName:
                        node.profilePositionName == null
                          ? ""
                          : Extension.ToThaiNumber(node.profilePositionName.toString()),
                      profilePosType:
                        node.profilePosType == null
                          ? ""
                          : Extension.ToThaiNumber(node.profilePosType.toString()),
                      profilePosLevel:
                        node.profilePosLevel == null
                          ? ""
                          : Extension.ToThaiNumber(node.profilePosLevel.toString()),
                      education:
                        node.education == null
                          ? ""
                          : Extension.ToThaiNumber(node.education.toString()),
                      salary: node.salary
                        ? Extension.ToThaiNumber(node.salary.toLocaleString())
                        : "",
                      reason:
                        node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
                    };
                    data.push(head);
                  }
                  no += 1;
                  _node = node;
                }
              }),
          );
          _node = null;

          for (let orgChild3 of orgChild3Data.filter(
            (orgChild3) => orgChild3.orgChild2Id === orgChild2.id,
          )) {
            await Promise.all(
              orgChild3.posMasters
                .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
                .map(async (posMaster) => {
                  if (posMaster.orgChild4Id == null) {
                    const positionName = [
                      ...new Set(posMaster.positions.map((x) => x.positionName)),
                    ];
                    const posType = [
                      ...new Set(
                        posMaster.positions
                          .filter((x: any) => x.posType != null)
                          .map((x) => x.posType.posTypeName),
                      ),
                    ];
                    const posLevel = [
                      ...new Set(
                        posMaster.positions
                          .filter((x: any) => x.posLevel != null)
                          .map((x) => x.posLevel.posLevelName),
                      ),
                    ];
                    const posExecutive = [
                      ...new Set(
                        posMaster.positions
                          .filter((x: any) => x.posExecutive != null)
                          .map((x) => x.posExecutive.posExecutiveName),
                      ),
                    ];
                    let positionMasterProfileOld: any = null;
                    if (posMaster.current_holder != null) {
                      positionMasterProfileOld = posMaster.current_holder.current_holders.find(
                        (x) => x.orgRevisionId == orgRevisionActive.id,
                      );
                    }

                    let positionMasterOld: any = null;
                    let profilePositionName: any = [];
                    let profilePosType: any = [];
                    let profilePosLevel: any = [];
                    let profilePosExecutive: any = [];
                    if (posMaster.ancestorDNA != null && posMaster.ancestorDNA != "") {
                      positionMasterOld = orgRevisionActive.posMasters.find(
                        (x: any) =>
                          x.orgRevisionId == orgRevisionActive.id &&
                          x.ancestorDNA == posMaster.ancestorDNA,
                      );
                      profilePositionName = [
                        ...new Set(positionMasterOld.positions.map((x: any) => x.positionName)),
                      ];
                      profilePosType = [
                        ...new Set(
                          positionMasterOld.positions
                            .filter((x: any) => x.posType != null)
                            .map((x: any) => x.posType.posTypeName),
                        ),
                      ];
                      profilePosLevel = [
                        ...new Set(
                          positionMasterOld.positions
                            .filter((x: any) => x.posLevel != null)
                            .map((x: any) => x.posLevel.posLevelName),
                        ),
                      ];
                      profilePosExecutive = [
                        ...new Set(
                          positionMasterOld.positions
                            .filter((x: any) => x.posExecutive != null)
                            .map((x: any) => x.posExecutive.posExecutiveName),
                        ),
                      ];
                    }
                    let education: any = "";
                    if (
                      posMaster.current_holder != null &&
                      posMaster.current_holder.profileEducations != null &&
                      posMaster.current_holder.profileEducations.length > 0
                    ) {
                      let _education: any = posMaster.current_holder.profileEducations
                        .filter((x) => x.isEducation == true || x.isUse == true)
                        .sort((a, b) => {
                          if (a.isEducation !== b.isEducation) {
                            return a.isEducation ? -1 : 1;
                          }
                          return b.level - a.level;
                        });
                      if (_education.length > 0) {
                        education = _education.map((e: any) => e.degree).join(", ");
                      }
                    }
                    let salary: any = "";
                    if (
                      posMaster.current_holder != null &&
                      posMaster.current_holder.profileSalary != null &&
                      posMaster.current_holder.profileSalary.length > 0
                    ) {
                      let _salary: any = posMaster.current_holder.profileSalary.sort(
                        (a, b) =>
                          (b.commandDateAffect == null ? 0 : b.commandDateAffect.getTime()) -
                          (a.commandDateAffect == null ? 0 : a.commandDateAffect.getTime()),
                      );
                      if (_salary.length > 0) {
                        salary = _salary[0];
                      }
                    }

                    let node = {
                      posMasterOrder: posMaster.posMasterOrder, //
                      isSit: posMaster.isSit, //
                      orgTreeName: orgChild3.orgChild3Name,
                      orgTreeShortName: orgChild3.orgChild3ShortName,
                      posMasterNo: posMaster.posMasterNo,
                      positionName:
                        posMaster.current_holder == null
                          ? positionName.join(" หรือ ")
                          : posMaster.isSit == false
                            ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                                ?.positionName
                            : posMaster.current_holder.position,
                      posType:
                        posMaster.current_holder == null
                          ? posType.join(" หรือ ")
                          : posMaster.isSit == false
                            ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                                ?.posType?.posTypeName
                            : posMaster.current_holder.posType == null
                              ? "-"
                              : posMaster.current_holder.posType.posTypeName,
                      posLevel:
                        posMaster.current_holder == null
                          ? posLevel.join(" หรือ ")
                          : posMaster.isSit == false
                            ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                                ?.posLevel?.posLevelName
                            : posMaster.current_holder.posLevel == null
                              ? "-"
                              : posMaster.current_holder.posLevel.posLevelName,
                      posExecutive:
                        posMaster.current_holder == null
                          ? posExecutive.join(" หรือ ")
                          : posMaster.isSit == false
                            ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                                ?.posExecutive?.posExecutiveName
                            : positionMasterProfileOld == null
                              ? "-"
                              : positionMasterProfileOld.positions.find(
                                  (x: any) => x.positionIsSelected == true,
                                )?.posExecutive?.posExecutiveName,

                      profileOrgName:
                        posMaster.current_holder == null
                          ? orgChild3.orgChild3Name
                          : positionMasterProfileOld == null
                            ? "-"
                            : positionMasterProfileOld.orgChild4 != null
                              ? positionMasterProfileOld.orgChild4.orgChild4Name
                              : positionMasterProfileOld.orgChild3 != null
                                ? positionMasterProfileOld.orgChild3.orgChild3Name
                                : positionMasterProfileOld.orgChild2 != null
                                  ? positionMasterProfileOld.orgChild2.orgChild2Name
                                  : positionMasterProfileOld.orgChild1 != null
                                    ? positionMasterProfileOld.orgChild1.orgChild1Name
                                    : positionMasterProfileOld.orgRoot != null
                                      ? positionMasterProfileOld.orgRoot.orgRootName
                                      : "-",
                      profileOrgShortName:
                        posMaster.current_holder == null
                          ? orgChild3.orgChild3ShortName
                          : positionMasterProfileOld == null
                            ? "-"
                            : positionMasterProfileOld.orgChild4 != null
                              ? positionMasterProfileOld.orgChild4.orgChild4ShortName
                              : positionMasterProfileOld.orgChild3 != null
                                ? positionMasterProfileOld.orgChild3.orgChild3ShortName
                                : positionMasterProfileOld.orgChild2 != null
                                  ? positionMasterProfileOld.orgChild2.orgChild2ShortName
                                  : positionMasterProfileOld.orgChild1 != null
                                    ? positionMasterProfileOld.orgChild1.orgChild1ShortName
                                    : positionMasterProfileOld.orgRoot != null
                                      ? positionMasterProfileOld.orgRoot.orgRootShortName
                                      : "-",
                      profileFullname:
                        posMaster.current_holder == null
                          ? "- ว่าง -"
                          : `${posMaster.current_holder.prefix}${posMaster.current_holder.firstName} ${posMaster.current_holder.lastName}`,
                      profilePosMasterNo:
                        posMaster.current_holder == null
                          ? positionMasterOld == null
                            ? "-"
                            : positionMasterOld.posMasterNo
                          : positionMasterProfileOld == null
                            ? "-"
                            : positionMasterProfileOld.posMasterNo,
                      profilePositionName:
                        posMaster.current_holder == null
                          ? positionMasterOld == null
                            ? positionName.join(" หรือ ")
                            : profilePositionName.join(" หรือ ")
                          : posMaster.current_holder.position,
                      profilePosType:
                        posMaster.current_holder == null
                          ? positionMasterOld == null
                            ? posType.join(" หรือ ")
                            : profilePosType.join(" หรือ ")
                          : posMaster.current_holder.posType == null
                            ? "-"
                            : posMaster.current_holder.posType.posTypeName,
                      profilePosLevel:
                        posMaster.current_holder == null
                          ? positionMasterOld == null
                            ? posLevel.join(" หรือ ")
                            : profilePosLevel.join(" หรือ ")
                          : posMaster.current_holder.posLevel == null
                            ? "-"
                            : posMaster.current_holder.posLevel.posLevelName,
                      profilePosExecutive:
                        posMaster.current_holder == null
                          ? positionMasterOld == null
                            ? posExecutive.join(" หรือ ")
                            : profilePosExecutive.join(" หรือ ")
                          : positionMasterProfileOld == null
                            ? "-"
                            : positionMasterProfileOld.positions.find(
                                (x: any) => x.positionIsSelected == true,
                              )?.posExecutive?.posExecutiveName,
                      education: education == "" ? "" : education,
                      salary: salary == "" ? "" : salary.amount,
                      reason: posMaster.reason,
                    };
                    if (_node == null) {
                      const head = {
                        posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName.toString()),
                        profileFullname: Extension.ToThaiNumber(node.profileOrgName.toString()),
                        posExecutive: Extension.ToThaiNumber(node.orgTreeName.toString()),
                        positionName: "",
                        posType: "",
                        posLevel: "",
                        profilePosMasterNo: Extension.ToThaiNumber(
                          node.profileOrgShortName.toString(),
                        ),
                        profilePosExecutive: "",
                        profilePositionName: "",
                        profilePosType: "",
                        profilePosLevel: "",
                        education: "",
                        salary: "",
                        reason: "",
                      };
                      data.push(head);
                      const _head = {
                        no: Extension.ToThaiNumber(no.toString()),
                        posMasterNo:
                          node.posMasterNo == null
                            ? ""
                            : Extension.ToThaiNumber(node.posMasterNo.toString()),
                        profileFullname:
                          node.profileFullname == null
                            ? ""
                            : Extension.ToThaiNumber(node.profileFullname.toString()),
                        posExecutive:
                          node.posExecutive == null
                            ? ""
                            : Extension.ToThaiNumber(node.posExecutive.toString()),
                        positionName:
                          node.positionName == null
                            ? ""
                            : Extension.ToThaiNumber(node.positionName.toString()),
                        posType:
                          node.posType == null
                            ? ""
                            : Extension.ToThaiNumber(node.posType.toString()),
                        posLevel:
                          node.posLevel == null
                            ? ""
                            : Extension.ToThaiNumber(node.posLevel.toString()),
                        profilePosMasterNo: Extension.ToThaiNumber(
                          node.profilePosMasterNo.toString(),
                        ),
                        profilePosExecutive:
                          node.profilePosExecutive == null
                            ? ""
                            : Extension.ToThaiNumber(node.profilePosExecutive.toString()),
                        profilePositionName:
                          node.profilePositionName == null
                            ? ""
                            : Extension.ToThaiNumber(node.profilePositionName.toString()),
                        profilePosType:
                          node.profilePosType == null
                            ? ""
                            : Extension.ToThaiNumber(node.profilePosType.toString()),
                        profilePosLevel:
                          node.profilePosLevel == null
                            ? ""
                            : Extension.ToThaiNumber(node.profilePosLevel.toString()),
                        education:
                          node.education == null
                            ? ""
                            : Extension.ToThaiNumber(node.education.toString()),
                        salary: node.salary
                          ? Extension.ToThaiNumber(node.salary.toLocaleString())
                          : "",
                        reason:
                          node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
                      };
                      data.push(_head);
                    } else {
                      if (
                        node.orgTreeShortName != _node.orgTreeShortName ||
                        node.orgTreeName != _node.orgTreeName ||
                        node.profileOrgShortName != _node.profileOrgShortName ||
                        node.profileOrgName != _node.profileOrgName
                      ) {
                        const head = {
                          posMasterNo:
                            node.orgTreeShortName == _node.orgTreeShortName
                              ? ""
                              : node.orgTreeShortName,
                          profileFullname:
                            node.profileOrgName == _node.profileOrgName ? "" : node.profileOrgName,
                          posExecutive:
                            node.orgTreeName == _node.orgTreeName ? "" : node.orgTreeName,
                          positionName: "",
                          posType: "",
                          posLevel: "",
                          profilePosMasterNo:
                            node.profileOrgShortName == _node.profileOrgShortName
                              ? ""
                              : node.profileOrgShortName,
                          profilePosExecutive: "",
                          profilePositionName: "",
                          profilePosType: "",
                          profilePosLevel: "",
                          education: "",
                          salary: "",
                          reason: "",
                        };
                        data.push(head);
                        _node == null;
                      }
                      const head = {
                        no: Extension.ToThaiNumber(no.toString()),
                        posMasterNo:
                          node.posMasterNo == null
                            ? ""
                            : Extension.ToThaiNumber(node.posMasterNo.toString()),
                        profileFullname:
                          node.profileFullname == null
                            ? ""
                            : Extension.ToThaiNumber(node.profileFullname.toString()),
                        posExecutive:
                          node.posExecutive == null
                            ? ""
                            : Extension.ToThaiNumber(node.posExecutive.toString()),
                        positionName:
                          node.positionName == null
                            ? ""
                            : Extension.ToThaiNumber(node.positionName.toString()),
                        posType:
                          node.posType == null
                            ? ""
                            : Extension.ToThaiNumber(node.posType.toString()),
                        posLevel:
                          node.posLevel == null
                            ? ""
                            : Extension.ToThaiNumber(node.posLevel.toString()),
                        profilePosMasterNo: Extension.ToThaiNumber(
                          node.profilePosMasterNo.toString(),
                        ),
                        profilePosExecutive:
                          node.profilePosExecutive == null
                            ? ""
                            : Extension.ToThaiNumber(node.profilePosExecutive.toString()),
                        profilePositionName:
                          node.profilePositionName == null
                            ? ""
                            : Extension.ToThaiNumber(node.profilePositionName.toString()),
                        profilePosType:
                          node.profilePosType == null
                            ? ""
                            : Extension.ToThaiNumber(node.profilePosType.toString()),
                        profilePosLevel:
                          node.profilePosLevel == null
                            ? ""
                            : Extension.ToThaiNumber(node.profilePosLevel.toString()),
                        education:
                          node.education == null
                            ? ""
                            : Extension.ToThaiNumber(node.education.toString()),
                        salary: node.salary
                          ? Extension.ToThaiNumber(node.salary.toLocaleString())
                          : "",
                        reason:
                          node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
                      };
                      data.push(head);
                    }
                    no += 1;
                    _node = node;
                  }
                }),
            );
            _node = null;

            for (let orgChild4 of orgChild4Data.filter(
              (orgChild4) => orgChild4.orgChild3Id === orgChild3.id,
            )) {
              await Promise.all(
                orgChild4.posMasters
                  .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
                  .map(async (posMaster) => {
                    const positionName = [
                      ...new Set(posMaster.positions.map((x) => x.positionName)),
                    ];
                    const posType = [
                      ...new Set(
                        posMaster.positions
                          .filter((x: any) => x.posType != null)
                          .map((x) => x.posType.posTypeName),
                      ),
                    ];
                    const posLevel = [
                      ...new Set(
                        posMaster.positions
                          .filter((x: any) => x.posLevel != null)
                          .map((x) => x.posLevel.posLevelName),
                      ),
                    ];
                    const posExecutive = [
                      ...new Set(
                        posMaster.positions
                          .filter((x: any) => x.posExecutive != null)
                          .map((x) => x.posExecutive.posExecutiveName),
                      ),
                    ];
                    let positionMasterProfileOld: any = null;
                    if (posMaster.current_holder != null) {
                      positionMasterProfileOld = posMaster.current_holder.current_holders.find(
                        (x) => x.orgRevisionId == orgRevisionActive.id,
                      );
                    }

                    let positionMasterOld: any = null;
                    let profilePositionName: any = [];
                    let profilePosType: any = [];
                    let profilePosLevel: any = [];
                    let profilePosExecutive: any = [];
                    if (posMaster.ancestorDNA != null && posMaster.ancestorDNA != "") {
                      positionMasterOld = orgRevisionActive.posMasters.find(
                        (x: any) =>
                          x.orgRevisionId == orgRevisionActive.id &&
                          x.ancestorDNA == posMaster.ancestorDNA,
                      );
                      profilePositionName = [
                        ...new Set(positionMasterOld.positions.map((x: any) => x.positionName)),
                      ];
                      profilePosType = [
                        ...new Set(
                          positionMasterOld.positions
                            .filter((x: any) => x.posType != null)
                            .map((x: any) => x.posType.posTypeName),
                        ),
                      ];
                      profilePosLevel = [
                        ...new Set(
                          positionMasterOld.positions
                            .filter((x: any) => x.posLevel != null)
                            .map((x: any) => x.posLevel.posLevelName),
                        ),
                      ];
                      profilePosExecutive = [
                        ...new Set(
                          positionMasterOld.positions
                            .filter((x: any) => x.posExecutive != null)
                            .map((x: any) => x.posExecutive.posExecutiveName),
                        ),
                      ];
                    }
                    let education: any = "";
                    if (
                      posMaster.current_holder != null &&
                      posMaster.current_holder.profileEducations != null &&
                      posMaster.current_holder.profileEducations.length > 0
                    ) {
                      let _education: any = posMaster.current_holder.profileEducations
                        .filter((x) => x.isEducation == true || x.isUse == true)
                        .sort((a, b) => {
                          if (a.isEducation !== b.isEducation) {
                            return a.isEducation ? -1 : 1;
                          }
                          return b.level - a.level;
                        });
                      if (_education.length > 0) {
                        education = _education.map((e: any) => e.degree).join(", ");
                      }
                    }
                    let salary: any = "";
                    if (
                      posMaster.current_holder != null &&
                      posMaster.current_holder.profileSalary != null &&
                      posMaster.current_holder.profileSalary.length > 0
                    ) {
                      let _salary: any = posMaster.current_holder.profileSalary.sort(
                        (a, b) =>
                          (b.commandDateAffect == null ? 0 : b.commandDateAffect.getTime()) -
                          (a.commandDateAffect == null ? 0 : a.commandDateAffect.getTime()),
                      );
                      if (_salary.length > 0) {
                        salary = _salary[0];
                      }
                    }

                    let node = {
                      posMasterOrder: posMaster.posMasterOrder, //
                      isSit: posMaster.isSit, //
                      orgTreeName: orgChild4.orgChild4Name,
                      orgTreeShortName: orgChild4.orgChild4ShortName,
                      posMasterNo: posMaster.posMasterNo,
                      positionName:
                        posMaster.current_holder == null
                          ? positionName.join(" หรือ ")
                          : posMaster.isSit == false
                            ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                                ?.positionName
                            : posMaster.current_holder.position,
                      posType:
                        posMaster.current_holder == null
                          ? posType.join(" หรือ ")
                          : posMaster.isSit == false
                            ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                                ?.posType?.posTypeName
                            : posMaster.current_holder.posType == null
                              ? "-"
                              : posMaster.current_holder.posType.posTypeName,
                      posLevel:
                        posMaster.current_holder == null
                          ? posLevel.join(" หรือ ")
                          : posMaster.isSit == false
                            ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                                ?.posLevel?.posLevelName
                            : posMaster.current_holder.posLevel == null
                              ? "-"
                              : posMaster.current_holder.posLevel.posLevelName,
                      posExecutive:
                        posMaster.current_holder == null
                          ? posExecutive.join(" หรือ ")
                          : posMaster.isSit == false
                            ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                                ?.posExecutive?.posExecutiveName
                            : positionMasterProfileOld == null
                              ? "-"
                              : positionMasterProfileOld.positions.find(
                                  (x: any) => x.positionIsSelected == true,
                                )?.posExecutive?.posExecutiveName,

                      profileOrgName:
                        posMaster.current_holder == null
                          ? orgChild4.orgChild4Name
                          : positionMasterProfileOld == null
                            ? "-"
                            : positionMasterProfileOld.orgChild4 != null
                              ? positionMasterProfileOld.orgChild4.orgChild4Name
                              : positionMasterProfileOld.orgChild3 != null
                                ? positionMasterProfileOld.orgChild3.orgChild3Name
                                : positionMasterProfileOld.orgChild2 != null
                                  ? positionMasterProfileOld.orgChild2.orgChild2Name
                                  : positionMasterProfileOld.orgChild1 != null
                                    ? positionMasterProfileOld.orgChild1.orgChild1Name
                                    : positionMasterProfileOld.orgRoot != null
                                      ? positionMasterProfileOld.orgRoot.orgRootName
                                      : "-",
                      profileOrgShortName:
                        posMaster.current_holder == null
                          ? orgChild4.orgChild4ShortName
                          : positionMasterProfileOld == null
                            ? "-"
                            : positionMasterProfileOld.orgChild4 != null
                              ? positionMasterProfileOld.orgChild4.orgChild4ShortName
                              : positionMasterProfileOld.orgChild3 != null
                                ? positionMasterProfileOld.orgChild3.orgChild3ShortName
                                : positionMasterProfileOld.orgChild2 != null
                                  ? positionMasterProfileOld.orgChild2.orgChild2ShortName
                                  : positionMasterProfileOld.orgChild1 != null
                                    ? positionMasterProfileOld.orgChild1.orgChild1ShortName
                                    : positionMasterProfileOld.orgRoot != null
                                      ? positionMasterProfileOld.orgRoot.orgRootShortName
                                      : "-",
                      profileFullname:
                        posMaster.current_holder == null
                          ? "- ว่าง -"
                          : `${posMaster.current_holder.prefix}${posMaster.current_holder.firstName} ${posMaster.current_holder.lastName}`,
                      profilePosMasterNo:
                        posMaster.current_holder == null
                          ? positionMasterOld == null
                            ? "-"
                            : positionMasterOld.posMasterNo
                          : positionMasterProfileOld == null
                            ? "-"
                            : positionMasterProfileOld.posMasterNo,
                      profilePositionName:
                        posMaster.current_holder == null
                          ? positionMasterOld == null
                            ? positionName.join(" หรือ ")
                            : profilePositionName.join(" หรือ ")
                          : posMaster.current_holder.position,
                      profilePosType:
                        posMaster.current_holder == null
                          ? positionMasterOld == null
                            ? posType.join(" หรือ ")
                            : profilePosType.join(" หรือ ")
                          : posMaster.current_holder.posType == null
                            ? "-"
                            : posMaster.current_holder.posType.posTypeName,
                      profilePosLevel:
                        posMaster.current_holder == null
                          ? positionMasterOld == null
                            ? posLevel.join(" หรือ ")
                            : profilePosLevel.join(" หรือ ")
                          : posMaster.current_holder.posLevel == null
                            ? "-"
                            : posMaster.current_holder.posLevel.posLevelName,
                      profilePosExecutive:
                        posMaster.current_holder == null
                          ? positionMasterOld == null
                            ? posExecutive.join(" หรือ ")
                            : profilePosExecutive.join(" หรือ ")
                          : positionMasterProfileOld == null
                            ? "-"
                            : positionMasterProfileOld.positions.find(
                                (x: any) => x.positionIsSelected == true,
                              )?.posExecutive?.posExecutiveName,
                      education: education == "" ? "" : education,
                      salary: salary == "" ? "" : salary.amount,
                      reason: posMaster.reason,
                    };
                    if (_node == null) {
                      const head = {
                        posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName.toString()),
                        profileFullname: Extension.ToThaiNumber(node.profileOrgName.toString()),
                        posExecutive: Extension.ToThaiNumber(node.orgTreeName.toString()),
                        positionName: "",
                        posType: "",
                        posLevel: "",
                        profilePosMasterNo: Extension.ToThaiNumber(
                          node.profileOrgShortName.toString(),
                        ),
                        profilePosExecutive: "",
                        profilePositionName: "",
                        profilePosType: "",
                        profilePosLevel: "",
                        education: "",
                        salary: "",
                        reason: "",
                      };
                      data.push(head);
                      const _head = {
                        no: Extension.ToThaiNumber(no.toString()),
                        posMasterNo:
                          node.posMasterNo == null
                            ? ""
                            : Extension.ToThaiNumber(node.posMasterNo.toString()),
                        profileFullname:
                          node.profileFullname == null
                            ? ""
                            : Extension.ToThaiNumber(node.profileFullname.toString()),
                        posExecutive:
                          node.posExecutive == null
                            ? ""
                            : Extension.ToThaiNumber(node.posExecutive.toString()),
                        positionName:
                          node.positionName == null
                            ? ""
                            : Extension.ToThaiNumber(node.positionName.toString()),
                        posType:
                          node.posType == null
                            ? ""
                            : Extension.ToThaiNumber(node.posType.toString()),
                        posLevel:
                          node.posLevel == null
                            ? ""
                            : Extension.ToThaiNumber(node.posLevel.toString()),
                        profilePosMasterNo: Extension.ToThaiNumber(
                          node.profilePosMasterNo.toString(),
                        ),
                        profilePosExecutive:
                          node.profilePosExecutive == null
                            ? ""
                            : Extension.ToThaiNumber(node.profilePosExecutive.toString()),
                        profilePositionName:
                          node.profilePositionName == null
                            ? ""
                            : Extension.ToThaiNumber(node.profilePositionName.toString()),
                        profilePosType:
                          node.profilePosType == null
                            ? ""
                            : Extension.ToThaiNumber(node.profilePosType.toString()),
                        profilePosLevel:
                          node.profilePosLevel == null
                            ? ""
                            : Extension.ToThaiNumber(node.profilePosLevel.toString()),
                        education:
                          node.education == null
                            ? ""
                            : Extension.ToThaiNumber(node.education.toString()),
                        salary: node.salary
                          ? Extension.ToThaiNumber(node.salary.toLocaleString())
                          : "",
                        reason:
                          node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
                      };
                      data.push(_head);
                    } else {
                      if (
                        node.orgTreeShortName != _node.orgTreeShortName ||
                        node.orgTreeName != _node.orgTreeName ||
                        node.profileOrgShortName != _node.profileOrgShortName ||
                        node.profileOrgName != _node.profileOrgName
                      ) {
                        const head = {
                          posMasterNo:
                            node.orgTreeShortName == _node.orgTreeShortName
                              ? ""
                              : node.orgTreeShortName,
                          profileFullname:
                            node.profileOrgName == _node.profileOrgName ? "" : node.profileOrgName,
                          posExecutive:
                            node.orgTreeName == _node.orgTreeName ? "" : node.orgTreeName,
                          positionName: "",
                          posType: "",
                          posLevel: "",
                          profilePosMasterNo:
                            node.profileOrgShortName == _node.profileOrgShortName
                              ? ""
                              : node.profileOrgShortName,
                          profilePosExecutive: "",
                          profilePositionName: "",
                          profilePosType: "",
                          profilePosLevel: "",
                          education: "",
                          salary: "",
                          reason: "",
                        };
                        data.push(head);
                        _node == null;
                      }
                      const head = {
                        no: Extension.ToThaiNumber(no.toString()),
                        posMasterNo:
                          node.posMasterNo == null
                            ? ""
                            : Extension.ToThaiNumber(node.posMasterNo.toString()),
                        profileFullname:
                          node.profileFullname == null
                            ? ""
                            : Extension.ToThaiNumber(node.profileFullname.toString()),
                        posExecutive:
                          node.posExecutive == null
                            ? ""
                            : Extension.ToThaiNumber(node.posExecutive.toString()),
                        positionName:
                          node.positionName == null
                            ? ""
                            : Extension.ToThaiNumber(node.positionName.toString()),
                        posType:
                          node.posType == null
                            ? ""
                            : Extension.ToThaiNumber(node.posType.toString()),
                        posLevel:
                          node.posLevel == null
                            ? ""
                            : Extension.ToThaiNumber(node.posLevel.toString()),
                        profilePosMasterNo: Extension.ToThaiNumber(
                          node.profilePosMasterNo.toString(),
                        ),
                        profilePosExecutive:
                          node.profilePosExecutive == null
                            ? ""
                            : Extension.ToThaiNumber(node.profilePosExecutive.toString()),
                        profilePositionName:
                          node.profilePositionName == null
                            ? ""
                            : Extension.ToThaiNumber(node.profilePositionName.toString()),
                        profilePosType:
                          node.profilePosType == null
                            ? ""
                            : Extension.ToThaiNumber(node.profilePosType.toString()),
                        profilePosLevel:
                          node.profilePosLevel == null
                            ? ""
                            : Extension.ToThaiNumber(node.profilePosLevel.toString()),
                        education:
                          node.education == null
                            ? ""
                            : Extension.ToThaiNumber(node.education.toString()),
                        salary: node.salary
                          ? Extension.ToThaiNumber(node.salary.toLocaleString())
                          : "",
                        reason:
                          node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
                      };
                      data.push(head);
                    }
                    no += 1;
                    _node = node;
                  }),
              );
              _node = null;
            }
          }
        }
      }
    }

    return new HttpSuccess({
      template: "report2",
      reportName: "report2",
      data: {
        rootName: orgRootData.length > 0 ? orgRootData[0].orgRootName : "-",
        data: data,
      },
    });
  }
  /**
   * API Report3
   *
   * @summary Report3
   *
   */
  @Post("report3")
  async NewReport3(
    @Body()
    reqBody: {
      node: number;
      nodeId: string;
    },
  ) {
    // @Get("report3/{rootId}")
    // async findReport3(@Path() rootId: string) {
    // const orgRevision = await this.orgRevisionRepository.findOne({
    //   where: { orgRevisionIsDraft: true, orgRevisionIsCurrent: false },
    //   relations: ["orgRoots"],
    // });
    // if (!orgRevision) {
    //   throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
    // }
    let nodeId: string = reqBody.nodeId ? reqBody.nodeId : "";
    let node: number = reqBody.node ? reqBody.node : 0;
    if (nodeId === "" || node < 0 || node > 4) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
    }
    // ดึงแค่ rootId ก่อน ถ้าลูกค้า confirm ค่อยปรับ
    switch (node) {
      case 0: {
        const orgRoot = await this.orgRootRepository.findOne({
          select: ["id"],
          where: { id: nodeId },
        });
        if (!orgRoot) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
        nodeId = orgRoot.id;
        break;
      }
      case 1: {
        const orgChild1 = await this.child1Repository.findOne({
          select: ["id", "orgRootId"],
          where: { id: nodeId },
        });
        if (!orgChild1) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
        nodeId = orgChild1.orgRootId;
        break;
      }
      case 2: {
        const orgChild2 = await this.child2Repository.findOne({
          select: ["id", "orgRootId"],
          where: { id: nodeId },
        });
        if (!orgChild2) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
        nodeId = orgChild2.orgRootId;
        break;
      }
      case 3: {
        const orgChild3 = await this.child3Repository.findOne({
          select: ["id", "orgRootId"],
          where: { id: nodeId },
        });
        if (!orgChild3) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
        nodeId = orgChild3.orgRootId;
        break;
      }
      case 4: {
        const orgChild4 = await this.child4Repository.findOne({
          select: ["id", "orgRootId"],
          where: { id: nodeId },
        });
        if (!orgChild4) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
        nodeId = orgChild4.orgRootId;
        break;
      }
      default:
        throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
    }
    // Step 1: ดึงข้อมูล OrgRoot พื้นฐาน
    const orgRootData = await this.orgRootRepository
      .createQueryBuilder("orgRoot")
      .select([
        "orgRoot.id",
        "orgRoot.orgRootName",
        "orgRoot.orgRootShortName",
        "orgRoot.orgRootOrder",
      ])
      .where("orgRoot.id = :nodeId", { nodeId })
      .orderBy("orgRoot.orgRootOrder", "ASC")
      .getMany();

    if (!orgRootData || orgRootData.length === 0) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลองค์กร");
    }

    // Step 2: ดึงข้อมูล PosMasters ที่เกี่ยวข้องเท่านั้น
    const posMastersData = await this.posMasterRepository
      .createQueryBuilder("posMaster")
      .select([
        "posMaster.id",
        "posMaster.posMasterOrder",
        "posMaster.isSit",
        "posMaster.posMasterNo",
        "posMaster.ancestorDNA",
        "posMaster.reason",
        "posMaster.orgRootId",
        "posMaster.orgChild1Id",
        "posMaster.current_holderId",
        "posMaster.next_holderId",
      ])
      .where("posMaster.orgRootId = :nodeId", { nodeId })
      .andWhere("posMaster.orgChild1Id IS NULL") // เฉพาะ root level
      .orderBy("posMaster.posMasterOrder", "ASC")
      .addOrderBy("posMaster.posMasterCreatedAt", "ASC")
      .getMany();

    // Step 3: ดึงข้อมูล Profiles ที่ใช้จริงเท่านั้น
    const profileIds = [
      ...new Set([
        ...posMastersData.map((pm: any) => pm.current_holderId).filter(Boolean),
        ...posMastersData.map((pm: any) => pm.next_holderId).filter(Boolean),
      ]),
    ];

    let profilesData: any[] = [];
    if (profileIds.length > 0) {
      profilesData = await this.profileRepository
        .createQueryBuilder("profile")
        .select([
          "profile.id",
          "profile.prefix",
          "profile.firstName",
          "profile.lastName",
          "profile.position",
        ])
        .where("profile.id IN (:...profileIds)", { profileIds })
        .getMany();
    }

    // Step 4: ดึงข้อมูล Education ล่าสุดของแต่ละ Profile
    let educationsData: any[] = [];
    if (profileIds.length > 0) {
      educationsData = await this.profileEducationRepository
        .createQueryBuilder("pe")
        .select(["pe.profileId", "pe.finishDate", "pe.degree", "pe.level", "pe.isDeleted"])
        .where("pe.profileId IN (:...profileIds)", { profileIds })
        .andWhere("pe.isDeleted = :isDeleted", { isDeleted: false })
        .andWhere(
          `(pe.profileId, COALESCE(pe.finishDate, '1900-01-01'), pe.level) IN (
          SELECT pe2.profileId, 
                 COALESCE(MAX(pe2.finishDate), '1900-01-01'),
                 CASE 
                   WHEN MAX(pe2.finishDate) IS NOT NULL THEN 
                     (SELECT pe3.level FROM profileEducation pe3 
                      WHERE pe3.profileId = pe2.profileId 
                      AND pe3.finishDate = MAX(pe2.finishDate) LIMIT 1)
                   ELSE MIN(pe2.level)
                 END
          FROM profileEducation pe2 
          WHERE pe2.profileId IN (:...profileIds)
          GROUP BY pe2.profileId
        )`,
          { profileIds },
        )
        .getMany();
    }

    // Step 5: ดึงข้อมูล Salary ล่าสุดของแต่ละ Profile
    let salariesData: any[] = [];
    if (profileIds.length > 0) {
      salariesData = await this.profileSalaryRepository
        .createQueryBuilder("ps")
        .select([
          "ps.profileId",
          "ps.commandDateAffect",
          "ps.amount",
          "ps.positionSalaryAmount",
          "ps.mouthSalaryAmount",
        ])
        .where("ps.profileId IN (:...profileIds)", { profileIds })
        .andWhere(
          `(ps.profileId, ps.commandDateAffect) IN (
          SELECT ps2.profileId, MAX(ps2.commandDateAffect) 
          FROM profileSalary ps2 
          WHERE ps2.profileId IN (:...profileIds)
          GROUP BY ps2.profileId
        )`,
          { profileIds },
        )
        .getMany();
    }

    // Step 6: ดึงข้อมูล Positions ที่เกี่ยวข้อง
    const posMasterIds = posMastersData.map((pm: any) => pm.id);
    let positionsData: any[] = [];
    if (posMasterIds.length > 0) {
      positionsData = await this.positionRepository
        .createQueryBuilder("position")
        .leftJoinAndSelect("position.posType", "posType")
        .leftJoinAndSelect("position.posLevel", "posLevel")
        .leftJoinAndSelect("position.posExecutive", "posExecutive")
        .select([
          "position.id",
          "position.positionName",
          "position.positionIsSelected",
          "position.posMasterId",
          "posType.id",
          "posType.posTypeName",
          "posLevel.id",
          "posLevel.posLevelName",
          "posExecutive.id",
          "posExecutive.posExecutiveName",
        ])
        .where("position.posMasterId IN (:...posMasterIds)", { posMasterIds })
        .getMany();
    }

    // Step 7: Combine ข้อมูลกลับเหมือนเดิม
    for (let orgRoot of orgRootData) {
      orgRoot.posMasters = posMastersData.filter((pm: any) => pm.orgRootId === orgRoot.id);

      for (let posMaster of orgRoot.posMasters) {
        // Attach current_holder
        if (posMaster.current_holderId) {
          posMaster.current_holder = profilesData.find(
            (p: any) => p.id === posMaster.current_holderId,
          );
          if (posMaster.current_holder) {
            posMaster.current_holder.profileEducations = educationsData.filter(
              (ed: any) => ed.profileId === posMaster.current_holderId,
            );
            posMaster.current_holder.profileSalary = salariesData.filter(
              (sal: any) => sal.profileId === posMaster.current_holderId,
            );
          }
        }

        // Attach next_holder
        if (posMaster.next_holderId) {
          posMaster.next_holder = profilesData.find((p: any) => p.id === posMaster.next_holderId);
          if (posMaster.next_holder) {
            posMaster.next_holder.profileEducations = educationsData.filter(
              (ed: any) => ed.profileId === posMaster.next_holderId,
            );
            posMaster.next_holder.profileSalary = salariesData.filter(
              (sal: any) => sal.profileId === posMaster.next_holderId,
            );
          }
        }

        // Attach positions
        posMaster.positions = positionsData.filter((pos: any) => pos.posMasterId === posMaster.id);
      }
    }

    if (!orgRootData || orgRootData.length === 0) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลองค์กร");
    }

    const orgName = orgRootData[0].orgRootName ?? "";
    const orgRootIds = orgRootData.map((orgRoot) => orgRoot.id) || null;

    // Step 8: ปรับปรุง orgChild1Data - ใช้ optimized approach
    const orgChild1Data = await this.child1Repository
      .createQueryBuilder("orgChild1")
      .select([
        "orgChild1.id",
        "orgChild1.orgRootId",
        "orgChild1.orgChild1Name",
        "orgChild1.orgChild1ShortName",
        "orgChild1.orgChild1Order",
      ])
      .where("orgChild1.orgRootId IN (:...orgRootIds)", { orgRootIds })
      .orderBy("orgChild1.orgChild1Order", "ASC")
      .getMany();

    // ดึงข้อมูล PosMasters สำหรับ orgChild1
    const orgChild1Ids = orgChild1Data.map((orgChild1) => orgChild1.id);
    let child1PosMasters: any[] = [];
    if (orgChild1Ids.length > 0) {
      child1PosMasters = await this.posMasterRepository
        .createQueryBuilder("posMaster")
        .select([
          "posMaster.id",
          "posMaster.posMasterOrder",
          "posMaster.isSit",
          "posMaster.posMasterNo",
          "posMaster.ancestorDNA",
          "posMaster.reason",
          "posMaster.orgChild1Id",
          "posMaster.orgChild2Id",
          "posMaster.current_holderId",
          "posMaster.next_holderId",
        ])
        .where("posMaster.orgChild1Id IN (:...orgChild1Ids)", { orgChild1Ids })
        .andWhere("posMaster.orgChild2Id IS NULL") // เฉพาะ child1 level
        .orderBy("posMaster.posMasterOrder", "ASC")
        .addOrderBy("posMaster.posMasterCreatedAt", "ASC")
        .getMany();
    }

    // รวบรวม Profile IDs สำหรับ child1
    const child1ProfileIds =
      child1PosMasters.length > 0
        ? [
            ...new Set([
              ...child1PosMasters.map((pm: any) => pm.current_holderId).filter(Boolean),
              ...child1PosMasters.map((pm: any) => pm.next_holderId).filter(Boolean),
            ]),
          ]
        : [];

    // ดึงข้อมูล Profiles, Education, Salary, Positions สำหรับ child1
    let child1Profiles: any[] = [];
    let child1Educations: any[] = [];
    let child1Salaries: any[] = [];
    let child1Positions: any[] = [];

    if (child1ProfileIds.length > 0) {
      [child1Profiles, child1Educations, child1Salaries] = await Promise.all([
        this.profileRepository
          .createQueryBuilder("profile")
          .select([
            "profile.id",
            "profile.prefix",
            "profile.firstName",
            "profile.lastName",
            "profile.position",
            "profile.posTypeId",
            "profile.posLevelId",
          ])
          .where("profile.id IN (:...child1ProfileIds)", { child1ProfileIds })
          .getMany(),

        this.profileEducationRepository
          .createQueryBuilder("pe")
          .select(["pe.profileId", "pe.finishDate", "pe.degree", "pe.level", "pe.isDeleted"])
          .where("pe.profileId IN (:...child1ProfileIds)", { child1ProfileIds })
          .andWhere("pe.isDeleted = :isDeleted", { isDeleted: false })
          .andWhere(
            `(pe.profileId, COALESCE(pe.finishDate, '1900-01-01'), pe.level) IN (
            SELECT pe2.profileId, 
                   COALESCE(MAX(pe2.finishDate), '1900-01-01'),
                   CASE 
                     WHEN MAX(pe2.finishDate) IS NOT NULL THEN 
                       (SELECT pe3.level FROM profileEducation pe3 
                        WHERE pe3.profileId = pe2.profileId 
                        AND pe3.finishDate = MAX(pe2.finishDate) LIMIT 1)
                     ELSE MIN(pe2.level)
                   END
            FROM profileEducation pe2 
            WHERE pe2.profileId IN (:...child1ProfileIds)
            GROUP BY pe2.profileId
          )`,
            { child1ProfileIds },
          )
          .getMany(),

        this.profileSalaryRepository
          .createQueryBuilder("ps")
          .select([
            "ps.profileId",
            "ps.commandDateAffect",
            "ps.amount",
            "ps.positionSalaryAmount",
            "ps.mouthSalaryAmount",
          ])
          .where("ps.profileId IN (:...child1ProfileIds)", { child1ProfileIds })
          .andWhere(
            `(ps.profileId, ps.commandDateAffect) IN (
            SELECT ps2.profileId, MAX(ps2.commandDateAffect) 
            FROM profileSalary ps2 
            WHERE ps2.profileId IN (:...child1ProfileIds)
            GROUP BY ps2.profileId
          )`,
            { child1ProfileIds },
          )
          .getMany(),
      ]);
    }

    if (child1PosMasters.length > 0) {
      const child1PosMasterIds = child1PosMasters.map((pm: any) => pm.id);
      child1Positions = await this.positionRepository
        .createQueryBuilder("position")
        .leftJoinAndSelect("position.posType", "posType")
        .leftJoinAndSelect("position.posLevel", "posLevel")
        .leftJoinAndSelect("position.posExecutive", "posExecutive")
        .select([
          "position.id",
          "position.positionName",
          "position.positionIsSelected",
          "position.posMasterId",
          "posType.id",
          "posType.posTypeName",
          "posLevel.id",
          "posLevel.posLevelName",
          "posExecutive.id",
          "posExecutive.posExecutiveName",
        ])
        .where("position.posMasterId IN (:...child1PosMasterIds)", { child1PosMasterIds })
        .getMany();
    }

    // Combine ข้อมูล orgChild1
    for (let orgChild1 of orgChild1Data) {
      orgChild1.posMasters = child1PosMasters.filter((pm: any) => pm.orgChild1Id === orgChild1.id);

      for (let posMaster of orgChild1.posMasters) {
        if (posMaster.current_holderId) {
          posMaster.current_holder = child1Profiles.find(
            (p: any) => p.id === posMaster.current_holderId,
          );
          if (posMaster.current_holder) {
            posMaster.current_holder.profileEducations = child1Educations.filter(
              (ed: any) => ed.profileId === posMaster.current_holderId,
            );
            posMaster.current_holder.profileSalary = child1Salaries.filter(
              (sal: any) => sal.profileId === posMaster.current_holderId,
            );
          }
        }

        if (posMaster.next_holderId) {
          posMaster.next_holder = child1Profiles.find((p: any) => p.id === posMaster.next_holderId);
          if (posMaster.next_holder) {
            posMaster.next_holder.profileEducations = child1Educations.filter(
              (ed: any) => ed.profileId === posMaster.next_holderId,
            );
            posMaster.next_holder.profileSalary = child1Salaries.filter(
              (sal: any) => sal.profileId === posMaster.next_holderId,
            );
          }
        }

        posMaster.positions = child1Positions.filter(
          (pos: any) => pos.posMasterId === posMaster.id,
        );
      }
    }

    // Step 9: ปรับปรุง orgChild2Data
    const originalOrgChild1Ids =
      orgChild1Data.length > 0 ? orgChild1Data.map((orgChild1) => orgChild1.id) : [];
    const orgChild2Data = await this.child2Repository
      .createQueryBuilder("orgChild2")
      .select([
        "orgChild2.id",
        "orgChild2.orgChild1Id",
        "orgChild2.orgChild2Name",
        "orgChild2.orgChild2ShortName",
        "orgChild2.orgChild2Order",
      ])
      .where(
        originalOrgChild1Ids.length > 0
          ? "orgChild2.orgChild1Id IN (:...originalOrgChild1Ids)"
          : "1=0",
        {
          originalOrgChild1Ids,
        },
      )
      .orderBy("orgChild2.orgChild2Order", "ASC")
      .getMany();

    // ดึงข้อมูล PosMasters สำหรับ orgChild2
    const orgChild2Ids = orgChild2Data.map((orgChild2) => orgChild2.id);
    let child2PosMasters: any[] = [];
    if (orgChild2Ids.length > 0) {
      child2PosMasters = await this.posMasterRepository
        .createQueryBuilder("posMaster")
        .select([
          "posMaster.id",
          "posMaster.posMasterOrder",
          "posMaster.isSit",
          "posMaster.posMasterNo",
          "posMaster.ancestorDNA",
          "posMaster.reason",
          "posMaster.orgChild2Id",
          "posMaster.orgChild3Id",
          "posMaster.current_holderId",
          "posMaster.next_holderId",
        ])
        .where("posMaster.orgChild2Id IN (:...orgChild2Ids)", { orgChild2Ids })
        .andWhere("posMaster.orgChild3Id IS NULL") // เฉพาะ child2 level
        .orderBy("posMaster.posMasterOrder", "ASC")
        .addOrderBy("posMaster.posMasterCreatedAt", "ASC")
        .getMany();
    }

    // รวบรวม Profile IDs สำหรับ child2
    const child2ProfileIds =
      child2PosMasters.length > 0
        ? [
            ...new Set([
              ...child2PosMasters.map((pm: any) => pm.current_holderId).filter(Boolean),
              ...child2PosMasters.map((pm: any) => pm.next_holderId).filter(Boolean),
            ]),
          ]
        : [];

    // ดึงข้อมูล Profiles, Education, Salary, Positions สำหรับ child2
    let child2Profiles: any[] = [];
    let child2Educations: any[] = [];
    let child2Salaries: any[] = [];
    let child2Positions: any[] = [];

    if (child2ProfileIds.length > 0) {
      [child2Profiles, child2Educations, child2Salaries] = await Promise.all([
        this.profileRepository
          .createQueryBuilder("profile")
          .select([
            "profile.id",
            "profile.prefix",
            "profile.firstName",
            "profile.lastName",
            "profile.position",
            "profile.posTypeId",
            "profile.posLevelId",
          ])
          .where("profile.id IN (:...child2ProfileIds)", { child2ProfileIds })
          .getMany(),

        this.profileEducationRepository
          .createQueryBuilder("pe")
          .select(["pe.profileId", "pe.finishDate", "pe.degree", "pe.level", "pe.isDeleted"])
          .where("pe.profileId IN (:...child2ProfileIds)", { child2ProfileIds })
          .andWhere("pe.isDeleted = :isDeleted", { isDeleted: false })
          .andWhere(
            `(pe.profileId, COALESCE(pe.finishDate, '1900-01-01'), pe.level) IN (
            SELECT pe2.profileId, 
                   COALESCE(MAX(pe2.finishDate), '1900-01-01'),
                   CASE 
                     WHEN MAX(pe2.finishDate) IS NOT NULL THEN 
                       (SELECT pe3.level FROM profileEducation pe3 
                        WHERE pe3.profileId = pe2.profileId 
                        AND pe3.finishDate = MAX(pe2.finishDate) LIMIT 1)
                     ELSE MIN(pe2.level)
                   END
            FROM profileEducation pe2 
            WHERE pe2.profileId IN (:...child2ProfileIds)
            GROUP BY pe2.profileId
          )`,
            { child2ProfileIds },
          )
          .getMany(),

        this.profileSalaryRepository
          .createQueryBuilder("ps")
          .select([
            "ps.profileId",
            "ps.commandDateAffect",
            "ps.amount",
            "ps.positionSalaryAmount",
            "ps.mouthSalaryAmount",
          ])
          .where("ps.profileId IN (:...child2ProfileIds)", { child2ProfileIds })
          .andWhere(
            `(ps.profileId, ps.commandDateAffect) IN (
            SELECT ps2.profileId, MAX(ps2.commandDateAffect) 
            FROM profileSalary ps2 
            WHERE ps2.profileId IN (:...child2ProfileIds)
            GROUP BY ps2.profileId
          )`,
            { child2ProfileIds },
          )
          .getMany(),
      ]);
    }

    if (child2PosMasters.length > 0) {
      const child2PosMasterIds = child2PosMasters.map((pm: any) => pm.id);
      child2Positions = await this.positionRepository
        .createQueryBuilder("position")
        .leftJoinAndSelect("position.posType", "posType")
        .leftJoinAndSelect("position.posLevel", "posLevel")
        .leftJoinAndSelect("position.posExecutive", "posExecutive")
        .select([
          "position.id",
          "position.positionName",
          "position.positionIsSelected",
          "position.posMasterId",
          "posType.id",
          "posType.posTypeName",
          "posLevel.id",
          "posLevel.posLevelName",
          "posExecutive.id",
          "posExecutive.posExecutiveName",
        ])
        .where("position.posMasterId IN (:...child2PosMasterIds)", { child2PosMasterIds })
        .getMany();
    }

    // Combine ข้อมูล orgChild2
    for (let orgChild2 of orgChild2Data) {
      orgChild2.posMasters = child2PosMasters.filter((pm: any) => pm.orgChild2Id === orgChild2.id);

      for (let posMaster of orgChild2.posMasters) {
        if (posMaster.current_holderId) {
          posMaster.current_holder = child2Profiles.find(
            (p: any) => p.id === posMaster.current_holderId,
          );
          if (posMaster.current_holder) {
            posMaster.current_holder.profileEducations = child2Educations.filter(
              (ed: any) => ed.profileId === posMaster.current_holderId,
            );
            posMaster.current_holder.profileSalary = child2Salaries.filter(
              (sal: any) => sal.profileId === posMaster.current_holderId,
            );
          }
        }

        if (posMaster.next_holderId) {
          posMaster.next_holder = child2Profiles.find((p: any) => p.id === posMaster.next_holderId);
          if (posMaster.next_holder) {
            posMaster.next_holder.profileEducations = child2Educations.filter(
              (ed: any) => ed.profileId === posMaster.next_holderId,
            );
            posMaster.next_holder.profileSalary = child2Salaries.filter(
              (sal: any) => sal.profileId === posMaster.next_holderId,
            );
          }
        }

        posMaster.positions = child2Positions.filter(
          (pos: any) => pos.posMasterId === posMaster.id,
        );
      }
    }

    // Step 10: ปรับปรุง orgChild3Data
    const originalOrgChild2Ids =
      orgChild2Data.length > 0 ? orgChild2Data.map((orgChild2) => orgChild2.id) : [];
    const orgChild3Data = await this.child3Repository
      .createQueryBuilder("orgChild3")
      .select([
        "orgChild3.id",
        "orgChild3.orgChild2Id",
        "orgChild3.orgChild3Name",
        "orgChild3.orgChild3ShortName",
        "orgChild3.orgChild3Order",
      ])
      .where(
        originalOrgChild2Ids.length > 0
          ? "orgChild3.orgChild2Id IN (:...originalOrgChild2Ids)"
          : "1=0",
        {
          originalOrgChild2Ids,
        },
      )
      .orderBy("orgChild3.orgChild3Order", "ASC")
      .getMany();

    // ดึงข้อมูล PosMasters สำหรับ orgChild3
    const orgChild3Ids = orgChild3Data.map((orgChild3) => orgChild3.id);
    let child3PosMasters: any[] = [];
    if (orgChild3Ids.length > 0) {
      child3PosMasters = await this.posMasterRepository
        .createQueryBuilder("posMaster")
        .select([
          "posMaster.id",
          "posMaster.posMasterOrder",
          "posMaster.isSit",
          "posMaster.posMasterNo",
          "posMaster.ancestorDNA",
          "posMaster.reason",
          "posMaster.orgChild2Id",
          "posMaster.orgChild3Id",
          "posMaster.orgChild4Id",
          "posMaster.current_holderId",
          "posMaster.next_holderId",
        ])
        .where("posMaster.orgChild3Id IN (:...orgChild3Ids)", { orgChild3Ids })
        .andWhere("posMaster.orgChild4Id IS NULL") // เฉพาะ child3 level
        .orderBy("posMaster.posMasterOrder", "ASC")
        .addOrderBy("posMaster.posMasterCreatedAt", "ASC")
        .getMany();
    }

    // รวบรวม Profile IDs สำหรับ child3
    const child3ProfileIds =
      child3PosMasters.length > 0
        ? [
            ...new Set([
              ...child3PosMasters.map((pm: any) => pm.current_holderId).filter(Boolean),
              ...child3PosMasters.map((pm: any) => pm.next_holderId).filter(Boolean),
            ]),
          ]
        : [];

    // ดึงข้อมูล Profiles, Education, Salary, Positions สำหรับ child3
    let child3Profiles: any[] = [];
    let child3Educations: any[] = [];
    let child3Salaries: any[] = [];
    let child3Positions: any[] = [];

    if (child3ProfileIds.length > 0) {
      [child3Profiles, child3Educations, child3Salaries] = await Promise.all([
        this.profileRepository
          .createQueryBuilder("profile")
          .select([
            "profile.id",
            "profile.prefix",
            "profile.firstName",
            "profile.lastName",
            "profile.position",
            "profile.posTypeId",
            "profile.posLevelId",
          ])
          .where("profile.id IN (:...child3ProfileIds)", { child3ProfileIds })
          .getMany(),

        this.profileEducationRepository
          .createQueryBuilder("pe")
          .select(["pe.profileId", "pe.finishDate", "pe.degree", "pe.level", "pe.isDeleted"])
          .where("pe.profileId IN (:...child3ProfileIds)", { child3ProfileIds })
          .andWhere("pe.isDeleted = :isDeleted", { isDeleted: false })
          .andWhere(
            `(pe.profileId, COALESCE(pe.finishDate, '1900-01-01'), pe.level) IN (
            SELECT pe2.profileId, 
                   COALESCE(MAX(pe2.finishDate), '1900-01-01'),
                   CASE 
                     WHEN MAX(pe2.finishDate) IS NOT NULL THEN 
                       (SELECT pe3.level FROM profileEducation pe3 
                        WHERE pe3.profileId = pe2.profileId 
                        AND pe3.finishDate = MAX(pe2.finishDate) LIMIT 1)
                     ELSE MIN(pe2.level)
                   END
            FROM profileEducation pe2 
            WHERE pe2.profileId IN (:...child3ProfileIds)
            GROUP BY pe2.profileId
          )`,
            { child3ProfileIds },
          )
          .getMany(),

        this.profileSalaryRepository
          .createQueryBuilder("ps")
          .select([
            "ps.profileId",
            "ps.commandDateAffect",
            "ps.amount",
            "ps.positionSalaryAmount",
            "ps.mouthSalaryAmount",
          ])
          .where("ps.profileId IN (:...child3ProfileIds)", { child3ProfileIds })
          .andWhere(
            `(ps.profileId, ps.commandDateAffect) IN (
            SELECT ps2.profileId, MAX(ps2.commandDateAffect) 
            FROM profileSalary ps2 
            WHERE ps2.profileId IN (:...child3ProfileIds)
            GROUP BY ps2.profileId
          )`,
            { child3ProfileIds },
          )
          .getMany(),
      ]);
    }
    console.log("2");

    if (child3PosMasters.length > 0) {
      const child3PosMasterIds = child3PosMasters.map((pm: any) => pm.id);
      child3Positions = await this.positionRepository
        .createQueryBuilder("position")
        .leftJoinAndSelect("position.posType", "posType")
        .leftJoinAndSelect("position.posLevel", "posLevel")
        .leftJoinAndSelect("position.posExecutive", "posExecutive")
        .select([
          "position.id",
          "position.positionName",
          "position.positionIsSelected",
          "position.posMasterId",
          "posType.id",
          "posType.posTypeName",
          "posLevel.id",
          "posLevel.posLevelName",
          "posExecutive.id",
          "posExecutive.posExecutiveName",
        ])
        .where("position.posMasterId IN (:...child3PosMasterIds)", { child3PosMasterIds })
        .getMany();
    }

    // Combine ข้อมูล orgChild3
    for (let orgChild3 of orgChild3Data) {
      orgChild3.posMasters = child3PosMasters.filter((pm: any) => pm.orgChild3Id === orgChild3.id);

      for (let posMaster of orgChild3.posMasters) {
        if (posMaster.current_holderId) {
          posMaster.current_holder = child3Profiles.find(
            (p: any) => p.id === posMaster.current_holderId,
          );
          if (posMaster.current_holder) {
            posMaster.current_holder.profileEducations = child3Educations.filter(
              (ed: any) => ed.profileId === posMaster.current_holderId,
            );
            posMaster.current_holder.profileSalary = child3Salaries.filter(
              (sal: any) => sal.profileId === posMaster.current_holderId,
            );
          }
        }

        if (posMaster.next_holderId) {
          posMaster.next_holder = child3Profiles.find((p: any) => p.id === posMaster.next_holderId);
          if (posMaster.next_holder) {
            posMaster.next_holder.profileEducations = child3Educations.filter(
              (ed: any) => ed.profileId === posMaster.next_holderId,
            );
            posMaster.next_holder.profileSalary = child3Salaries.filter(
              (sal: any) => sal.profileId === posMaster.next_holderId,
            );
          }
        }

        posMaster.positions = child3Positions.filter(
          (pos: any) => pos.posMasterId === posMaster.id,
        );
      }
    }

    // Step 11: ปรับปรุง orgChild4Data
    const originalOrgChild3Ids =
      orgChild3Data.length > 0 ? orgChild3Data.map((orgChild3) => orgChild3.id) : [];
    const orgChild4Data = await this.child4Repository
      .createQueryBuilder("orgChild4")
      .select([
        "orgChild4.id",
        "orgChild4.orgChild3Id",
        "orgChild4.orgChild4Name",
        "orgChild4.orgChild4ShortName",
        "orgChild4.orgChild4Order",
      ])
      .where(
        originalOrgChild3Ids.length > 0
          ? "orgChild4.orgChild3Id IN (:...originalOrgChild3Ids)"
          : "1=0",
        {
          originalOrgChild3Ids,
        },
      )
      .orderBy("orgChild4.orgChild4Order", "ASC")
      .getMany();

    // ดึงข้อมูล PosMasters สำหรับ orgChild4
    const orgChild4Ids = orgChild4Data.map((orgChild4) => orgChild4.id);
    let child4PosMasters: any[] = [];
    if (orgChild4Ids.length > 0) {
      child4PosMasters = await this.posMasterRepository
        .createQueryBuilder("posMaster")
        .select([
          "posMaster.id",
          "posMaster.posMasterOrder",
          "posMaster.isSit",
          "posMaster.posMasterNo",
          "posMaster.ancestorDNA",
          "posMaster.reason",
          "posMaster.orgChild3Id",
          "posMaster.orgChild4Id",
          "posMaster.current_holderId",
          "posMaster.next_holderId",
        ])
        .where("posMaster.orgChild4Id IN (:...orgChild4Ids)", { orgChild4Ids })
        .orderBy("posMaster.posMasterOrder", "ASC")
        .addOrderBy("posMaster.posMasterCreatedAt", "ASC")
        .getMany();
    }

    // รวบรวม Profile IDs สำหรับ child4
    const child4ProfileIds =
      child4PosMasters.length > 0
        ? [
            ...new Set([
              ...child4PosMasters.map((pm: any) => pm.current_holderId).filter(Boolean),
              ...child4PosMasters.map((pm: any) => pm.next_holderId).filter(Boolean),
            ]),
          ]
        : [];

    // ดึงข้อมูล Profiles, Education, Salary, Positions สำหรับ child4
    let child4Profiles: any[] = [];
    let child4Educations: any[] = [];
    let child4Salaries: any[] = [];
    let child4Positions: any[] = [];

    if (child4ProfileIds.length > 0) {
      [child4Profiles, child4Educations, child4Salaries] = await Promise.all([
        this.profileRepository
          .createQueryBuilder("profile")
          .select([
            "profile.id",
            "profile.prefix",
            "profile.firstName",
            "profile.lastName",
            "profile.position",
            "profile.posTypeId",
            "profile.posLevelId",
          ])
          .where("profile.id IN (:...child4ProfileIds)", { child4ProfileIds })
          .getMany(),

        this.profileEducationRepository
          .createQueryBuilder("pe")
          .select(["pe.profileId", "pe.finishDate", "pe.degree", "pe.level", "pe.isDeleted"])
          .where("pe.profileId IN (:...child4ProfileIds)", { child4ProfileIds })
          .andWhere("pe.isDeleted = :isDeleted", { isDeleted: false })
          .andWhere(
            `(pe.profileId, COALESCE(pe.finishDate, '1900-01-01'), pe.level) IN (
            SELECT pe2.profileId, 
                   COALESCE(MAX(pe2.finishDate), '1900-01-01'),
                   CASE 
                     WHEN MAX(pe2.finishDate) IS NOT NULL THEN 
                       (SELECT pe3.level FROM profileEducation pe3 
                        WHERE pe3.profileId = pe2.profileId 
                        AND pe3.finishDate = MAX(pe2.finishDate) LIMIT 1)
                     ELSE MIN(pe2.level)
                   END
            FROM profileEducation pe2 
            WHERE pe2.profileId IN (:...child4ProfileIds)
            GROUP BY pe2.profileId
          )`,
            { child4ProfileIds },
          )
          .getMany(),

        this.profileSalaryRepository
          .createQueryBuilder("ps")
          .select([
            "ps.profileId",
            "ps.commandDateAffect",
            "ps.amount",
            "ps.positionSalaryAmount",
            "ps.mouthSalaryAmount",
          ])
          .where("ps.profileId IN (:...child4ProfileIds)", { child4ProfileIds })
          .andWhere(
            `(ps.profileId, ps.commandDateAffect) IN (
            SELECT ps2.profileId, MAX(ps2.commandDateAffect) 
            FROM profileSalary ps2 
            WHERE ps2.profileId IN (:...child4ProfileIds)
            GROUP BY ps2.profileId
          )`,
            { child4ProfileIds },
          )
          .getMany(),
      ]);
    }

    if (child4PosMasters.length > 0) {
      const child4PosMasterIds = child4PosMasters.map((pm: any) => pm.id);
      child4Positions = await this.positionRepository
        .createQueryBuilder("position")
        .leftJoinAndSelect("position.posType", "posType")
        .leftJoinAndSelect("position.posLevel", "posLevel")
        .leftJoinAndSelect("position.posExecutive", "posExecutive")
        .select([
          "position.id",
          "position.positionName",
          "position.positionIsSelected",
          "position.posMasterId",
          "posType.id",
          "posType.posTypeName",
          "posLevel.id",
          "posLevel.posLevelName",
          "posExecutive.id",
          "posExecutive.posExecutiveName",
        ])
        .where("position.posMasterId IN (:...child4PosMasterIds)", { child4PosMasterIds })
        .getMany();
    }

    // Combine ข้อมูล orgChild4
    for (let orgChild4 of orgChild4Data) {
      orgChild4.posMasters = child4PosMasters.filter((pm: any) => pm.orgChild4Id === orgChild4.id);

      for (let posMaster of orgChild4.posMasters) {
        if (posMaster.current_holderId) {
          posMaster.current_holder = child4Profiles.find(
            (p: any) => p.id === posMaster.current_holderId,
          );
          if (posMaster.current_holder) {
            posMaster.current_holder.profileEducations = child4Educations.filter(
              (ed: any) => ed.profileId === posMaster.current_holderId,
            );
            posMaster.current_holder.profileSalary = child4Salaries.filter(
              (sal: any) => sal.profileId === posMaster.current_holderId,
            );
          }
        }

        if (posMaster.next_holderId) {
          posMaster.next_holder = child4Profiles.find((p: any) => p.id === posMaster.next_holderId);
          if (posMaster.next_holder) {
            posMaster.next_holder.profileEducations = child4Educations.filter(
              (ed: any) => ed.profileId === posMaster.next_holderId,
            );
            posMaster.next_holder.profileSalary = child4Salaries.filter(
              (sal: any) => sal.profileId === posMaster.next_holderId,
            );
          }
        }

        posMaster.positions = child4Positions.filter(
          (pos: any) => pos.posMasterId === posMaster.id,
        );
      }
    }

    let orgRevisionActive: any = await this.orgRevisionRepository.findOne({
      where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false },
      relations: [
        "posMasters",
        "posMasters.positions",
        "posMasters.positions.posLevel",
        "posMasters.positions.posType",
        "posMasters.positions.posExecutive",
      ],
    });
    if (orgRevisionActive == null) {
      const _orgRevisionActive = await this.orgRevisionRepository.find({
        order: { createdAt: "DESC" },
        skip: 1,
        relations: [
          "posMasters",
          "posMasters.positions",
          "posMasters.positions.posLevel",
          "posMasters.positions.posType",
          "posMasters.positions.posExecutive",
        ],
      });
      if (_orgRevisionActive.length > 0) orgRevisionActive = _orgRevisionActive[0];
    }

    let data = new Array();
    let _node: any;
    let no = 1;
    for (let orgRoot of orgRootData) {
      await Promise.all(
        orgRoot.posMasters
          .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
          .map(async (posMaster) => {
            if (posMaster.orgChild1Id == null && posMaster.next_holder != null) {
              let education: any = "";
              if (
                posMaster.next_holder != null &&
                posMaster.next_holder.profileEducations != null &&
                posMaster.next_holder.profileEducations.length > 0
              ) {
                let _education: any = posMaster.next_holder.profileEducations.sort(
                  (a, b) =>
                    (b.finishDate == null ? 0 : b.finishDate.getTime()) -
                    (a.finishDate == null ? 0 : a.finishDate.getTime()),
                );
                if (_education.length > 0) {
                  education = _education[0];
                }
              }
              let salary: any = "";
              if (
                posMaster.next_holder != null &&
                posMaster.next_holder.profileSalary != null &&
                posMaster.next_holder.profileSalary.length > 0
              ) {
                let _salary: any = posMaster.next_holder.profileSalary.sort(
                  (a, b) =>
                    (b.commandDateAffect == null ? 0 : b.commandDateAffect.getTime()) -
                    (a.commandDateAffect == null ? 0 : a.commandDateAffect.getTime()),
                );
                if (_salary.length > 0) {
                  salary = _salary[0];
                }
              }

              let node = {
                orgTreeName: orgRoot.orgRootName,
                orgTreeShortName: orgRoot.orgRootShortName,
                posMasterNo: posMaster.posMasterNo,
                positionName:
                  posMaster.isSit == false
                    ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                        ?.positionName
                    : posMaster.next_holder.position,
                posType:
                  posMaster.isSit == false
                    ? posMaster.positions.find((x: any) => x.positionIsSelected == true)?.posType
                        ?.posTypeName
                    : "-",
                posLevel:
                  posMaster.isSit == false
                    ? posMaster.positions.find((x: any) => x.positionIsSelected == true)?.posLevel
                        ?.posLevelName
                    : "-",
                posExecutive:
                  posMaster.isSit == false
                    ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                        ?.posExecutive?.posExecutiveName
                    : "-",

                profileFullname: `${posMaster.next_holder.prefix}${posMaster.next_holder.firstName} ${posMaster.next_holder.lastName}`,
                education: education == "" ? "" : education.degree,
                salary: salary == "" ? "" : salary.amount,
                positionSalaryAmount: salary == "" ? "" : salary.positionSalaryAmount,
                mouthSalaryAmount: salary == "" ? "" : salary.mouthSalaryAmount,
                reason: posMaster.reason == null ? "" : posMaster.reason,
              };
              if (_node == null) {
                const head = {
                  posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName.toString()),
                  profileFullname: "",
                  posExecutive: Extension.ToThaiNumber(node.orgTreeName.toString()),
                  positionName: "",
                  posType: "",
                  posLevel: "",
                  education: "",
                  salary: "",
                  positionSalaryAmount: "",
                  mouthSalaryAmount: "",
                  reason: "",
                };
                data.push(head);
                const _head = {
                  no: Extension.ToThaiNumber(no.toString()),
                  posMasterNo:
                    node.posMasterNo == null
                      ? ""
                      : Extension.ToThaiNumber(node.posMasterNo.toString()),
                  profileFullname:
                    node.profileFullname == null
                      ? ""
                      : Extension.ToThaiNumber(node.profileFullname.toString()),
                  posExecutive: node.posExecutive == undefined ? "" : node.posExecutive,
                  positionName:
                    node.positionName == null
                      ? ""
                      : Extension.ToThaiNumber(node.positionName.toString()),
                  posType:
                    node.posType == null ? "" : Extension.ToThaiNumber(node.posType.toString()),
                  posLevel:
                    node.posLevel == null ? "" : Extension.ToThaiNumber(node.posLevel.toString()),
                  education:
                    node.education == null ? "" : Extension.ToThaiNumber(node.education.toString()),
                  salary: node.salary ? Extension.ToThaiNumber(node.salary.toLocaleString()) : "",
                  positionSalaryAmount: node.positionSalaryAmount
                    ? Extension.ToThaiNumber(node.positionSalaryAmount.toLocaleString())
                    : "",
                  mouthSalaryAmount: node.mouthSalaryAmount
                    ? Extension.ToThaiNumber(node.mouthSalaryAmount.toLocaleString())
                    : "",
                  reason: node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
                };
                data.push(_head);
              } else {
                if (
                  node.orgTreeShortName != _node.orgTreeShortName ||
                  node.orgTreeName != _node.orgTreeName
                ) {
                  const head = {
                    posMasterNo:
                      node.orgTreeShortName == _node.orgTreeShortName ? "" : node.orgTreeShortName,
                    profileFullname: "",
                    posExecutive: node.orgTreeName == _node.orgTreeName ? "" : node.orgTreeName,
                    positionName: "",
                    posType: "",
                    posLevel: "",
                    education: "",
                    salary: "",
                    positionSalaryAmount: "",
                    mouthSalaryAmount: "",
                    reason: "",
                  };
                  data.push(head);
                  _node == null;
                }
                const head = {
                  no: Extension.ToThaiNumber(no.toString()),
                  posMasterNo:
                    node.posMasterNo == null
                      ? ""
                      : Extension.ToThaiNumber(node.posMasterNo.toString()),
                  profileFullname:
                    node.profileFullname == null
                      ? ""
                      : Extension.ToThaiNumber(node.profileFullname.toString()),
                  posExecutive: node.posExecutive == _node.posExecutive ? "" : node.posExecutive,
                  positionName:
                    node.positionName == null
                      ? ""
                      : Extension.ToThaiNumber(node.positionName.toString()),
                  posType:
                    node.posType == null ? "" : Extension.ToThaiNumber(node.posType.toString()),
                  posLevel:
                    node.posLevel == null ? "" : Extension.ToThaiNumber(node.posLevel.toString()),
                  education:
                    node.education == null ? "" : Extension.ToThaiNumber(node.education.toString()),
                  salary: node.salary ? Extension.ToThaiNumber(node.salary.toLocaleString()) : "",
                  positionSalaryAmount: node.positionSalaryAmount
                    ? Extension.ToThaiNumber(node.positionSalaryAmount.toLocaleString())
                    : "",
                  mouthSalaryAmount: node.mouthSalaryAmount
                    ? Extension.ToThaiNumber(node.mouthSalaryAmount.toLocaleString())
                    : "",
                  reason: node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
                };
                data.push(head);
              }
              no += 1;
              _node = node;
            }
          }),
      );
      _node = null;

      console.log("13");
      for (let orgChild1 of orgChild1Data.filter(
        (orgChild1) => orgChild1.orgRootId === orgRoot.id,
      )) {
        await Promise.all(
          orgChild1.posMasters
            .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
            .map(async (posMaster) => {
              if (posMaster.orgChild2Id == null && posMaster.next_holder != null) {
                let education: any = "";
                if (
                  posMaster.next_holder != null &&
                  posMaster.next_holder.profileEducations != null &&
                  posMaster.next_holder.profileEducations.length > 0
                ) {
                  let _education: any = posMaster.next_holder.profileEducations.sort(
                    (a, b) =>
                      (b.finishDate == null ? 0 : b.finishDate.getTime()) -
                      (a.finishDate == null ? 0 : a.finishDate.getTime()),
                  );
                  if (_education.length > 0) {
                    education = _education[0];
                  }
                }
                let salary: any = "";
                if (
                  posMaster.next_holder != null &&
                  posMaster.next_holder.profileSalary != null &&
                  posMaster.next_holder.profileSalary.length > 0
                ) {
                  let _salary: any = posMaster.next_holder.profileSalary.sort(
                    (a, b) =>
                      (b.commandDateAffect == null ? 0 : b.commandDateAffect.getTime()) -
                      (a.commandDateAffect == null ? 0 : a.commandDateAffect.getTime()),
                  );
                  if (_salary.length > 0) {
                    salary = _salary[0];
                  }
                }

                console.log("14");
                let node = {
                  orgTreeName: orgChild1.orgChild1Name,
                  orgTreeShortName: orgChild1.orgChild1ShortName,
                  posMasterNo: posMaster.posMasterNo,
                  positionName:
                    posMaster.isSit == false
                      ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                          ?.positionName
                      : posMaster.next_holder.position,
                  posType:
                    posMaster.isSit == false
                      ? posMaster.positions.find((x: any) => x.positionIsSelected == true)?.posType
                          ?.posTypeName
                      : "-",
                  posLevel:
                    posMaster.isSit == false
                      ? posMaster.positions.find((x: any) => x.positionIsSelected == true)?.posLevel
                          ?.posLevelName
                      : "-",
                  posExecutive:
                    posMaster.isSit == false
                      ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                          ?.posExecutive?.posExecutiveName
                      : "-",

                  profileFullname: `${posMaster.next_holder.prefix}${posMaster.next_holder.firstName} ${posMaster.next_holder.lastName}`,
                  education: education == "" ? "" : education.degree,
                  salary: salary == "" ? "" : salary.amount,
                  positionSalaryAmount: salary == "" ? "" : salary.positionSalaryAmount,
                  mouthSalaryAmount: salary == "" ? "" : salary.mouthSalaryAmount,
                  reason: posMaster.reason == null ? "" : posMaster.reason,
                };
                if (_node == null) {
                  const head = {
                    posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName.toString()),
                    profileFullname: "",
                    posExecutive: Extension.ToThaiNumber(node.orgTreeName.toString()),
                    positionName: "",
                    posType: "",
                    posLevel: "",
                    education: "",
                    salary: "",
                    positionSalaryAmount: "",
                    mouthSalaryAmount: "",
                    reason: "",
                  };
                  data.push(head);
                  const _head = {
                    no: Extension.ToThaiNumber(no.toString()),
                    posMasterNo:
                      node.posMasterNo == null
                        ? ""
                        : Extension.ToThaiNumber(node.posMasterNo.toString()),
                    profileFullname:
                      node.profileFullname == null
                        ? ""
                        : Extension.ToThaiNumber(node.profileFullname.toString()),
                    posExecutive: node.posExecutive,
                    positionName:
                      node.positionName == null
                        ? ""
                        : Extension.ToThaiNumber(node.positionName.toString()),
                    posType:
                      node.posType == null ? "" : Extension.ToThaiNumber(node.posType.toString()),
                    posLevel:
                      node.posLevel == null ? "" : Extension.ToThaiNumber(node.posLevel.toString()),
                    education:
                      node.education == null
                        ? ""
                        : Extension.ToThaiNumber(node.education.toString()),
                    salary: node.salary ? Extension.ToThaiNumber(node.salary.toLocaleString()) : "",
                    positionSalaryAmount: node.positionSalaryAmount
                      ? Extension.ToThaiNumber(node.positionSalaryAmount.toLocaleString())
                      : "",
                    mouthSalaryAmount: node.mouthSalaryAmount
                      ? Extension.ToThaiNumber(node.mouthSalaryAmount.toLocaleString())
                      : "",
                    reason:
                      node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
                  };
                  data.push(_head);
                } else {
                  if (
                    node.orgTreeShortName != _node.orgTreeShortName ||
                    node.orgTreeName != _node.orgTreeName
                  ) {
                    const head = {
                      posMasterNo:
                        node.orgTreeShortName == _node.orgTreeShortName
                          ? ""
                          : node.orgTreeShortName,
                      profileFullname: "",
                      posExecutive: node.orgTreeName == _node.orgTreeName ? "" : node.orgTreeName,
                      positionName: "",
                      posType: "",
                      posLevel: "",
                      education: "",
                      salary: "",
                      positionSalaryAmount: "",
                      mouthSalaryAmount: "",
                      reason: "",
                    };
                    data.push(head);
                    _node == null;
                  }
                  const head = {
                    no: Extension.ToThaiNumber(no.toString()),
                    posMasterNo:
                      node.posMasterNo == null
                        ? ""
                        : Extension.ToThaiNumber(node.posMasterNo.toString()),
                    profileFullname:
                      node.profileFullname == null
                        ? ""
                        : Extension.ToThaiNumber(node.profileFullname.toString()),
                    posExecutive: node.posExecutive == _node.posExecutive ? "" : node.posExecutive,
                    positionName:
                      node.positionName == null
                        ? ""
                        : Extension.ToThaiNumber(node.positionName.toString()),
                    posType:
                      node.posType == null ? "" : Extension.ToThaiNumber(node.posType.toString()),
                    posLevel:
                      node.posLevel == null ? "" : Extension.ToThaiNumber(node.posLevel.toString()),
                    education:
                      node.education == null
                        ? ""
                        : Extension.ToThaiNumber(node.education.toString()),
                    salary: node.salary ? Extension.ToThaiNumber(node.salary.toLocaleString()) : "",
                    positionSalaryAmount: node.positionSalaryAmount
                      ? Extension.ToThaiNumber(node.positionSalaryAmount.toLocaleString())
                      : "",
                    mouthSalaryAmount: node.mouthSalaryAmount
                      ? Extension.ToThaiNumber(node.mouthSalaryAmount.toLocaleString())
                      : "",
                    reason:
                      node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
                  };
                  data.push(head);
                }
                no += 1;
                _node = node;
              }
            }),
        );
        _node = null;

        console.log("15");
        for (let orgChild2 of orgChild2Data.filter(
          (orgChild2) => orgChild2.orgChild1Id === orgChild1.id,
        )) {
          console.log("111");
          await Promise.all(
            orgChild2.posMasters
              .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
              .map(async (posMaster) => {
                console.log("112");
                if (posMaster.orgChild3Id == null && posMaster.next_holder != null) {
                  console.log("114");
                  let education: any = "";
                  if (
                    posMaster.next_holder != null &&
                    posMaster.next_holder.profileEducations != null &&
                    posMaster.next_holder.profileEducations.length > 0
                  ) {
                    let _education: any = posMaster.next_holder.profileEducations.sort(
                      (a, b) =>
                        (b.finishDate == null ? 0 : b.finishDate.getTime()) -
                        (a.finishDate == null ? 0 : a.finishDate.getTime()),
                    );
                    if (_education.length > 0) {
                      education = _education[0];
                    }
                  }
                  console.log("115");
                  let salary: any = "";
                  if (
                    posMaster.next_holder != null &&
                    posMaster.next_holder.profileSalary != null &&
                    posMaster.next_holder.profileSalary.length > 0
                  ) {
                    let _salary: any = posMaster.next_holder.profileSalary.sort(
                      (a, b) =>
                        (b.commandDateAffect == null ? 0 : b.commandDateAffect.getTime()) -
                        (a.commandDateAffect == null ? 0 : a.commandDateAffect.getTime()),
                    );
                    if (_salary.length > 0) {
                      salary = _salary[0];
                    }
                  }
                  console.log("116");

                  let node = {
                    orgTreeName: orgChild2.orgChild2Name,
                    orgTreeShortName: orgChild2.orgChild2ShortName,
                    posMasterNo: posMaster.posMasterNo,
                    positionName:
                      posMaster.isSit == false
                        ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                            ?.positionName
                        : posMaster.next_holder.position,
                    posType:
                      posMaster.isSit == false
                        ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                            ?.posType?.posTypeName
                        : "-",
                    posLevel:
                      posMaster.isSit == false
                        ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                            ?.posLevel?.posLevelName
                        : "-",
                    posExecutive:
                      posMaster.isSit == false
                        ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                            ?.posExecutive?.posExecutiveName
                        : "-",
                    profileFullname: `${posMaster.next_holder.prefix}${posMaster.next_holder.firstName} ${posMaster.next_holder.lastName}`,
                    education: education == "" ? "" : education.degree,
                    salary: salary == "" ? "" : salary.amount,
                    positionSalaryAmount: salary == "" ? "" : salary.positionSalaryAmount,
                    mouthSalaryAmount: salary == "" ? "" : salary.mouthSalaryAmount,
                    reason: posMaster.reason == null ? "" : posMaster.reason,
                  };
                  if (_node == null) {
                    const head = {
                      posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName.toString()),
                      profileFullname: "",
                      posExecutive: Extension.ToThaiNumber(node.orgTreeName.toString()),
                      positionName: "",
                      posType: "",
                      posLevel: "",
                      education: "",
                      salary: "",
                      positionSalaryAmount: "",
                      mouthSalaryAmount: "",
                      reason: "",
                    };
                    data.push(head);
                    const _head = {
                      no: Extension.ToThaiNumber(no.toString()),
                      posMasterNo:
                        node.posMasterNo == null
                          ? ""
                          : Extension.ToThaiNumber(node.posMasterNo.toString()),
                      profileFullname:
                        node.profileFullname == null
                          ? ""
                          : Extension.ToThaiNumber(node.profileFullname.toString()),
                      posExecutive: node.posExecutive,
                      positionName:
                        node.positionName == null
                          ? ""
                          : Extension.ToThaiNumber(node.positionName.toString()),
                      posType:
                        node.posType == null ? "" : Extension.ToThaiNumber(node.posType.toString()),
                      posLevel:
                        node.posLevel == null
                          ? ""
                          : Extension.ToThaiNumber(node.posLevel.toString()),
                      education:
                        node.education == null
                          ? ""
                          : Extension.ToThaiNumber(node.education.toString()),
                      salary: node.salary
                        ? Extension.ToThaiNumber(node.salary.toLocaleString())
                        : "",
                      positionSalaryAmount: node.positionSalaryAmount
                        ? Extension.ToThaiNumber(node.positionSalaryAmount.toLocaleString())
                        : "",
                      mouthSalaryAmount: node.mouthSalaryAmount
                        ? Extension.ToThaiNumber(node.mouthSalaryAmount.toLocaleString())
                        : "",
                      reason:
                        node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
                    };
                    data.push(_head);
                  } else {
                    if (
                      node.orgTreeShortName != _node.orgTreeShortName ||
                      node.orgTreeName != _node.orgTreeName
                    ) {
                      const head = {
                        posMasterNo:
                          node.orgTreeShortName == _node.orgTreeShortName
                            ? ""
                            : node.orgTreeShortName,
                        profileFullname: "",
                        posExecutive: node.orgTreeName == _node.orgTreeName ? "" : node.orgTreeName,
                        positionName: "",
                        posType: "",
                        posLevel: "",
                        education: "",
                        salary: "",
                        positionSalaryAmount: "",
                        mouthSalaryAmount: "",
                        reason: "",
                      };
                      data.push(head);
                      _node == null;
                    }
                    const head = {
                      no: Extension.ToThaiNumber(no.toString()),
                      posMasterNo:
                        node.posMasterNo == null
                          ? ""
                          : Extension.ToThaiNumber(node.posMasterNo.toString()),
                      profileFullname:
                        node.profileFullname == null
                          ? ""
                          : Extension.ToThaiNumber(node.profileFullname.toString()),
                      posExecutive:
                        node.posExecutive == _node.posExecutive ? "" : node.posExecutive,
                      positionName:
                        node.positionName == null
                          ? ""
                          : Extension.ToThaiNumber(node.positionName.toString()),
                      posType:
                        node.posType == null ? "" : Extension.ToThaiNumber(node.posType.toString()),
                      posLevel:
                        node.posLevel == null
                          ? ""
                          : Extension.ToThaiNumber(node.posLevel.toString()),
                      education:
                        node.education == null
                          ? ""
                          : Extension.ToThaiNumber(node.education.toString()),
                      salary: node.salary
                        ? Extension.ToThaiNumber(node.salary.toLocaleString())
                        : "",
                      positionSalaryAmount: node.positionSalaryAmount
                        ? Extension.ToThaiNumber(node.positionSalaryAmount.toLocaleString())
                        : "",
                      mouthSalaryAmount: node.mouthSalaryAmount
                        ? Extension.ToThaiNumber(node.mouthSalaryAmount.toLocaleString())
                        : "",
                      reason:
                        node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
                    };
                    data.push(head);
                  }
                  no += 1;
                  _node = node;
                }
              }),
          );
          _node = null;

          console.log("16");
          for (let orgChild3 of orgChild3Data.filter(
            (orgChild3) => orgChild3.orgChild2Id === orgChild2.id,
          )) {
            await Promise.all(
              orgChild3.posMasters
                .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
                .map(async (posMaster) => {
                  if (posMaster.orgChild4Id == null && posMaster.next_holder != null) {
                    let education: any = "";
                    if (
                      posMaster.next_holder != null &&
                      posMaster.next_holder.profileEducations != null &&
                      posMaster.next_holder.profileEducations.length > 0
                    ) {
                      let _education: any = posMaster.next_holder.profileEducations.sort(
                        (a, b) =>
                          (b.finishDate == null ? 0 : b.finishDate.getTime()) -
                          (a.finishDate == null ? 0 : a.finishDate.getTime()),
                      );
                      if (_education.length > 0) {
                        education = _education[0];
                      }
                    }
                    let salary: any = "";
                    if (
                      posMaster.next_holder != null &&
                      posMaster.next_holder.profileSalary != null &&
                      posMaster.next_holder.profileSalary.length > 0
                    ) {
                      let _salary: any = posMaster.next_holder.profileSalary.sort(
                        (a, b) =>
                          (b.commandDateAffect == null ? 0 : b.commandDateAffect.getTime()) -
                          (a.commandDateAffect == null ? 0 : a.commandDateAffect.getTime()),
                      );
                      if (_salary.length > 0) {
                        salary = _salary[0];
                      }
                    }

                    let node = {
                      orgTreeName: orgChild3.orgChild3Name,
                      orgTreeShortName: orgChild3.orgChild3ShortName,
                      posMasterNo: posMaster.posMasterNo,
                      positionName:
                        posMaster.isSit == false
                          ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                              ?.positionName
                          : posMaster.next_holder.position,
                      posType:
                        posMaster.isSit == false
                          ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                              ?.posType?.posTypeName
                          : "-",
                      posLevel:
                        posMaster.isSit == false
                          ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                              ?.posLevel?.posLevelName
                          : "-",
                      posExecutive:
                        posMaster.isSit == false
                          ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                              ?.posExecutive?.posExecutiveName
                          : "-",
                      profileFullname: `${posMaster.next_holder.prefix}${posMaster.next_holder.firstName} ${posMaster.next_holder.lastName}`,
                      education: education == "" ? "" : education.degree,
                      salary: salary == "" ? "" : salary.amount,
                      positionSalaryAmount: salary == "" ? "" : salary.positionSalaryAmount,
                      mouthSalaryAmount: salary == "" ? "" : salary.mouthSalaryAmount,
                      reason: posMaster.reason == null ? "" : posMaster.reason,
                    };
                    if (_node == null) {
                      const head = {
                        posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName.toString()),
                        profileFullname: "",
                        posExecutive: Extension.ToThaiNumber(node.orgTreeName.toString()),
                        positionName: "",
                        posType: "",
                        posLevel: "",
                        education: "",
                        salary: "",
                        positionSalaryAmount: "",
                        mouthSalaryAmount: "",
                        reason: "",
                      };
                      data.push(head);
                      const _head = {
                        no: Extension.ToThaiNumber(no.toString()),
                        posMasterNo:
                          node.posMasterNo == null
                            ? ""
                            : Extension.ToThaiNumber(node.posMasterNo.toString()),
                        profileFullname:
                          node.profileFullname == null
                            ? ""
                            : Extension.ToThaiNumber(node.profileFullname.toString()),
                        posExecutive: node.posExecutive,
                        positionName:
                          node.positionName == null
                            ? ""
                            : Extension.ToThaiNumber(node.positionName.toString()),
                        posType:
                          node.posType == null
                            ? ""
                            : Extension.ToThaiNumber(node.posType.toString()),
                        posLevel:
                          node.posLevel == null
                            ? ""
                            : Extension.ToThaiNumber(node.posLevel.toString()),
                        education:
                          node.education == null
                            ? ""
                            : Extension.ToThaiNumber(node.education.toString()),
                        salary: node.salary
                          ? Extension.ToThaiNumber(node.salary.toLocaleString())
                          : "",
                        positionSalaryAmount: node.positionSalaryAmount
                          ? Extension.ToThaiNumber(node.positionSalaryAmount.toLocaleString())
                          : "",
                        mouthSalaryAmount: node.mouthSalaryAmount
                          ? Extension.ToThaiNumber(node.mouthSalaryAmount.toLocaleString())
                          : "",
                        reason:
                          node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
                      };
                      data.push(_head);
                    } else {
                      if (
                        node.orgTreeShortName != _node.orgTreeShortName ||
                        node.orgTreeName != _node.orgTreeName
                      ) {
                        const head = {
                          posMasterNo:
                            node.orgTreeShortName == _node.orgTreeShortName
                              ? ""
                              : node.orgTreeShortName,
                          profileFullname: "",
                          posExecutive:
                            node.orgTreeName == _node.orgTreeName ? "" : node.orgTreeName,
                          positionName: "",
                          posType: "",
                          posLevel: "",
                          education: "",
                          salary: "",
                          positionSalaryAmount: "",
                          mouthSalaryAmount: "",
                          reason: "",
                        };
                        data.push(head);
                        _node == null;
                      }
                      const head = {
                        no: Extension.ToThaiNumber(no.toString()),
                        posMasterNo:
                          node.posMasterNo == null
                            ? ""
                            : Extension.ToThaiNumber(node.posMasterNo.toString()),
                        profileFullname:
                          node.profileFullname == null
                            ? ""
                            : Extension.ToThaiNumber(node.profileFullname.toString()),
                        posExecutive:
                          node.posExecutive == _node.posExecutive ? "" : node.posExecutive,
                        positionName:
                          node.positionName == null
                            ? ""
                            : Extension.ToThaiNumber(node.positionName.toString()),
                        posType:
                          node.posType == null
                            ? ""
                            : Extension.ToThaiNumber(node.posType.toString()),
                        posLevel:
                          node.posLevel == null
                            ? ""
                            : Extension.ToThaiNumber(node.posLevel.toString()),
                        education:
                          node.education == null
                            ? ""
                            : Extension.ToThaiNumber(node.education.toString()),
                        salary: node.salary
                          ? Extension.ToThaiNumber(node.salary.toLocaleString())
                          : "",
                        positionSalaryAmount: node.positionSalaryAmount
                          ? Extension.ToThaiNumber(node.positionSalaryAmount.toLocaleString())
                          : "",
                        mouthSalaryAmount: node.mouthSalaryAmount
                          ? Extension.ToThaiNumber(node.mouthSalaryAmount.toLocaleString())
                          : "",
                        reason:
                          node.reason == null ? "" : Extension.ToThaiNumber(node.reason.toString()),
                      };
                      data.push(head);
                    }
                    no += 1;
                    _node = node;
                  }
                }),
            );
            _node = null;

            console.log("17");
            for (let orgChild4 of orgChild4Data.filter(
              (orgChild4) => orgChild4.orgChild3Id === orgChild3.id,
            )) {
              await Promise.all(
                orgChild4.posMasters
                  .sort((a, b) => a.posMasterOrder - b.posMasterOrder)
                  .map(async (posMaster) => {
                    if (posMaster.next_holder != null) {
                      let education: any = "";
                      if (
                        posMaster.next_holder != null &&
                        posMaster.next_holder.profileEducations != null &&
                        posMaster.next_holder.profileEducations.length > 0
                      ) {
                        let _education: any = posMaster.next_holder.profileEducations.sort(
                          (a, b) =>
                            b.finishDate == null
                              ? 0
                              : (b.finishDate == null ? 0 : b.finishDate.getTime()) -
                                (a.finishDate == null ? 0 : a.finishDate.getTime()),
                        );
                        if (_education.length > 0) {
                          education = _education[0];
                        }
                      }
                      let salary: any = "";
                      if (
                        posMaster.next_holder != null &&
                        posMaster.next_holder.profileSalary != null &&
                        posMaster.next_holder.profileSalary.length > 0
                      ) {
                        let _salary: any = posMaster.next_holder.profileSalary.sort(
                          (a, b) =>
                            (b.commandDateAffect == null ? 0 : b.commandDateAffect.getTime()) -
                            (a.commandDateAffect == null ? 0 : a.commandDateAffect.getTime()),
                        );
                        if (_salary.length > 0) {
                          salary = _salary[0];
                        }
                      }

                      let node = {
                        orgTreeName: orgChild4.orgChild4Name,
                        orgTreeShortName: orgChild4.orgChild4ShortName,
                        posMasterNo: posMaster.posMasterNo,
                        positionName:
                          posMaster.isSit == false
                            ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                                ?.positionName
                            : posMaster.next_holder.position,
                        posType:
                          posMaster.isSit == false
                            ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                                ?.posType?.posTypeName
                            : "-",
                        posLevel:
                          posMaster.isSit == false
                            ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                                ?.posLevel?.posLevelName
                            : "-",
                        posExecutive:
                          posMaster.isSit == false
                            ? posMaster.positions.find((x: any) => x.positionIsSelected == true)
                                ?.posExecutive?.posExecutiveName
                            : "-",
                        profileFullname: `${posMaster.next_holder.prefix}${posMaster.next_holder.firstName} ${posMaster.next_holder.lastName}`,
                        education: education == "" ? "" : education.degree,
                        salary: salary == "" ? "" : salary.amount,
                        positionSalaryAmount: salary == "" ? "" : salary.positionSalaryAmount,
                        mouthSalaryAmount: salary == "" ? "" : salary.mouthSalaryAmount,
                        reason: posMaster.reason == null ? "" : posMaster.reason,
                      };
                      if (_node == null) {
                        const head = {
                          posMasterNo: Extension.ToThaiNumber(node.orgTreeShortName.toString()),
                          profileFullname: "",
                          posExecutive: Extension.ToThaiNumber(node.orgTreeName.toString()),
                          positionName: "",
                          posType: "",
                          posLevel: "",
                          education: "",
                          salary: "",
                          positionSalaryAmount: "",
                          mouthSalaryAmount: "",
                          reason: "",
                        };
                        data.push(head);
                        const _head = {
                          no: Extension.ToThaiNumber(no.toString()),
                          posMasterNo:
                            node.posMasterNo == null
                              ? ""
                              : Extension.ToThaiNumber(node.posMasterNo.toString()),
                          profileFullname:
                            node.profileFullname == null
                              ? ""
                              : Extension.ToThaiNumber(node.profileFullname.toString()),
                          posExecutive: node.posExecutive,
                          positionName:
                            node.positionName == null
                              ? ""
                              : Extension.ToThaiNumber(node.positionName.toString()),
                          posType:
                            node.posType == null
                              ? ""
                              : Extension.ToThaiNumber(node.posType.toString()),
                          posLevel:
                            node.posLevel == null
                              ? ""
                              : Extension.ToThaiNumber(node.posLevel.toString()),
                          education:
                            node.education == null
                              ? ""
                              : Extension.ToThaiNumber(node.education.toString()),
                          salary: node.salary
                            ? Extension.ToThaiNumber(node.salary.toLocaleString())
                            : "",
                          positionSalaryAmount: node.positionSalaryAmount
                            ? Extension.ToThaiNumber(node.positionSalaryAmount.toLocaleString())
                            : "",
                          mouthSalaryAmount: node.mouthSalaryAmount
                            ? Extension.ToThaiNumber(node.mouthSalaryAmount.toLocaleString())
                            : "",
                          reason:
                            node.reason == null
                              ? ""
                              : Extension.ToThaiNumber(node.reason.toString()),
                        };
                        data.push(_head);
                      } else {
                        if (
                          node.orgTreeShortName != _node.orgTreeShortName ||
                          node.orgTreeName != _node.orgTreeName
                        ) {
                          const head = {
                            posMasterNo:
                              node.orgTreeShortName == _node.orgTreeShortName
                                ? ""
                                : node.orgTreeShortName,
                            profileFullname: "",
                            posExecutive:
                              node.orgTreeName == _node.orgTreeName ? "" : node.orgTreeName,
                            positionName: "",
                            posType: "",
                            posLevel: "",
                            education: "",
                            salary: "",
                            positionSalaryAmount: "",
                            mouthSalaryAmount: "",
                            reason: "",
                          };
                          data.push(head);
                          _node == null;
                        }
                        const head = {
                          no: Extension.ToThaiNumber(no.toString()),
                          posMasterNo:
                            node.posMasterNo == null
                              ? ""
                              : Extension.ToThaiNumber(node.posMasterNo.toString()),
                          profileFullname:
                            node.profileFullname == null
                              ? ""
                              : Extension.ToThaiNumber(node.profileFullname.toString()),
                          posExecutive:
                            node.posExecutive == _node.posExecutive ? "" : node.posExecutive,
                          positionName:
                            node.positionName == null
                              ? ""
                              : Extension.ToThaiNumber(node.positionName.toString()),
                          posType:
                            node.posType == null
                              ? ""
                              : Extension.ToThaiNumber(node.posType.toString()),
                          posLevel:
                            node.posLevel == null
                              ? ""
                              : Extension.ToThaiNumber(node.posLevel.toString()),
                          education:
                            node.education == null
                              ? ""
                              : Extension.ToThaiNumber(node.education.toString()),
                          salary: node.salary
                            ? Extension.ToThaiNumber(node.salary.toLocaleString())
                            : "",
                          positionSalaryAmount: node.positionSalaryAmount
                            ? Extension.ToThaiNumber(node.positionSalaryAmount.toLocaleString())
                            : "",
                          mouthSalaryAmount: node.mouthSalaryAmount
                            ? Extension.ToThaiNumber(node.mouthSalaryAmount.toLocaleString())
                            : "",
                          reason:
                            node.reason == null
                              ? ""
                              : Extension.ToThaiNumber(node.reason.toString()),
                        };
                        data.push(head);
                      }
                      no += 1;
                      _node = node;
                    }
                  }),
              );
              _node = null;
            }
          }
        }
      }
    }
    return new HttpSuccess({
      template: "report3",
      reportName: "report3",
      data: { org: orgName, data },
    });
  }

  @Post("report4")
  async NewReport4(
    @Body()
    reqBody: {
      node: number;
      nodeId: string;
    },
  ) {
    // @Get("report4/{rootId}")
    // async findReport4(@Path() rootId: string) {

    let nodeId: string = reqBody.nodeId ? reqBody.nodeId : "";
    let node: number = reqBody.node ? reqBody.node : 0;
    let rootName: string = "";
    let whereCase: string = "";
    let params: any = {};

    if (nodeId === "" || node < 0 || node > 4) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
    }
    switch (node) {
      case 0: {
        const orgRoot = await this.orgRootRepository.findOne({
          select: ["id", "orgRootName"],
          where: { id: nodeId },
        });
        if (!orgRoot) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
        rootName = orgRoot.orgRootName;
        whereCase = "posMaster.orgRootId = :nodeId";
        params = { nodeId };
        break;
      }
      case 1: {
        const orgChild1 = await this.child1Repository.findOne({
          select: ["id", "orgChild1Name"],
          where: { id: nodeId },
        });
        if (!orgChild1) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
        rootName = orgChild1.orgChild1Name;
        whereCase = "posMaster.orgChild1Id = :nodeId";
        params = { nodeId };
        break;
      }
      case 2: {
        const orgChild2 = await this.child2Repository.findOne({
          select: ["id", "orgChild2Name"],
          where: { id: nodeId },
        });
        if (!orgChild2) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
        rootName = orgChild2.orgChild2Name;
        whereCase = "posMaster.orgChild2Id = :nodeId";
        params = { nodeId };
        break;
      }
      case 3: {
        const orgChild3 = await this.child3Repository.findOne({
          select: ["id", "orgChild3Name"],
          where: { id: nodeId },
        });
        if (!orgChild3) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
        rootName = orgChild3.orgChild3Name;
        whereCase = "posMaster.orgChild3Id = :nodeId";
        params = { nodeId };
        break;
      }
      case 4: {
        const orgChild4 = await this.child4Repository.findOne({
          select: ["id", "orgChild4Name"],
          where: { id: nodeId },
        });
        if (!orgChild4) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
        rootName = orgChild4.orgChild4Name;
        whereCase = "posMaster.orgChild4Id = :nodeId";
        params = { nodeId };
        break;
      }
      default:
        throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
    }

    // const orgRootData = await this.orgRootRepository.findOne({
    //   where: { id: reqBody.nodeId },
    // });
    // if (!orgRootData) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
    // let rootId:string = reqBody.nodeId;
    const posMaster = await this.posMasterRepository
      .createQueryBuilder("posMaster")
      .leftJoinAndSelect("posMaster.positions", "position")
      .leftJoinAndSelect("position.posType", "posType")
      .leftJoinAndSelect("position.posLevel", "posLevel")
      // .where("posMaster.orgRootId = :rootId", { rootId })
      .where(whereCase, params)
      .orderBy("posType.posTypeRank", "ASC")
      .addOrderBy("posLevel.posLevelRank", "ASC")
      .getMany();

    const _posMaster = posMaster.map((x) => ({
      type: [...new Set(x.positions.flatMap((y) => y.posType.posTypeName))].join(","),
      typeRank: [...new Set(x.positions.flatMap((y) => y.posType.posTypeRank))].join(""),
      level: [...new Set(x.positions.flatMap((y) => y.posLevel.posLevelName))].join(","),
      levelRank: [
        ...new Set(
          x.positions.flatMap((y) => `${y.posType.posTypeRank}${y.posLevel.posLevelRank}`),
        ),
      ].join(""),
      positions: [...new Set(x.positions.flatMap((y) => y.positionName))].join(""),
    }));

    const groupedData = _posMaster.reduce((acc: any, curr: any) => {
      const key = `${curr.type}|${curr.typeRank}|${curr.level}|${curr.levelRank}`;
      if (!acc[key]) {
        acc[key] = { ...curr, total: 1 };
      } else {
        acc[key].total += 1;
      }
      return acc;
    }, {});

    let result = Object.values(groupedData)
      .map((x: any) => ({
        type: x.type,
        typeRank: parseInt(x.typeRank),
        level: x.level,
        levelRank: parseInt(x.levelRank),
        total: x.total,
        remark: x.positions,
      }))
      .sort((x, y) => {
        if (x.typeRank !== y.typeRank) {
          return x.typeRank - y.typeRank;
        }
        return x.levelRank - y.levelRank;
      });
    let tmpType: string = "";
    let allTotal: number = 0;
    let total: number = 0;
    let _total: number = 0;
    let _reslut = new Array();

    result.forEach((x: any, idx: number) => {
      allTotal += x.total;
      total += x.total;
      if (x.type === tmpType) {
        _reslut.push({
          ...x,
          type: "",
        });
      } else {
        if (x.type !== tmpType && tmpType != "") {
          _total = total - x.total;
          _reslut.push({
            type: "",
            typeRank: "",
            level: "รวม",
            levelRank: "",
            total: _total,
            remark: "",
          });
          total = x.total;
          _total = 0;
        }
        _reslut.push({
          ...x,
        });
      }
      tmpType = x.type;
    });

    _reslut.push({
      type: "",
      typeRank: "",
      level: "รวม",
      levelRank: "",
      total: total,
      remark: "",
    });
    _reslut.push({
      type: "",
      typeRank: "",
      level: "รวมทั้งสิ้น",
      levelRank: "",
      total: allTotal,
      remark: "",
    });

    return new HttpSuccess({
      template: "report4",
      reportName: "report4",
      data: {
        dateCurrent: Extension.ToThaiShortDate(new Date()),
        rootName: rootName ? rootName : "-",
        data: _reslut,
      },
    });
  }

  @Get("report4-employee/{rootId}")
  async findReportEmp4(@Path() rootId: string) {
    const orgRootData = await this.orgRootRepository.findOne({
      where: { id: rootId },
    });
    if (!orgRootData) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");

    const posMaster = await this.empPosMasterRepository
      .createQueryBuilder("posMaster")
      .leftJoinAndSelect("posMaster.positions", "position")
      .leftJoinAndSelect("position.posType", "posType")
      .leftJoinAndSelect("position.posLevel", "posLevel")
      .where("posMaster.orgRootId = :rootId", { rootId })
      .orderBy("posType.posTypeRank", "ASC")
      .addOrderBy("posLevel.posLevelRank", "ASC")
      .getMany();

    const _posMaster = posMaster.map((x) => ({
      type: [...new Set(x.positions.flatMap((y) => y.posType.posTypeName))].join(","),
      typeRank: [...new Set(x.positions.flatMap((y) => y.posType.posTypeRank))].join(""),
      level: [...new Set(x.positions.flatMap((y) => y.posLevel.posLevelName))].join(","),
      levelRank: [
        ...new Set(
          x.positions.flatMap((y) => `${y.posType.posTypeRank}${y.posLevel.posLevelRank}`),
        ),
      ].join(""),
      positions: [...new Set(x.positions.flatMap((y) => y.positionName))].join(""),
    }));

    const groupedData = _posMaster.reduce((acc: any, curr: any) => {
      const key = `${curr.type}|${curr.typeRank}|${curr.level}|${curr.levelRank}`;
      if (!acc[key]) {
        acc[key] = { ...curr, total: 1 };
      } else {
        acc[key].total += 1;
         acc[key].total += 1;
        const combinedPositions = new Set([
          ...acc[key].positions.split(", "),
          ...curr.positions.split(", "),
        ]);
        acc[key].positions = Array.from(combinedPositions).join(", ");
      }
      return acc;
    }, {});

    let result = Object.values(groupedData)
      .map((x: any) => ({
        type: x.type,
        typeRank: parseInt(x.typeRank),
        level: x.level,
        levelRank: parseInt(x.levelRank),

        total: x.total,
        remark: x.positions,
      }))
      .sort((x, y) => {
        if (x.typeRank !== y.typeRank) {
          return x.typeRank - y.typeRank;
        }
        return x.levelRank - y.levelRank;
      });
    let tmpType: string = "";
    let allTotal: number = 0;
    let total: number = 0;
    let _total: number = 0;
    let _reslut = new Array();

    result.forEach((x: any, idx: number) => {
      allTotal += x.total;
      total += x.total;
      if (x.type === tmpType) {
        _reslut.push({
          ...x,
          type: "",
        });
      } else {
        if (x.type !== tmpType && tmpType != "") {
          _total = total - x.total;
          _reslut.push({
            type: "",
            typeRank: "",
            level: "รวม",
            levelRank: "",
            total: _total,
            remark: "",
          });
          total = x.total;
          _total = 0;
        }
        _reslut.push({
          ...x,
        });
      }
      tmpType = x.type;
    });

    _reslut.push({
      type: "",
      typeRank: "",
      level: "รวม",
      levelRank: "",
      total: total,
      remark: "",
    });
    _reslut.push({
      type: "",
      typeRank: "",
      level: "รวมทั้งสิ้น",
      levelRank: "",
      total: allTotal,
      remark: "",
    });

    return new HttpSuccess({
      template: "report4",
      reportName: "report4",
      data: {
        dateCurrent: Extension.ToThaiShortDate(new Date()),
        rootName: orgRootData ? orgRootData.orgRootName : "-",
        data: _reslut,
      },
    });
  }

  @Get("report4-employee-temp/{rootId}")
  async findReportEmp4Temp(@Path() rootId: string) {
    const orgRootData = await this.orgRootRepository.findOne({
      where: { id: rootId },
    });
    if (!orgRootData) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");

    const posMaster = await this.empTempPosMasterRepository
      .createQueryBuilder("posMaster")
      .leftJoinAndSelect("posMaster.positions", "position")
      .leftJoinAndSelect("position.posType", "posType")
      .leftJoinAndSelect("position.posLevel", "posLevel")
      .where("posMaster.orgRootId = :rootId", { rootId })
      .orderBy("posType.posTypeRank", "ASC")
      .addOrderBy("posLevel.posLevelRank", "ASC")
      .getMany();
    
    const _posMaster = posMaster.map((x) => ({
      type: [...new Set(x.positions.flatMap((y) => y.posType.posTypeName))].join(","),
      typeRank: [...new Set(x.positions.flatMap((y) => y.posType.posTypeRank))].join(""),
      typeShortNameAndRank: [
        ...new Set(
          x.positions.map(
            (y) => `${y.posType.posTypeShortName} ${y.posLevel.posLevelRank}`
          )
        ),
      ].join(", "),
      level: [...new Set(x.positions.flatMap((y) => y.posLevel.posLevelName))].join(","),
      levelRank: [
        ...new Set(
          x.positions.flatMap((y) => `${y.posType.posTypeRank}${y.posLevel.posLevelRank}`),
        ),
      ].join(""),
      positions: [...new Set(x.positions.map((y) => y.positionName))].join(", "),
    }));

    const groupedData = _posMaster.reduce((acc: any, curr: any) => {
      const key = `${curr.type}|${curr.typeRank}|${curr.level}|${curr.levelRank}`;
      if (!acc[key]) {
        acc[key] = { ...curr, total: 1 };
      } else {
        acc[key].total += 1;
        const combinedPositions = new Set([
          ...acc[key].positions.split(", "),
          ...curr.positions.split(", "),
        ]);
        acc[key].positions = Array.from(combinedPositions).join(", ");
      }
      return acc;
    }, {});
    // console.log("groupedData>>>",groupedData);
    
    let result = Object.values(groupedData)
      .map((x: any) => ({
        type: x.type,
        typeRank: parseInt(x.typeRank),
        typeShortNameAndRank: x.typeShortNameAndRank,
        level: x.level,
        levelRank: parseInt(x.levelRank),

        total: x.total,
        remark: x.positions,
      }))
      .sort((x, y) => {
        if (x.typeRank !== y.typeRank) {
          return x.typeRank - y.typeRank;
        }
        return x.levelRank - y.levelRank;
      });
    let tmpType: string = "";
    let allTotal: number = 0;
    let total: number = 0;
    let _total: number = 0;
    let _reslut = new Array();

    result.forEach((x: any, idx: number) => {
      allTotal += x.total;
      total += x.total;
      if (x.type === tmpType) {
        _reslut.push({
          ...x,
          type: "",
        });
      } else {
        if (x.type !== tmpType && tmpType != "") {
          _total = total - x.total;
          _reslut.push({
            type: "รวม",
            typeRank: "",
            typeShortNameAndRank: "",
            level: "",
            levelRank: "",
            total: _total,
            remark: "",
          });
          total = x.total;
          _total = 0;
        }
        _reslut.push({
          ...x,
        });
      }
      tmpType = x.type;
    });

    _reslut.push({
      type: "รวม",
      typeRank: "",
      typeShortNameAndRank: "",
      level: "",
      levelRank: "",
      total: total,
      remark: "",
    });
    _reslut.push({
      type: "รวมทั้งสิ้น",
      typeRank: "",
      typeShortNameAndRank: "",
      level: "",
      levelRank: "",
      total: allTotal,
      remark: "",
    });

    return new HttpSuccess({
      template: "report5",
      reportName: "report5",
      data: {
        dateCurrent: Extension.ToThaiShortDate(new Date()),
        rootName: orgRootData ? orgRootData.orgRootName : "-",
        data: _reslut,
      },
    });
  }
}
