import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Route,
  Security,
  Tags,
  Body,
  Path,
  Request,
  Example,
} from "tsoa";
import { CreateOrgRoot, OrgRoot, UpdateOrgRoot } from "../entities/OrgRoot";
import { AppDataSource } from "../database/data-source";
import HttpSuccess from "../interfaces/http-success";
import { OrgChild1 } from "../entities/OrgChild1";
import { In, Not } from "typeorm";
import HttpError from "../interfaces/http-error";
import HttpStatusCode from "../interfaces/http-status";
import { OrgRevision } from "../entities/OrgRevision";
import { OrgChild2 } from "../entities/OrgChild2";
import { OrgChild3 } from "../entities/OrgChild3";
import { OrgChild4 } from "../entities/OrgChild4";
import { PosMaster } from "../entities/PosMaster";
import { Position } from "../entities/Position";
import { EmployeePosMaster } from "../entities/EmployeePosMaster";
import { EmployeePosition } from "../entities/EmployeePosition";
import permission from "../interfaces/permission";
import { RequestWithUser } from "../middlewares/user";
import { setLogDataDiff } from "../interfaces/utils";
import { EmployeeTempPosMaster } from "../entities/EmployeeTempPosMaster";
import { Profile } from "../entities/Profile";
import { ProfileEmployee } from "../entities/ProfileEmployee";

@Route("api/v1/org/root")
@Tags("OrgRoot")
@Security("bearerAuth")
export class OrgRootController extends Controller {
  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 orgRevisionRepository = AppDataSource.getRepository(OrgRevision);
  private posMasterRepository = AppDataSource.getRepository(PosMaster);
  private positionRepository = AppDataSource.getRepository(Position);
  private empPosMasterRepository = AppDataSource.getRepository(EmployeePosMaster);
  private empPositionRepository = AppDataSource.getRepository(EmployeePosition);

  /**
   * API รายละเอียดโครงสร้างระดับ Root
   *
   * @summary ORG_016 - รายละเอียดโครงสร้างระดับ Root (ADMIN) #16
   *
   * @param {string} id  Id Root
   */
  @Get("{id}")
  async GetRoot(@Path() id: string) {
    const orgRoot = await this.orgRootRepository.findOne({ where: { id } });
    if (!orgRoot) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงสร้างระดับ Root นี้");
    }
    const getOrgRoot = {
      orgRootId: orgRoot.id,
      responsibility: orgRoot.responsibility,
      orgRootName: orgRoot.orgRootName,
      orgName: "-",
      orgRootShortName: orgRoot.orgRootShortName,
      orgRootCode: orgRoot.orgRootCode,
      orgRootRank: orgRoot.orgRootRank,
      orgRootRankSub: orgRoot.orgRootRankSub,
      orgRootOrder: orgRoot.orgRootOrder,
      orgRootPhoneEx: orgRoot.orgRootPhoneEx,
      orgRootPhoneIn: orgRoot.orgRootPhoneIn,
      orgRootFax: orgRoot.orgRootFax,
      orgRevisionId: orgRoot.orgRevisionId,
      isDeputy: orgRoot.isDeputy,
      isCommission: orgRoot.isCommission,
      misId: orgRoot.misId,
      DEPARTMENT_CODE: orgRoot.DEPARTMENT_CODE,
      DIVISION_CODE: orgRoot.DIVISION_CODE,
      SECTION_CODE: orgRoot.SECTION_CODE,
      JOB_CODE: orgRoot.JOB_CODE,
      orgCode: orgRoot.orgRootCode + "00",
    };
    return new HttpSuccess(getOrgRoot);
  }

  /**
   * สร้างโครงสร้างระดับ Root
   *
   * @summary ORG_001 - สร้างโครงสร้างระดับ Root (ADMIN) #1
   *
   */
  @Post()
  @Example([
    {
      orgRootName: "string", //ชื่อหน่วยงาน
      orgRootShortName: "string", //อักษรย่อ
      orgRootCode: "string", //รหัสหน่วยงาน
      orgRootPhoneEx: "string", //หมายเลขโทรศัพท์ที่ติดต่อจากภายนอก
      orgRootPhoneIn: "string", //หมายเลขโทรศัพท์ที่ติดต่อจากภายใน
      orgRootFax: "string", //หมายเลขโทรสาร
      orgRootIsNormal: "boolean", //สถานะของหน่วยงาน
    },
  ])
  async create(
    // @Path() id: string,
    @Body()
    requestBody: CreateOrgRoot,
    @Request() request: RequestWithUser,
  ) {
    await new permission().PermissionCreate(request, "SYS_ORG");

    if (requestBody.isDeputy == true) {
      const orgRevision = await this.orgRevisionRepository.findOne({
        where: { id: requestBody.orgRevisionId },
        relations: ["orgRoots"],
      });
      if (orgRevision != null) {
        await Promise.all(
          orgRevision.orgRoots
            .filter((x: OrgRoot) => x.isDeputy == true)
            .map(async (item: OrgRoot) => {
              item.isDeputy = false;
              await this.orgRootRepository.save(item);
            }),
        );
      }
    }

    if (requestBody.isCommission == true) {
      const orgRevision = await this.orgRevisionRepository.findOne({
        where: { id: requestBody.orgRevisionId },
        relations: ["orgRoots"],
      });
      if (orgRevision != null) {
        await Promise.all(
          orgRevision.orgRoots
            .filter((x: OrgRoot) => x.isCommission == true)
            .map(async (item: OrgRoot) => {
              item.isCommission = false;
              await this.orgRootRepository.save(item);
            }),
        );
      }
    }

    const validOrgRootRanks = ["DEPARTMENT", "OFFICE", "DIVISION", "SECTION"];
    if (!validOrgRootRanks.includes(requestBody.orgRootRank.toUpperCase())) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "not found. orgRootRank");
    }

    const orgRoot = Object.assign(new OrgRoot(), requestBody);
    if (!orgRoot) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
    }

    const chkCode = await this.orgRootRepository.findOne({
      where: { orgRevisionId: requestBody.orgRevisionId, orgRootCode: requestBody.orgRootCode },
    });
    if (chkCode != null) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "รหัสหน่วยงานนี้มีอยู่ในระบบแล้ว");
    }

    const chkShort = await this.orgRootRepository.findOne({
      where: {
        orgRevisionId: requestBody.orgRevisionId,
        orgRootShortName: requestBody.orgRootShortName,
      },
    });
    if (chkShort != null) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "อักษรย่อนี้มีอยู่ในระบบแล้ว");
    }

    const orgRevision = await this.orgRevisionRepository.findOne({
      where: { id: requestBody.orgRevisionId },
    });
    if (!orgRevision) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "not found. RevisionId");
    }

    if (orgRevision.orgRevisionIsDraft != true && orgRevision.orgRevisionIsCurrent != false) {
      throw new HttpError(
        HttpStatusCode.NOT_FOUND,
        "not found. orgRevisionIsDraft:true, orgRevisionIsCurrent:false",
      );
    }
    const order: any = await this.orgRootRepository.findOne({
      where: {
        orgRevisionId: requestBody.orgRevisionId,
      },
      order: { orgRootOrder: "DESC" },
    });
    const before = null;
    orgRoot.createdUserId = request.user.sub;
    orgRoot.createdFullName = request.user.name;
    orgRoot.lastUpdateUserId = request.user.sub;
    orgRoot.lastUpdateFullName = request.user.name;
    orgRoot.createdAt = new Date();
    orgRoot.lastUpdatedAt = new Date();
    orgRoot.orgRootOrder = order == null || order.orgRootOrder == null ? 1 : order.orgRootOrder + 1;
    await this.orgRootRepository.save(orgRoot, { data: request });
    // update ancestorDNA = id row
    orgRoot.ancestorDNA = orgRoot.id;
    await this.orgRootRepository.save(orgRoot, { data: request });
    setLogDataDiff(request, { before, after: orgRoot });

    return new HttpSuccess();
  }

  /**
   * แก้ไขโครงสร้างระดับ Root
   *
   * @summary ORG_002 - แก้ไขโครงสร้างระดับ Root (ADMIN) #2
   *
   * @param {string} id  Guid, *Id root
   */
  @Put("{id}")
  @Example([
    {
      orgRootName: "string", //ชื่อหน่วยงาน
      orgRootShortName: "string", //อักษรย่อ
      orgRootCode: "string", //รหัสหน่วยงาน
      orgRootPhoneEx: "string", //หมายเลขโทรศัพท์ที่ติดต่อจากภายนอก
      orgRootPhoneIn: "string", //หมายเลขโทรศัพท์ที่ติดต่อจากภายใน
      orgRootFax: "string", //หมายเลขโทรสาร
      orgRootIsNormal: "boolean", //สถานะของหน่วยงาน
    },
  ])
  async update(
    @Path() id: string,
    @Body()
    requestBody: UpdateOrgRoot,
    @Request() request: RequestWithUser,
  ) {
    await new permission().PermissionUpdate(request, "SYS_ORG");
    const validOrgRootRanks = ["DEPARTMENT", "OFFICE", "DIVISION", "SECTION"];
    if (!validOrgRootRanks.includes(requestBody.orgRootRank.toUpperCase())) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "not found. orgRo otRank");
    }

    if (requestBody.isDeputy == true) {
      const orgRevision = await this.orgRevisionRepository.findOne({
        where: { id: requestBody.orgRevisionId },
        relations: ["orgRoots"],
      });
      if (orgRevision != null) {
        await Promise.all(
          orgRevision.orgRoots
            .filter((x: OrgRoot) => x.isDeputy == true)
            .map(async (item: OrgRoot) => {
              item.isDeputy = false;
              await this.orgRootRepository.save(item);
            }),
        );
      }
    }

    if (requestBody.isCommission == true) {
      const orgRevision = await this.orgRevisionRepository.findOne({
        where: { id: requestBody.orgRevisionId },
        relations: ["orgRoots"],
      });
      if (orgRevision != null) {
        await Promise.all(
          orgRevision.orgRoots
            .filter((x: OrgRoot) => x.isCommission == true)
            .map(async (item: OrgRoot) => {
              item.isCommission = false;
              await this.orgRootRepository.save(item);
            }),
        );
      }
    }

    const revisionIdExits = await this.orgRevisionRepository.findOne({
      where: { id: requestBody.orgRevisionId },
    });
    if (!revisionIdExits) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "not found. RevisionId");
    }
    if (
      revisionIdExits.orgRevisionIsDraft != true &&
      revisionIdExits.orgRevisionIsCurrent != false
    ) {
      throw new HttpError(
        HttpStatusCode.NOT_FOUND,
        "not found. orgRevisionIsDraft:true, orgRevisionIsCurrent:false",
      );
    }

    const chkCode = await this.orgRootRepository.findOne({
      where: {
        orgRevisionId: requestBody.orgRevisionId,
        orgRootCode: requestBody.orgRootCode,
        id: Not(id),
      },
    });
    if (chkCode != null) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "รหัสหน่วยงานนี้มีอยู่ในระบบแล้ว");
    }

    const chkShort = await this.orgRootRepository.findOne({
      where: {
        orgRevisionId: requestBody.orgRevisionId,
        orgRootShortName: requestBody.orgRootShortName,
        id: Not(id),
      },
    });
    if (chkShort != null) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "อักษรย่อนี้มีอยู่ในระบบแล้ว");
    }

    const orgRoot = await this.orgRootRepository.findOne({ where: { id } });
    if (!orgRoot) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงสร้างระดับ Root นี้");
    }

    // const chkCodeChild1 = await this.child1Repository.findOne({
    //   where:{
    //     orgRevisionId : requestBody.orgRevisionId,
    //     orgRootId: id,
    //     orgChild1Code: requestBody.orgRootCode,
    //   }
    // });
    // if(chkCodeChild1 != null){
    //   throw new HttpError(HttpStatusCode.NOT_FOUND, "รหัสหน่วยงานนี้ซ้ำกับรหัสส่วนราชการ");
    // }
    // const chkShortChild1 = await this.child1Repository.findOne({
    //   where:{
    //     orgRevisionId : requestBody.orgRevisionId,
    //     orgRootId: id,
    //     orgChild1ShortName: requestBody.orgRootShortName,
    //   }
    // });
    // if(chkShortChild1 != null){
    //   throw new HttpError(HttpStatusCode.NOT_FOUND, "อักษรย่อนี้ซ้ำกับอักษรย่อส่วนราชการ");
    // }
    const _null: any = null;
    const before = structuredClone(orgRoot);
    orgRoot.lastUpdateUserId = request.user.sub;
    orgRoot.lastUpdateFullName = request.user.name;
    // orgRoot.lastUpdatedAt = new Date();
    this.orgRootRepository.merge(orgRoot, {
      ...requestBody,
      DEPARTMENT_CODE: requestBody.DEPARTMENT_CODE != null ? requestBody.DEPARTMENT_CODE : _null,
      DIVISION_CODE: requestBody.DIVISION_CODE != null ? requestBody.DIVISION_CODE : _null,
      SECTION_CODE: requestBody.SECTION_CODE != null ? requestBody.SECTION_CODE : _null,
      JOB_CODE: requestBody.JOB_CODE != null ? requestBody.JOB_CODE : _null,
    });
    await this.orgRootRepository.save(orgRoot, { data: request });
    setLogDataDiff(request, { before, after: orgRoot });

    if (orgRoot.orgRootRankSub == "DISTRICT" || orgRoot.orgRootRankSub == "OFFICE") {
      const up_Child1 = await this.child1Repository.find({
        where: {
          orgRevisionId: orgRoot.orgRevisionId,
          orgRootId: id,
        },
      });
      if (up_Child1.length > 0) {
        for (const _child1 of up_Child1) {
          _child1.orgChild1ShortName = String(requestBody.orgRootShortName);
          _child1.orgChild1Code = String(requestBody.orgRootCode);
        }
        await this.child1Repository.save(up_Child1);
      }
      const up_Child2 = await this.child2Repository.find({
        where: {
          orgRevisionId: orgRoot.orgRevisionId,
          orgRootId: id,
        },
      });
      if (up_Child2.length > 0) {
        for (const _child2 of up_Child2) {
          _child2.orgChild2ShortName = String(requestBody.orgRootShortName);
          _child2.orgChild2Code = String(requestBody.orgRootCode);
        }
        await this.child2Repository.save(up_Child2);
      }

      const up_Child3 = await this.child3Repository.find({
        where: {
          orgRevisionId: orgRoot.orgRevisionId,
          orgRootId: id,
        },
      });
      if (up_Child3.length > 0) {
        for (const _child3 of up_Child3) {
          _child3.orgChild3ShortName = String(requestBody.orgRootShortName);
          _child3.orgChild3Code = String(requestBody.orgRootCode);
        }
        await this.child3Repository.save(up_Child3);
      }

      const up_Child4 = await this.child4Repository.find({
        where: {
          orgRevisionId: orgRoot.orgRevisionId,
          orgRootId: id,
        },
      });
      if (up_Child4.length > 0) {
        for (const _child4 of up_Child4) {
          _child4.orgChild4ShortName = String(requestBody.orgRootShortName);
          _child4.orgChild4Code = String(requestBody.orgRootCode);
        }
        await this.child4Repository.save(up_Child4);
      }
    }
    return new HttpSuccess();
  }

  /**
   * ลบโครงสร้างระดับ Root
   *
   * @summary ORG_003 - ลบโครงสร้างระดับ Root (ADMIN) #3
   *
   * @param {string} id  Guid, *Id root
   */
  @Delete("{id}")
  async delete(@Path() id: string, @Request() request: RequestWithUser) {
    await new permission().PermissionDelete(request, "SYS_ORG");
    const orgRoot = await this.orgRootRepository.findOne({ where: { id } });
    if (!orgRoot) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงสร้างระดับ Root นี้");
    }

    // const orgChild1 = await this.child1Repository.findOne({ where: { orgRootId: id } });
    // if (orgChild1 != null) {
    //   throw new HttpError(
    //     HttpStatusCode.INTERNAL_SERVER_ERROR,
    //     "ไม่สามารถลบข้อมูลได้เมื่อมีข้อมูลโครงสร้างระดับ1",
    //   );
    // }

    const revisionIdExits = await this.orgRevisionRepository.findOne({
      where: { id: orgRoot.orgRevisionId },
    });
    if (!revisionIdExits) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "not found. RevisionId");
    }
    if (
      revisionIdExits.orgRevisionIsDraft != true &&
      revisionIdExits.orgRevisionIsCurrent != false
    ) {
      throw new HttpError(
        HttpStatusCode.NOT_FOUND,
        "not found. orgRevisionIsDraft:true, orgRevisionIsCurrent:false",
      );
    }
    const posMasters = await this.posMasterRepository.find({
      where: { orgRootId: id },
    });
    const positions = await this.positionRepository.find({
      where: [{ posMasterId: In(posMasters.map((x) => x.id)) }],
    });
    const empPosMasters = await this.empPosMasterRepository.find({
      where: { orgRootId: id },
    });
    const empPositions = await this.empPositionRepository.find({
      where: [{ posMasterId: In(empPosMasters.map((x) => x.id)) }],
    });

    await this.empPositionRepository.remove(empPositions, { data: request });
    await this.empPosMasterRepository.remove(empPosMasters, { data: request });
    await this.positionRepository.remove(positions, { data: request });
    await this.posMasterRepository.remove(posMasters, { data: request });
    await this.child4Repository.delete({ orgRootId: id });
    await this.child3Repository.delete({ orgRootId: id });
    await this.child2Repository.delete({ orgRootId: id });
    await this.child1Repository.delete({ orgRootId: id });
    await this.orgRootRepository.delete({ id });

    return new HttpSuccess();
  }

  @Get("publish/employee")
  async publishEmployee(@Request() request: RequestWithUser) {
    const repoEmployeePosmaster = AppDataSource.getRepository(EmployeePosMaster);
    const repoEmployeeTempPosmaster = AppDataSource.getRepository(EmployeeTempPosMaster);
    const repoProfileEmployee = AppDataSource.getRepository(ProfileEmployee);
    const employeePositionRepository = AppDataSource.getRepository(EmployeePosition);
    const repoOrgRevision = AppDataSource.getRepository(OrgRevision);
    const orgRootRepository = AppDataSource.getRepository(OrgRoot);
    const child1Repository = AppDataSource.getRepository(OrgChild1);
    const child2Repository = AppDataSource.getRepository(OrgChild2);
    const child3Repository = AppDataSource.getRepository(OrgChild3);
    const child4Repository = AppDataSource.getRepository(OrgChild4);

    const orgRevisionPublish = await repoOrgRevision
      .createQueryBuilder("orgRevision")
      .where("orgRevision.orgRevisionIsDraft = false")
      .andWhere("orgRevision.orgRevisionIsCurrent = true")
      .getOne();
    try {
      if (orgRevisionPublish != null) {
        const _orgRevisions = await repoOrgRevision.find({
          where: [{ orgRevisionIsDraft: true, id: Not(orgRevisionPublish.id) }],
        });
        const _employeePosMasters = await repoEmployeePosmaster.find({
          where: [{ orgRevisionId: In(_orgRevisions.map((x) => x.id)) }],
        });
        const _employeeTempPosMasters = await repoEmployeeTempPosmaster.find({
          where: [{ orgRevisionId: In(_orgRevisions.map((x) => x.id)) }],
        });
        await employeePositionRepository.delete({
          posMasterId: In(_employeePosMasters.map((x) => x.id)),
        });
        await employeePositionRepository.delete({
          posMasterTempId: In(_employeeTempPosMasters.map((x) => x.id)),
        });
        await repoEmployeePosmaster.remove(_employeePosMasters);
        await repoEmployeeTempPosmaster.remove(_employeeTempPosMasters);

        //หา dna tree
        const orgRoot = await orgRootRepository.find({
          where: { orgRevisionId: orgRevisionPublish.id },
        });

        const orgChild1 = await child1Repository.find({
          where: { orgRevisionId: orgRevisionPublish.id },
        });

        const orgChild2 = await child2Repository.find({
          where: { orgRevisionId: orgRevisionPublish.id },
        });

        const orgChild3 = await child3Repository.find({
          where: { orgRevisionId: orgRevisionPublish.id },
        });

        const orgChild4 = await child4Repository.find({
          where: { orgRevisionId: orgRevisionPublish.id },
        });

        //หา dna posmaster ถ้าไม่มีให้เอาตัวเองเป็น dna
        const orgemployeePosMaster = await repoEmployeePosmaster.find({
          where: { orgRevisionId: orgRevisionPublish.id },
          relations: ["positions"],
        });

        let _orgemployeePosMaster: EmployeePosMaster[];
        _orgemployeePosMaster = orgemployeePosMaster.map((x) => ({
          ...x,
          ancestorDNA:
            x.ancestorDNA == null || x.ancestorDNA == "00000000-0000-0000-0000-000000000000"
              ? x.id
              : x.ancestorDNA,
        }));
        await repoEmployeePosmaster.save(_orgemployeePosMaster);
        //หา dna posmaster ถ้าไม่มีให้เอาตัวเองเป็น dna
        const orgemployeeTempPosMaster = await repoEmployeeTempPosmaster.find({
          where: { orgRevisionId: orgRevisionPublish.id },
          relations: ["positions"],
        });

        let _orgemployeeTempPosMaster: EmployeeTempPosMaster[];
        _orgemployeeTempPosMaster = orgemployeeTempPosMaster.map((x) => ({
          ...x,
          ancestorDNA:
            x.ancestorDNA == null || x.ancestorDNA == "00000000-0000-0000-0000-000000000000"
              ? x.id
              : x.ancestorDNA,
        }));
        await repoEmployeeTempPosmaster.save(_orgemployeeTempPosMaster);

        //create org
        orgRoot.forEach(async (x: any) => {
          var dataId = x.id;
          //create employeePosmaster
          await Promise.all(
            _orgemployeePosMaster
              .filter((x: EmployeePosMaster) => x.orgRootId == dataId && x.orgChild1Id == null)
              .map(async (item: any) => {
                delete item.id;
                const employeePosMaster = Object.assign(new EmployeePosMaster(), item);
                employeePosMaster.positions = [];
                employeePosMaster.orgRevisionId = orgRevisionPublish.id;
                employeePosMaster.orgRootId = dataId;
                employeePosMaster.createdUserId = "";
                employeePosMaster.createdFullName = "System Administrator";
                employeePosMaster.createdAt = new Date();
                employeePosMaster.lastUpdateUserId = "";
                employeePosMaster.lastUpdateFullName = "System Administrator";
                employeePosMaster.lastUpdatedAt = new Date();
                await repoEmployeePosmaster.save(employeePosMaster);

                //create employeePosition
                item.positions.map(async (pos: any) => {
                  delete pos.id;
                  const employeePosition: EmployeePosition = Object.assign(
                    new EmployeePosition(),
                    pos,
                  );
                  employeePosition.posMasterId = employeePosMaster.id;
                  employeePosition.createdUserId = "";
                  employeePosition.createdFullName = "System Administrator";
                  employeePosition.createdAt = new Date();
                  employeePosition.lastUpdateUserId = "";
                  employeePosition.lastUpdateFullName = "System Administrator";
                  employeePosition.lastUpdatedAt = new Date();
                  await employeePositionRepository.save(employeePosition);
                });
              }),
          );
          //create employeeTempPosmaster
          await Promise.all(
            _orgemployeeTempPosMaster
              .filter((x: EmployeeTempPosMaster) => x.orgRootId == dataId && x.orgChild1Id == null)
              .map(async (item: any) => {
                delete item.id;
                const employeeTempPosMaster = Object.assign(new EmployeeTempPosMaster(), item);
                employeeTempPosMaster.positions = [];
                employeeTempPosMaster.orgRevisionId = orgRevisionPublish.id;
                employeeTempPosMaster.orgRootId = dataId;
                employeeTempPosMaster.createdUserId = "";
                employeeTempPosMaster.createdFullName = "System Administrator";
                employeeTempPosMaster.createdAt = new Date();
                employeeTempPosMaster.lastUpdateUserId = "";
                employeeTempPosMaster.lastUpdateFullName = "System Administrator";
                employeeTempPosMaster.lastUpdatedAt = new Date();
                await repoEmployeeTempPosmaster.save(employeeTempPosMaster);

                //create employeePosition
                item.positions.map(async (pos: any) => {
                  delete pos.id;
                  const employeePosition: EmployeePosition = Object.assign(
                    new EmployeePosition(),
                    pos,
                  );
                  employeePosition.createdUserId = "";
                  employeePosition.createdFullName = "System Administrator";
                  employeePosition.createdAt = new Date();
                  employeePosition.lastUpdateUserId = "";
                  employeePosition.lastUpdateFullName = "System Administrator";
                  employeePosition.lastUpdatedAt = new Date();
                  await employeePositionRepository.save(employeePosition);
                });
              }),
          );
          // }

          //create org
          orgChild1
            .filter((x: OrgChild1) => x.orgRootId == dataId)
            .forEach(async (x: any) => {
              var data1Id = x.id;
              //create employeePosmaster
              await Promise.all(
                _orgemployeePosMaster
                  .filter(
                    (x: EmployeePosMaster) => x.orgChild1Id == data1Id && x.orgChild2Id == null,
                  )
                  .map(async (item: any) => {
                    delete item.id;
                    const employeePosMaster = Object.assign(new EmployeePosMaster(), item);
                    employeePosMaster.positions = [];
                    employeePosMaster.orgRevisionId = orgRevisionPublish.id;
                    employeePosMaster.orgRootId = dataId;
                    employeePosMaster.orgChild1Id = data1Id;
                    employeePosMaster.createdUserId = "";
                    employeePosMaster.createdFullName = "System Administrator";
                    employeePosMaster.createdAt = new Date();
                    employeePosMaster.lastUpdateUserId = "";
                    employeePosMaster.lastUpdateFullName = "System Administrator";
                    employeePosMaster.lastUpdatedAt = new Date();
                    await repoEmployeePosmaster.save(employeePosMaster);

                    //create employeePosition
                    item.positions.map(async (pos: any) => {
                      delete pos.id;
                      const employeePosition: EmployeePosition = Object.assign(
                        new EmployeePosition(),
                        pos,
                      );
                      employeePosition.posMasterId = employeePosMaster.id;
                      employeePosition.createdUserId = "";
                      employeePosition.createdFullName = "System Administrator";
                      employeePosition.createdAt = new Date();
                      employeePosition.lastUpdateUserId = "";
                      employeePosition.lastUpdateFullName = "System Administrator";
                      employeePosition.lastUpdatedAt = new Date();
                      await employeePositionRepository.save(employeePosition);
                    });
                  }),
              );
              // create employeeTempPosmaster
              await Promise.all(
                _orgemployeeTempPosMaster
                  .filter(
                    (x: EmployeeTempPosMaster) => x.orgChild1Id == data1Id && x.orgChild2Id == null,
                  )
                  .map(async (item: any) => {
                    delete item.id;
                    const employeeTempPosMaster = Object.assign(new EmployeeTempPosMaster(), item);
                    employeeTempPosMaster.positions = [];
                    employeeTempPosMaster.orgRevisionId = orgRevisionPublish.id;
                    employeeTempPosMaster.orgRootId = dataId;
                    employeeTempPosMaster.orgChild1Id = data1Id;
                    employeeTempPosMaster.createdUserId = "";
                    employeeTempPosMaster.createdFullName = "System Administrator";
                    employeeTempPosMaster.createdAt = new Date();
                    employeeTempPosMaster.lastUpdateUserId = "";
                    employeeTempPosMaster.lastUpdateFullName = "System Administrator";
                    employeeTempPosMaster.lastUpdatedAt = new Date();
                    await repoEmployeeTempPosmaster.save(employeeTempPosMaster);

                    //create employeePosition
                    item.positions.map(async (pos: any) => {
                      delete pos.id;
                      const employeePosition: EmployeePosition = Object.assign(
                        new EmployeePosition(),
                        pos,
                      );
                      employeePosition.posMasterTempId = employeeTempPosMaster.id;
                      employeePosition.createdUserId = "";
                      employeePosition.createdFullName = "System Administrator";
                      employeePosition.createdAt = new Date();
                      employeePosition.lastUpdateUserId = "";
                      employeePosition.lastUpdateFullName = "System Administrator";
                      employeePosition.lastUpdatedAt = new Date();
                      await employeePositionRepository.save(employeePosition);
                    });
                  }),
              );
              // }

              //create org
              orgChild2
                .filter((x: OrgChild2) => x.orgChild1Id == data1Id)
                .forEach(async (x: any) => {
                  var data2Id = x.id;
                  //create employeePosmaster
                  await Promise.all(
                    _orgemployeePosMaster
                      .filter(
                        (x: EmployeePosMaster) => x.orgChild2Id == data2Id && x.orgChild3Id == null,
                      )
                      .map(async (item: any) => {
                        delete item.id;
                        const employeePosMaster = Object.assign(new EmployeePosMaster(), item);
                        employeePosMaster.positions = [];
                        employeePosMaster.orgRevisionId = orgRevisionPublish.id;
                        employeePosMaster.orgRootId = dataId;
                        employeePosMaster.orgChild1Id = data1Id;
                        employeePosMaster.orgChild2Id = data2Id;
                        employeePosMaster.createdUserId = "";
                        employeePosMaster.createdFullName = "System Administrator";
                        employeePosMaster.createdAt = new Date();
                        employeePosMaster.lastUpdateUserId = "";
                        employeePosMaster.lastUpdateFullName = "System Administrator";
                        employeePosMaster.lastUpdatedAt = new Date();
                        await repoEmployeePosmaster.save(employeePosMaster);

                        //create employeePosition
                        item.positions.map(async (pos: any) => {
                          delete pos.id;
                          const employeePosition: EmployeePosition = Object.assign(
                            new EmployeePosition(),
                            pos,
                          );
                          employeePosition.posMasterId = employeePosMaster.id;
                          employeePosition.createdUserId = "";
                          employeePosition.createdFullName = "System Administrator";
                          employeePosition.createdAt = new Date();
                          employeePosition.lastUpdateUserId = "";
                          employeePosition.lastUpdateFullName = "System Administrator";
                          employeePosition.lastUpdatedAt = new Date();
                          await employeePositionRepository.save(employeePosition);
                        });
                      }),
                  );
                  // create employeeTempPosmaster
                  await Promise.all(
                    _orgemployeeTempPosMaster
                      .filter(
                        (x: EmployeeTempPosMaster) =>
                          x.orgChild2Id == data2Id && x.orgChild3Id == null,
                      )
                      .map(async (item: any) => {
                        delete item.id;
                        const employeeTempPosMaster = Object.assign(
                          new EmployeeTempPosMaster(),
                          item,
                        );
                        employeeTempPosMaster.positions = [];
                        employeeTempPosMaster.orgRevisionId = orgRevisionPublish.id;
                        employeeTempPosMaster.orgRootId = dataId;
                        employeeTempPosMaster.orgChild1Id = data1Id;
                        employeeTempPosMaster.orgChild2Id = data2Id;
                        employeeTempPosMaster.createdUserId = "";
                        employeeTempPosMaster.createdFullName = "System Administrator";
                        employeeTempPosMaster.createdAt = new Date();
                        employeeTempPosMaster.lastUpdateUserId = "";
                        employeeTempPosMaster.lastUpdateFullName = "System Administrator";
                        employeeTempPosMaster.lastUpdatedAt = new Date();
                        await repoEmployeeTempPosmaster.save(employeeTempPosMaster);

                        //create employeePosition
                        item.positions.map(async (pos: any) => {
                          delete pos.id;
                          const employeePosition: EmployeePosition = Object.assign(
                            new EmployeePosition(),
                            pos,
                          );
                          employeePosition.posMasterTempId = employeeTempPosMaster.id;
                          employeePosition.createdUserId = "";
                          employeePosition.createdFullName = "System Administrator";
                          employeePosition.createdAt = new Date();
                          employeePosition.lastUpdateUserId = "";
                          employeePosition.lastUpdateFullName = "System Administrator";
                          employeePosition.lastUpdatedAt = new Date();
                          await employeePositionRepository.save(employeePosition);
                        });
                      }),
                  );
                  // }

                  //create org
                  orgChild3
                    .filter((x: OrgChild3) => x.orgChild2Id == data2Id)
                    .forEach(async (x: any) => {
                      var data3Id = x.id;
                      //create employeePosmaster
                      await Promise.all(
                        _orgemployeePosMaster
                          .filter(
                            (x: EmployeePosMaster) =>
                              x.orgChild3Id == data3Id && x.orgChild4Id == null,
                          )
                          .map(async (item: any) => {
                            delete item.id;
                            const employeePosMaster = Object.assign(new EmployeePosMaster(), item);
                            employeePosMaster.positions = [];
                            employeePosMaster.orgRevisionId = orgRevisionPublish.id;
                            employeePosMaster.orgRootId = dataId;
                            employeePosMaster.orgChild1Id = data1Id;
                            employeePosMaster.orgChild2Id = data2Id;
                            employeePosMaster.orgChild3Id = data3Id;
                            employeePosMaster.createdUserId = "";
                            employeePosMaster.createdFullName = "System Administrator";
                            employeePosMaster.createdAt = new Date();
                            employeePosMaster.lastUpdateUserId = "";
                            employeePosMaster.lastUpdateFullName = "System Administrator";
                            employeePosMaster.lastUpdatedAt = new Date();
                            await repoEmployeePosmaster.save(employeePosMaster);

                            //create employeePosition
                            item.positions.map(async (pos: any) => {
                              delete pos.id;
                              const employeePosition: EmployeePosition = Object.assign(
                                new EmployeePosition(),
                                pos,
                              );
                              employeePosition.posMasterId = employeePosMaster.id;
                              employeePosition.createdUserId = "";
                              employeePosition.createdFullName = "System Administrator";
                              employeePosition.createdAt = new Date();
                              employeePosition.lastUpdateUserId = "";
                              employeePosition.lastUpdateFullName = "System Administrator";
                              employeePosition.lastUpdatedAt = new Date();
                              await employeePositionRepository.save(employeePosition);
                            });
                          }),
                      );
                      // create employeeTempPosmaster
                      await Promise.all(
                        _orgemployeeTempPosMaster
                          .filter(
                            (x: EmployeeTempPosMaster) =>
                              x.orgChild3Id == data3Id && x.orgChild4Id == null,
                          )
                          .map(async (item: any) => {
                            delete item.id;
                            const employeeTempPosMaster = Object.assign(
                              new EmployeeTempPosMaster(),
                              item,
                            );
                            employeeTempPosMaster.positions = [];
                            employeeTempPosMaster.orgRevisionId = orgRevisionPublish.id;
                            employeeTempPosMaster.orgRootId = dataId;
                            employeeTempPosMaster.orgChild1Id = data1Id;
                            employeeTempPosMaster.orgChild2Id = data2Id;
                            employeeTempPosMaster.orgChild3Id = data3Id;
                            employeeTempPosMaster.createdUserId = "";
                            employeeTempPosMaster.createdFullName = "System Administrator";
                            employeeTempPosMaster.createdAt = new Date();
                            employeeTempPosMaster.lastUpdateUserId = "";
                            employeeTempPosMaster.lastUpdateFullName = "System Administrator";
                            employeeTempPosMaster.lastUpdatedAt = new Date();
                            await repoEmployeeTempPosmaster.save(employeeTempPosMaster);

                            //create employeePosition
                            item.positions.map(async (pos: any) => {
                              delete pos.id;
                              const employeePosition: EmployeePosition = Object.assign(
                                new EmployeePosition(),
                                pos,
                              );
                              employeePosition.posMasterTempId = employeeTempPosMaster.id;
                              employeePosition.createdUserId = "";
                              employeePosition.createdFullName = "System Administrator";
                              employeePosition.createdAt = new Date();
                              employeePosition.lastUpdateUserId = "";
                              employeePosition.lastUpdateFullName = "System Administrator";
                              employeePosition.lastUpdatedAt = new Date();
                              await employeePositionRepository.save(employeePosition);
                            });
                          }),
                      );

                      //create org
                      orgChild4
                        .filter((x: OrgChild4) => x.orgChild3Id == data3Id)
                        .forEach(async (x: any) => {
                          var data4Id = x.id;
                          await Promise.all(
                            _orgemployeePosMaster
                              .filter((x: EmployeePosMaster) => x.orgChild4Id == data4Id)
                              .map(async (item: any) => {
                                delete item.id;
                                const employeePosMaster = Object.assign(
                                  new EmployeePosMaster(),
                                  item,
                                );
                                employeePosMaster.positions = [];
                                employeePosMaster.orgRevisionId = orgRevisionPublish.id;
                                employeePosMaster.orgRootId = dataId;
                                employeePosMaster.orgChild1Id = data1Id;
                                employeePosMaster.orgChild2Id = data2Id;
                                employeePosMaster.orgChild3Id = data3Id;
                                employeePosMaster.orgChild4Id = data4Id;
                                employeePosMaster.createdUserId = "";
                                employeePosMaster.createdFullName = "System Administrator";
                                employeePosMaster.createdAt = new Date();
                                employeePosMaster.lastUpdateUserId = "";
                                employeePosMaster.lastUpdateFullName = "System Administrator";
                                employeePosMaster.lastUpdatedAt = new Date();
                                await repoEmployeePosmaster.save(employeePosMaster);

                                //create employeePosition
                                item.positions.map(async (pos: any) => {
                                  delete pos.id;
                                  const employeePosition: EmployeePosition = Object.assign(
                                    new EmployeePosition(),
                                    pos,
                                  );
                                  employeePosition.posMasterId = employeePosMaster.id;
                                  employeePosition.createdUserId = "";
                                  employeePosition.createdFullName = "System Administrator";
                                  employeePosition.createdAt = new Date();
                                  employeePosition.lastUpdateUserId = "";
                                  employeePosition.lastUpdateFullName = "System Administrator";
                                  employeePosition.lastUpdatedAt = new Date();
                                  await employeePositionRepository.save(employeePosition);
                                });
                              }),
                          );
                          //create employeeTempPosmaster
                          await Promise.all(
                            _orgemployeeTempPosMaster
                              .filter((x: EmployeeTempPosMaster) => x.orgChild4Id == data4Id)
                              .map(async (item: any) => {
                                delete item.id;
                                const employeeTempPosMaster = Object.assign(
                                  new EmployeeTempPosMaster(),
                                  item,
                                );
                                employeeTempPosMaster.positions = [];
                                employeeTempPosMaster.orgRevisionId = orgRevisionPublish.id;
                                employeeTempPosMaster.orgRootId = dataId;
                                employeeTempPosMaster.orgChild1Id = data1Id;
                                employeeTempPosMaster.orgChild2Id = data2Id;
                                employeeTempPosMaster.orgChild3Id = data3Id;
                                employeeTempPosMaster.orgChild4Id = data4Id;
                                employeeTempPosMaster.createdUserId = "";
                                employeeTempPosMaster.createdFullName = "System Administrator";
                                employeeTempPosMaster.createdAt = new Date();
                                employeeTempPosMaster.lastUpdateUserId = "";
                                employeeTempPosMaster.lastUpdateFullName = "System Administrator";
                                employeeTempPosMaster.lastUpdatedAt = new Date();
                                await repoEmployeeTempPosmaster.save(employeeTempPosMaster);

                                //create employeePosition
                                item.positions.map(async (pos: any) => {
                                  delete pos.id;
                                  const employeePosition: EmployeePosition = Object.assign(
                                    new EmployeePosition(),
                                    pos,
                                  );
                                  employeePosition.posMasterTempId = employeeTempPosMaster.id;
                                  employeePosition.createdUserId = "";
                                  employeePosition.createdFullName = "System Administrator";
                                  employeePosition.createdAt = new Date();
                                  employeePosition.lastUpdateUserId = "";
                                  employeePosition.lastUpdateFullName = "System Administrator";
                                  employeePosition.lastUpdatedAt = new Date();
                                  await employeePositionRepository.save(employeePosition);
                                });
                              }),
                          );
                        });
                    });
                });
            });
        });

        const employeePosMaster = await repoEmployeePosmaster.find({
          where: { orgRevisionId: orgRevisionPublish.id },
          relations: ["positions", "positions.posLevel", "positions.posType"],
        });
        for (const item of employeePosMaster) {
          if (item.next_holderId != null) {
            const profile = await repoProfileEmployee.findOne({
              where: { id: item.next_holderId == null ? "" : item.next_holderId },
            });
            const position = await item.positions.find((x) => x.positionIsSelected == true);
            const _null: any = null;
            if (profile != null) {
              profile.posLevelId = position?.posLevelId ?? _null;
              profile.posTypeId = position?.posTypeId ?? _null;
              profile.position = position?.positionName ?? _null;
              await repoProfileEmployee.save(profile);
            }
          }
          item.lastUpdateUserId = request.user.sub;
          item.lastUpdateFullName = request.user.name;
          item.lastUpdatedAt = new Date();
        }
        const employeeTempPosMaster = await repoEmployeeTempPosmaster.find({
          where: { orgRevisionId: orgRevisionPublish.id },
          relations: ["positions", "positions.posLevel", "positions.posType"],
        });
        for (const item of employeeTempPosMaster) {
          if (item.next_holderId != null) {
            const profile = await repoProfileEmployee.findOne({
              where: { id: item.next_holderId == null ? "" : item.next_holderId },
            });
            const position = await item.positions.find((x) => x.positionIsSelected == true);
            const _null: any = null;
            if (profile != null) {
              profile.posLevelId = position?.posLevelId ?? _null;
              profile.posTypeId = position?.posTypeId ?? _null;
              profile.position = position?.positionName ?? _null;
              await repoProfileEmployee.save(profile);
            }
          }
          item.lastUpdateUserId = request.user.sub;
          item.lastUpdateFullName = request.user.name;
          item.lastUpdatedAt = new Date();

          await repoEmployeeTempPosmaster.save(item).catch((e) => console.log(e));
        }
      }
      return new HttpSuccess();
    } catch (error) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่สามารถสร้างโครงสร้างลูกจ้างได้");
    }
  }
}
