import {
  Controller,
  Post,
  Put,
  Delete,
  Route,
  Security,
  Tags,
  Body,
  Path,
  Request,
  SuccessResponse,
  Response,
  Get,
  Query,
  Example,
} from "tsoa";
import { AppDataSource } from "../database/data-source";
import HttpSuccess from "../interfaces/http-success";
import HttpStatus from "../interfaces/http-status";
import HttpError from "../interfaces/http-error";
import HttpStatusCode from "../interfaces/http-status";
import { Brackets, Double, In, IsNull, Like, Not } from "typeorm";
import { OrgRevision } from "../entities/OrgRevision";
import {
  calculateRetireDate,
  calculateRetireLaw,
  removeProfileInOrganize,
} from "../interfaces/utils";
import { EmployeePosMaster } from "../entities/EmployeePosMaster";
import {
  ProfileEmployee,
  CreateProfileEmployee,
  UpdateProfileEmployee,
  ProfileEmployeeHistory,
  UpdatePositionTempProfileEmployee,
  UpdateInformationProfileEmployee,
} from "../entities/ProfileEmployee";
import { EmployeePosLevel } from "../entities/EmployeePosLevel";
import { EmployeePosType } from "../entities/EmployeePosType";
import { RequestWithUser } from "../middlewares/user";
import { Province } from "../entities/Province";
import { District } from "../entities/District";
import { SubDistrict } from "../entities/SubDistrict";
import { ProfileCertificate } from "../entities/ProfileCertificate";
import { ProfileTraining } from "../entities/ProfileTraining";
import { ProfileDiscipline } from "../entities/ProfileDiscipline";
import { ProfileEducation } from "../entities/ProfileEducation";
import { ProfileSalary } from "../entities/ProfileSalary";
import { ProfileFamilyCouple } from "../entities/ProfileFamilyCouple";
import { ProfileFamilyMother } from "../entities/ProfileFamilyMother";
import { ProfileFamilyFather } from "../entities/ProfileFamilyFather";
import Extension from "../interfaces/extension";
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 { ProfileEmployeeInformationHistory } from "../entities/ProfileEmployeeInformationHistory";
import {
  ProfileEmployeeEmployment,
  CreateEmploymentProfileEmployee,
  UpdateEmploymentProfileEmployee,
} from "../entities/ProfileEmployeeEmployment";
import { ProfileEmployeeEmploymentHistory } from "../entities/ProfileEmployeeEmploymentHistory";
import CallAPI from "../interfaces/call-api";
import { ProfileInsignia } from "../entities/ProfileInsignia";
import { ProfileLeave } from "../entities/ProfileLeave";
import { ProfileEmployeeAbsentLate } from "../entities/ProfileEmployeeAbsentLate";
import permission from "../interfaces/permission";
import axios from "axios";
import { Position } from "../entities/Position";
import { EmployeePosition } from "../entities/EmployeePosition";
import { deleteUser } from "../keycloak";
import { PermissionProfile } from "../entities/PermissionProfile";
import { ProfileSalaryHistory } from "../entities/ProfileSalaryHistory";
import { ProfileAbility } from "../entities/ProfileAbility";
import { ProfileActposition } from "../entities/ProfileActposition";
import { ProfileAssessment } from "../entities/ProfileAssessment";
import { ProfileAssistance } from "../entities/ProfileAssistance";
import { ProfileChangeName } from "../entities/ProfileChangeName";
import { ProfileChildren } from "../entities/ProfileChildren";
import { ProfileDuty } from "../entities/ProfileDuty";
import { CreatePosMasterHistoryEmployee, getTopDegrees } from "../services/PositionService";
import { ProfileLeaveService } from "../services/ProfileLeaveService";
import { CommandCode } from "../entities/CommandCode";
import { updateHolderProfileHistory } from "../services/PositionService";
@Route("api/v1/org/profile-employee")
@Tags("ProfileEmployee")
@Security("bearerAuth")
@Response(
  HttpStatus.INTERNAL_SERVER_ERROR,
  "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง",
)
@SuccessResponse(HttpStatus.OK, "สำเร็จ")
export class ProfileEmployeeController extends Controller {
  private orgRevisionRepo = AppDataSource.getRepository(OrgRevision);
  private posMasterRepo = AppDataSource.getRepository(EmployeePosMaster);
  private profileRepo = AppDataSource.getRepository(ProfileEmployee);
  private profileHistoryRepo = AppDataSource.getRepository(ProfileEmployeeHistory);
  private posLevelRepo = AppDataSource.getRepository(EmployeePosLevel);
  private posTypeRepo = AppDataSource.getRepository(EmployeePosType);
  private provinceRepository = AppDataSource.getRepository(Province);
  private districtRepository = AppDataSource.getRepository(District);
  private subDistrict = AppDataSource.getRepository(SubDistrict);
  private certificateRepository = AppDataSource.getRepository(ProfileCertificate);
  private profileFamilyCoupleRepository = AppDataSource.getRepository(ProfileFamilyCouple);
  private profileFamilyMotherRepository = AppDataSource.getRepository(ProfileFamilyMother);
  private profileFamilyFatherRepository = AppDataSource.getRepository(ProfileFamilyFather);
  private trainingRepository = AppDataSource.getRepository(ProfileTraining);
  private disciplineRepository = AppDataSource.getRepository(ProfileDiscipline);
  private salaryRepo = AppDataSource.getRepository(ProfileSalary);
  private salaryHistoryRepo = AppDataSource.getRepository(ProfileSalaryHistory);
  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 informationHistoryRepository = AppDataSource.getRepository(
    ProfileEmployeeInformationHistory,
  );
  private employmentRepository = AppDataSource.getRepository(ProfileEmployeeEmployment);
  private employmentHistoryRepository = AppDataSource.getRepository(
    ProfileEmployeeEmploymentHistory,
  );
  private profileEducationRepo = AppDataSource.getRepository(ProfileEducation);
  private profileInsigniaRepo = AppDataSource.getRepository(ProfileInsignia);
  private profileLeaveRepository = AppDataSource.getRepository(ProfileLeave);
  private profileEmployeeAbsentLateRepo = AppDataSource.getRepository(ProfileEmployeeAbsentLate);
  private positionRepository = AppDataSource.getRepository(Position);
  private employeePositionRepository = AppDataSource.getRepository(EmployeePosition);
  private permissionProflileRepository = AppDataSource.getRepository(PermissionProfile);
  private profileChildrenRepository = AppDataSource.getRepository(ProfileChildren);
  private changeNameRepository = AppDataSource.getRepository(ProfileChangeName);
  private profileActpositionRepo = AppDataSource.getRepository(ProfileActposition);
  private dutyRepository = AppDataSource.getRepository(ProfileDuty);
  private profileAssessmentsRepository = AppDataSource.getRepository(ProfileAssessment);
  private profileAbilityRepo = AppDataSource.getRepository(ProfileAbility);
  private profileAssistanceRepository = AppDataSource.getRepository(ProfileAssistance);
  private commandCodeRepository = AppDataSource.getRepository(CommandCode);

  // Services
  private profileLeaveService = new ProfileLeaveService();

  /**
   * report ประวัติแบบย่อ ลูกจ้าง
   *
   * @summary report ประวัติแบบย่อ ลูกจ้าง
   *
   * @param {string} id  Id โปรไฟล์
   */
  @Get("kp7-short/{id}")
  async kp7ShortById(@Path() id: string, @Request() req: RequestWithUser) {
    const orgRevision = await this.orgRevisionRepo.findOne({
      where: { orgRevisionIsCurrent: true },
    });

    const profile = await this.profileRepo.findOne({
      relations: [
        "profileSalary",
        "profileEducations",
        "current_holders",
        "current_holders.orgRoot",
        "current_holders.orgChild1",
        "current_holders.orgChild2",
        "current_holders.orgChild3",
        "current_holders.orgChild4",
      ],
      where: { id: id },
      order: {
        profileSalary: {
          commandDateAffect: "DESC",
        },
      },
    });
    if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    let _workflow = await new permission().Workflow(req, id, "SYS_REGISTRY_EMP");
    if (_workflow == false && req.user.sub != profile.keycloak)
      await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_EMP", profile.id);
    let ImgUrl: any;
    if (profile?.avatar != null && profile?.avatarName != null) {
      // await new CallAPI()
      //   .GetData(req, `/salary/file/${profile?.avatar}/${profile?.avatarName}`)
      //   .then(async (x) => {
      //     ImgUrl = x.downloadUrl;
      //   })
      //   .catch();
      let req_: any = req;
      const token_ = "Bearer " + req_.headers.authorization.replace("Bearer ", "");
      const url = process.env.API_URL + `/salary/file/${profile?.avatar}/${profile?.avatarName}`;
      try {
        const response_ = await axios.get(url, {
          headers: {
            Authorization: `${token_}`,
            "Content-Type": "application/json",
            api_key: process.env.API_KEY,
          },
        });
        ImgUrl = response_.data.downloadUrl;
      } catch { }
    }
    const province = await this.provinceRepository.findOneBy({
      id: profile.registrationProvinceId,
    });
    const district = await this.districtRepository.findOneBy({
      id: profile.registrationDistrictId,
    });
    const subDistrict = await this.subDistrict.findOneBy({ id: profile.registrationSubDistrictId });

    const root =
      profile.current_holders == null ||
        profile.current_holders.length == 0 ||
        profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
        ? null
        : profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgRoot;

    const child1 =
      profile.current_holders == null ||
        profile.current_holders.length == 0 ||
        profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
        ? null
        : profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild1;

    const child2 =
      profile.current_holders == null ||
        profile.current_holders.length == 0 ||
        profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
        ? null
        : profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild2;

    const child3 =
      profile.current_holders == null ||
        profile.current_holders.length == 0 ||
        profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
        ? null
        : profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild3;

    const child4 =
      profile.current_holders == null ||
        profile.current_holders.length == 0 ||
        profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
        ? null
        : profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild4;

    let _regisAddres =
      profile && profile.registrationAddress != null ? profile.registrationAddress : "";
    let _subDistrict =
      subDistrict && subDistrict.name != null ? `\r\nตำบล/แขวง ${province?.name}` : "";
    let _district = district && district.name != null ? `\r\nเขต/อำเภอ ${district?.name}` : "";
    let _province = province && province.name != null ? `\r\nจังหวัด ${province?.name}` : "";
    let registrationZipCode =
      profile && profile.registrationZipCode != null
        ? ` รหัสไปรษณีย์ ${profile.registrationZipCode}`
        : "";

    let _root = root?.orgRootName;
    let _child1 = child1?.orgChild1Name;
    let _child2 = child2?.orgChild2Name;
    let _child3 = child3?.orgChild3Name;
    let _child4 = child4?.orgChild4Name;

    const salary_raw = await this.salaryRepo.find({
      //   select: [
      //     "commandDateAffect",
      //     "posNo",
      //     "positionType",
      //     "positionLevel",
      //     "positionSalaryAmount",
      //     "commandNo",
      //     "amount",
      //     "remark",
      //     "positionName",
      //     "orgRoot",
      //     "orgChild1",
      //     "orgChild2",
      //     "orgChild3",
      //     "orgChild4",
      //     "positionCee",
      //     "positionExecutive",
      //   ],
      where: {
        profileEmployeeId: id,
        commandCode: In(["1", "2", "3", "4", "8", "10", "11", "12", "15", "16", "20"]),
      },
      order: { order: "ASC" },
    });
    const salarys =
      salary_raw.length > 1
        ? salary_raw.slice(1).map((item) => ({
          date: item.commandDateAffect
            ? Extension.ToThaiNumber(Extension.ToThaiShortDate(item.commandDateAffect))
            : null,
          position: Extension.ToThaiNumber(
            Extension.ToThaiNumber(
              `${item.positionName != null ? item.positionName : "-"} ${item.positionType == null ? item.positionCee ?? "" : (item.positionType == "อำนวยการ" || item.positionType == "บริหาร" ? item.positionType : "") + item.positionLevel}`,
            ),
          ),
          posNo: item.posNo != null ? Extension.ToThaiNumber(item.posNo) : "",
          orgRoot: item.orgRoot != null ? Extension.ToThaiNumber(item.orgRoot) : "",
          orgChild1: item.orgChild1 != null ? Extension.ToThaiNumber(item.orgChild1) : "",
          orgChild2: item.orgChild2 != null ? Extension.ToThaiNumber(item.orgChild2) : "",
          orgChild3: item.orgChild3 != null ? Extension.ToThaiNumber(item.orgChild3) : "",
          orgChild4: item.orgChild4 != null ? Extension.ToThaiNumber(item.orgChild4) : "",
          positionCee: item.positionCee != null ? Extension.ToThaiNumber(item.positionCee) : "",
          positionExecutive:
            item.positionExecutive != null ? Extension.ToThaiNumber(item.positionExecutive) : "",
        }))
        : [
          {
            date: "-",
            position: "-",
            posNo: "-",
            orgRoot: null,
            orgChild1: null,
            orgChild2: null,
            orgChild3: null,
            orgChild4: null,
            positionCee: null,
            positionExecutive: null,
          },
        ];

    const educations = await this.profileEducationRepo.find({
      select: [
        "startDate",
        "endDate",
        "educationLevel",
        "degree",
        "field",
        "institute",
        "isDeleted",
      ],
      where: { profileEmployeeId: id, isDeleted: false },
      order: { level: "ASC" },
    });
    const Education =
      educations && educations.length > 0
        ? educations.map((item) => ({
          institute: item.institute ? item.institute : "-",
          date:
            item.startDate && item.endDate
              ? `${Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.startDate))} - ${Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.endDate))}`
              : "-",
          degree: item.degree && item.field ? `${item.degree} ${item.field}` : "-",
        }))
        : [
          {
            institute: "-",
            date: "-",
            degree: "-",
          },
        ];

    const mapData = {
      // Id: profile.id,
      fullName: `${profile?.prefix}${profile?.firstName} ${profile?.lastName}`,
      prefix: profile.prefix != null ? profile.prefix : null,
      firstName: profile.firstName != null ? profile.firstName : null,
      lastName: profile.lastName != null ? profile.lastName : null,
      citizenId: profile.citizenId != null ? Extension.ToThaiNumber(profile.citizenId) : "",
      dateOfBirth:
        profile.birthDate != null
          ? Extension.ToThaiNumber(Extension.ToThaiShortDate_monthYear2(profile.birthDate))
          : "",
      dateRetire:
        profile.dateRetire != null
          ? Extension.ToThaiNumber(Extension.ToThaiShortDate_monthYear2(profile.dateRetire))
          : "",
      salaryAmount:
        profile.amount != null ? Extension.ToThaiNumber(profile.amount.toLocaleString()) : "",
      registrationAddress: Extension.ToThaiNumber(
        `${_regisAddres}${_subDistrict}${_district}${_province}${registrationZipCode}`,
      ),
      date:
        salary_raw.length > 0 && salary_raw[0].commandDateAffect != null
          ? Extension.ToThaiNumber(Extension.ToThaiShortDate(salary_raw[0].commandDateAffect))
          : "",
      positionName: profile.position != null ? profile.position : "",
      appointText:
        profile.dateAppoint != null
          ? Extension.ToThaiNumber(Extension.ToThaiShortDate_monthYear(profile.dateAppoint))
          : "",
      posNo:
        salary_raw.length > 0 && salary_raw[0].posNo != null
          ? Extension.ToThaiNumber(Extension.ToThaiNumber(salary_raw[0].posNo))
          : "",
      position:
        salary_raw.length > 0 && salary_raw[0].positionName != null
          ? Extension.ToThaiNumber(
            Extension.ToThaiNumber(
              `${salary_raw[0].positionName != null ? salary_raw[0].positionName : "-"} ${salary_raw[0].positionType == null ? salary_raw[0].positionCee ?? "" : (salary_raw[0].positionType == "อำนวยการ" || salary_raw[0].positionType == "บริหาร" ? salary_raw[0].positionType : "") + salary_raw[0].positionLevel}`,
            ),
          )
          : "",
      positionCee:
        salary_raw.length > 0 && salary_raw[0].positionCee != null
          ? Extension.ToThaiNumber(Extension.ToThaiNumber(salary_raw[0].positionCee))
          : "",
      positionExecutive:
        salary_raw.length > 0 && salary_raw[0].positionExecutive != null
          ? Extension.ToThaiNumber(Extension.ToThaiNumber(salary_raw[0].positionExecutive))
          : "",
      org: `${salary_raw.length > 0 && salary_raw[0].orgChild4 && salary_raw[0].orgChild4 != "-"
          ? Extension.ToThaiNumber(Extension.ToThaiNumber(salary_raw[0].orgChild4)) + " "
          : ""
        }${salary_raw.length > 0 && salary_raw[0].orgChild3 && salary_raw[0].orgChild3 != "-"
          ? Extension.ToThaiNumber(Extension.ToThaiNumber(salary_raw[0].orgChild3)) + " "
          : ""
        }${salary_raw.length > 0 && salary_raw[0].orgChild2 && salary_raw[0].orgChild2 != "-"
          ? Extension.ToThaiNumber(Extension.ToThaiNumber(salary_raw[0].orgChild2)) + " "
          : ""
        }${salary_raw.length > 0 && salary_raw[0].orgChild1 && salary_raw[0].orgChild1 != "-"
          ? Extension.ToThaiNumber(Extension.ToThaiNumber(salary_raw[0].orgChild1)) + " "
          : ""
        }${salary_raw.length > 0 && salary_raw[0].orgRoot && salary_raw[0].orgRoot != "-"
          ? Extension.ToThaiNumber(Extension.ToThaiNumber(salary_raw[0].orgRoot))
          : ""
        }`,
      ocFullPath:
        (_child4 == null ? "" : _child4 + "\n") +
        (_child3 == null ? "" : _child3 + "\n") +
        (_child2 == null ? "" : _child2 + "\n") +
        (_child1 == null ? "" : _child1 + "\n") +
        (_root == null ? "" : _root),
      educations: Education,
      salarys: salarys.map((item) => {
        return {
          ...item,
          org: `${item.orgChild4 && item.orgChild4 != "-" ? item.orgChild4 + " " : ""}${item.orgChild3 && item.orgChild3 != "-" ? item.orgChild3 + " " : ""}${item.orgChild2 && item.orgChild2 != "-" ? item.orgChild2 + " " : ""}${item.orgChild1 && item.orgChild1 != "-" ? item.orgChild1 + " " : ""}${item.orgRoot && item.orgRoot != "-" ? item.orgRoot + " " : ""}`,
        };
      }),
      url: ImgUrl ? ImgUrl : `${process.env.VITE_URL_MGT}`,
    };

    return new HttpSuccess({
      template: "kp7",
      reportName: "docx-report",
      data: mapData,
    });
  }

  /**
   * รายงาน ก.ก.1 (ลูกจ้างประจำ)
   *
   * @summary รายงาน ก.ก.1 (ลูกจ้างประจำ)
   *
   * @param {string} id  Id โปรไฟล์
   */
  @Get("old/{id}")
  public async getKk1Employee(@Path() id: string, @Request() req: RequestWithUser) {
    const profiles = await this.profileRepo.findOne({
      relations: ["currentSubDistrict", "currentDistrict", "currentProvince", "profileAvatars"],
      order: {
        profileAvatars: { createdAt: "ASC" },
      },
      where: { id: id },
    });
    if (!profiles) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    let ImgUrl: any = null;
    let _ImgUrl: any = [];
    if (profiles?.avatar != null && profiles?.avatarName != null) {
      // await new CallAPI()
      //   .GetData(req, `/salary/file/${profiles?.avatar}/${profiles?.avatarName}`)
      //   .then(async (x) => {
      //     ImgUrl = x.downloadUrl;
      //   })
      //   .catch();

      let req_: any = req;
      const token_ = "Bearer " + req_.headers.authorization.replace("Bearer ", "");

      await Promise.all(
        await profiles.profileAvatars.slice(-7).map(async (x, i) => {
          if (x == null) {
            _ImgUrl[i] = null;
          } else {
            const url = process.env.API_URL + `/salary/file/${x?.avatar}/${x?.avatarName}`;
            try {
              const response_ = await axios.get(url, {
                headers: {
                  Authorization: `${token_}`,
                  "Content-Type": "application/json",
                  api_key: process.env.API_KEY,
                },
              });
              _ImgUrl[i] = response_.data.downloadUrl;
            } catch { }
          }
        }),
      );
      const url = process.env.API_URL + `/salary/file/${profiles?.avatar}/${profiles?.avatarName}`;
      try {
        const response_ = await axios.get(url, {
          headers: {
            Authorization: `${token_}`,
            "Content-Type": "application/json",
            api_key: process.env.API_KEY,
          },
        });
        ImgUrl = response_.data.downloadUrl;
      } catch { }
    }
    const profileOc = await this.profileRepo.findOne({
      relations: [
        "current_holders",
        "current_holders.orgRoot",
        "current_holders.orgChild1",
        "current_holders.orgChild2",
        "current_holders.orgChild3",
        "current_holders.orgChild4",
      ],
      where: { id: id },
    });
    if (!profileOc) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");

    const orgRevision = await this.orgRevisionRepo.findOne({
      where: { orgRevisionIsCurrent: true },
    });

    const profileFamilyCouple = await this.profileFamilyCoupleRepository.findOne({
      where: { profileEmployeeId: id },
      select: ["couplePrefix", "coupleFirstName", "coupleLastName", "coupleLastNameOld"],
      order: { lastUpdatedAt: "DESC" },
    });

    const profileFamilyMother = await this.profileFamilyMotherRepository.findOne({
      where: { profileEmployeeId: id },
      select: ["motherPrefix", "motherFirstName", "motherLastName"],
      order: { lastUpdatedAt: "DESC" },
    });

    const profileFamilyFather = await this.profileFamilyFatherRepository.findOne({
      where: { profileEmployeeId: id },
      select: ["fatherPrefix", "fatherFirstName", "fatherLastName"],
      order: { lastUpdatedAt: "DESC" },
    });

    const root =
      profileOc.current_holders == null ||
        profileOc.current_holders.length == 0 ||
        profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
        ? null
        : profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgRoot;

    const child1 =
      profileOc.current_holders == null ||
        profileOc.current_holders.length == 0 ||
        profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
        ? null
        : profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild1;

    const child2 =
      profileOc.current_holders == null ||
        profileOc.current_holders.length == 0 ||
        profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
        ? null
        : profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild2;

    const child3 =
      profileOc.current_holders == null ||
        profileOc.current_holders.length == 0 ||
        profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
        ? null
        : profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild3;

    const child4 =
      profileOc.current_holders == null ||
        profileOc.current_holders.length == 0 ||
        profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
        ? null
        : profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild4;

    // Construct org path
    let _root = root?.orgRootName;
    let _child1 = child1?.orgChild1Name;
    let _child2 = child2?.orgChild2Name;
    let _child3 = child3?.orgChild3Name;
    let _child4 = child4?.orgChild4Name;

    const cert_raw = await this.certificateRepository.find({
      select: ["certificateType", "issuer", "certificateNo", "issueDate", "isDeleted"],
      where: { profileEmployeeId: id, isDeleted: false },
      order: { createdAt: "ASC" },
    });
    const certs =
      cert_raw.length > 0
        ? cert_raw.slice(-2).map((item) => ({
          CertificateType: item.certificateType ?? null,
          Issuer: item.issuer ?? null,
          CertificateNo: Extension.ToThaiNumber(item.certificateNo) ?? null,
          IssueDate: Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.issueDate)) ?? null,
        }))
        : [
          {
            CertificateType: "-",
            Issuer: "-",
            CertificateNo: "-",
            IssueDate: "-",
          },
        ];
    const training_raw = await this.trainingRepository.find({
      select: ["startDate", "endDate", "place", "department", "isDeleted"],
      where: { profileEmployeeId: id, isDeleted: false },
      order: { createdAt: "ASC" },
    });
    const trainings =
      training_raw.length > 0
        ? training_raw.slice(-2).map((item) => ({
          Institute: item.department ?? "",
          Start:
            item.startDate == null
              ? ""
              : Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.startDate)),
          End:
            item.endDate == null
              ? ""
              : Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.endDate)),
          Date:
            item.startDate && item.endDate
              ? `${Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.startDate))} - ${Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.endDate))}`
              : "",
          Level: "",
          Degree: item.name,
          Field: "",
        }))
        : [
          {
            Institute: "-",
            Start: "-",
            End: "-",
            Date: "-",
            Level: "-",
            Degree: "-",
            Field: "-",
          },
        ];

    const discipline_raw = await this.disciplineRepository.find({
      select: ["refCommandDate", "refCommandNo", "detail", "isDeleted"],
      where: { profileEmployeeId: id, isDeleted: false },
      order: { createdAt: "ASC" },
    });
    const disciplines =
      discipline_raw.length > 0
        ? discipline_raw.slice(-2).map((item) => ({
          DisciplineYear:
            Extension.ToThaiNumber(new Date(item.refCommandDate).getFullYear().toString()) ??
            null,
          DisciplineDetail: item.detail ?? null,
          RefNo: item.refCommandNo ? Extension.ToThaiNumber(item.refCommandNo) : null,
        }))
        : [
          {
            DisciplineYear: "-",
            DisciplineDetail: "-",
            RefNo: "-",
          },
        ];

    const education_raw = await this.profileEducationRepo.find({
      select: [
        "startDate",
        "endDate",
        "educationLevel",
        "degree",
        "field",
        "institute",
        "isDeleted",
      ],
      where: { profileEmployeeId: id, isDeleted: false },
      // order: { lastUpdatedAt: "DESC" },
      order: { level: "ASC" },
    });
    const educations =
      education_raw.length > 0
        ? education_raw.slice(-2).map((item) => ({
          Institute: item.institute,
          Start:
            item.startDate == null
              ? ""
              : Extension.ToThaiNumber(new Date(item.startDate).getFullYear().toString()),
          End:
            item.endDate == null
              ? ""
              : Extension.ToThaiNumber(new Date(item.endDate).getFullYear().toString()),
          Date:
            item.startDate && item.endDate
              ? `${Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.startDate))} - ${Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.endDate))}`
              : "",
          Level: item.educationLevel ?? "",
          Degree: item.degree ? `${item.degree} ${item.field ? item.field : ""}` : "",
          Field: item.field ?? "-",
        }))
        : [
          {
            Institute: "-",
            Start: "-",
            End: "-",
            Date: "-",
            Level: "-",
            Degree: "-",
            Field: "-",
          },
        ];
    const salary_raw = await this.salaryRepo.find({
      select: [
        "commandDateAffect",
        "positionName",
        "posNo",
        "positionType",
        "positionLevel",
        "positionSalaryAmount",
        "commandNo",
        "amount",
        "remark",
      ],
      where: { profileEmployeeId: id },
      order: { order: "ASC" },
    });

    const salarys =
      salary_raw.length > 0
        ? salary_raw.map((item) => ({
          SalaryDate: item.commandDateAffect
            ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.commandDateAffect))
            : null,
          Position: item.positionName != null ? Extension.ToThaiNumber(item.positionName) : null,
          PosNo: item.posNo != null ? Extension.ToThaiNumber(item.posNo) : null,
          Salary:
            item.amount != null ? Extension.ToThaiNumber(item.amount.toLocaleString()) : null,
          Rank: item.positionLevel != null ? Extension.ToThaiNumber(item.positionLevel) : null,
          RefAll: item.remark ? Extension.ToThaiNumber(item.remark) : null,
          PositionLevel:
            item.positionLevel != null ? Extension.ToThaiNumber(item.positionLevel) : null,
          PositionType: item.positionType ?? null,
          PositionAmount:
            item.positionSalaryAmount == null
              ? null
              : Extension.ToThaiNumber(item.positionSalaryAmount.toLocaleString()),
          FullName: `${profiles?.prefix}${profiles?.firstName} ${profiles?.lastName}`,
          OcFullPath:
            (_child4 == null ? "" : _child4 + "\n") +
            (_child3 == null ? "" : _child3 + "\n") +
            (_child2 == null ? "" : _child2 + "\n") +
            (_child1 == null ? "" : _child1 + "\n") +
            (_root == null ? "" : _root),
        }))
        : [
          {
            SalaryDate: "-",
            Position: "-",
            PosNo: "-",
            Salary: "-",
            Rank: "-",
            RefAll: "-",
            PositionLevel: "-",
            PositionType: "-",
            PositionAmount: "-",
            FullName: "-",
            OcFullPath: "-",
          },
        ];

    const insignia_raw = await this.profileInsigniaRepo.find({
      relations: {
        insignia: {
          insigniaType: true,
        },
      },
      where: { profileEmployeeId: id, isDeleted: false },
      order: { receiveDate: "ASC" },
    });
    const insignias =
      insignia_raw.length > 0
        ? insignia_raw.map((item) => ({
          ReceiveDate: item.receiveDate
            ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.receiveDate))
            : "",
          InsigniaName: item.insignia.name,
          InsigniaShortName: item.insignia.shortName,
          InsigniaTypeName: item.insignia.insigniaType.name,
          No: item.no ? Extension.ToThaiNumber(item.no) : "",
          Issue: item.issue ? item.issue : "",
          VolumeNo: item.volumeNo ? Extension.ToThaiNumber(item.volumeNo) : "",
          Volume: item.volume ? Extension.ToThaiNumber(item.volume) : "",
          Section: item.section ? Extension.ToThaiNumber(item.section) : "",
          Page: item.page ? Extension.ToThaiNumber(item.page) : "",
          RefCommandDate: item.refCommandDate
            ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.refCommandDate))
            : "",
        }))
        : [
          {
            ReceiveDate: "-",
            InsigniaName: "-",
            InsigniaShortName: "-",
            InsigniaTypeName: "-",
            No: "-",
            Issue: "-",
            VolumeNo: "-",
            Volume: "-",
            Section: "-",
            Page: "-",
            RefCommandDate: "-",
          },
        ];

    const leave_raw = await this.profileLeaveRepository
      .createQueryBuilder("profileLeave")
      .leftJoinAndSelect("profileLeave.leaveType", "leaveType")
      .select([
        "profileLeave.isDeleted",
        "profileLeave.leaveTypeId",
        "leaveType.name as name",
        "leaveType.code as code",
        "profileLeave.status",
        "profileLeave.profileEmployeeId",
        "MAX(profileLeave.dateLeaveStart) as maxDateLeaveStart",
      ])
      .addSelect("SUM(profileLeave.leaveDays)", "totalLeaveDays")
      .where("profileLeave.profileEmployeeId = :profileId", { profileId: id })
      .andWhere("profileLeave.isDeleted = :isDeleted", { isDeleted: false })
      .andWhere("profileLeave.status = :status", { status: "approve" })
      .groupBy("profileLeave.leaveTypeId")
      .orderBy("code", "ASC")
      .addOrderBy("maxDateLeaveStart", "ASC")
      .getRawMany();

    const leaves: any[] = [];

    leave_raw.forEach((item) => {
      const leaveTypeCode = item.code ? item.code.trim().toUpperCase() : "";
      if (leaveTypeCode.startsWith("LV-")) {
        const lvIndex = parseInt(leaveTypeCode.split("-")[1], 10);

        if (lvIndex >= 1 && lvIndex <= 11) {
          const leaveTypeCodeKey = `leaveTypeCodeLv${lvIndex}`;
          const totalLeaveDaysKey = `totalLeaveDaysLv${lvIndex}`;
          const leaveTypeNameKey = `leaveTypeNameLv${lvIndex}`;

          const leaveDate = item.maxDateLeaveStart ? new Date(item.maxDateLeaveStart) : null;
          const year = leaveDate
            ? Extension.ToThaiNumber(Extension.ToThaiShortYear(leaveDate))
            : "";

          let yearData = leaves.find((data) => data.year === year);
          if (!yearData) {
            yearData = { year };

            for (let i = 1; i <= 11; i++) {
              yearData[`leaveTypeCodeLv${i}`] = "-";
              yearData[`totalLeaveDaysLv${i}`] = "-";
              yearData[`leaveTypeNameLv${i}`] = "-";
            }

            leaves.push(yearData);
          }

          yearData[leaveTypeCodeKey] = item.code ? item.code : "-";
          yearData[totalLeaveDaysKey] = item.totalLeaveDays
            ? Extension.ToThaiNumber(item.totalLeaveDays.toString())
            : "-";
          yearData[leaveTypeNameKey] = item.name ? item.name : "-";
        }
      }
    });

    // กรองเอา object ที่ไม่มี year ออก
    const filteredLeaves = leaves.filter((item) => item.year && item.year !== "");

    const data = {
      fullName: `${profiles?.prefix}${profiles?.firstName} ${profiles?.lastName}`,
      prefix: profiles?.prefix != null ? profiles.prefix : "",
      firstName: profiles?.firstName != null ? profiles.firstName : "",
      lastName: profiles?.lastName != null ? profiles.lastName : "",
      ocFullPath:
        (_child4 == null ? "" : _child4 + "\n") +
        (_child3 == null ? "" : _child3 + "\n") +
        (_child2 == null ? "" : _child2 + "\n") +
        (_child1 == null ? "" : _child1 + "\n") +
        (_root == null ? "" : _root),
      birthDate: profiles?.birthDate
        ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(profiles.birthDate))
        : "",
      retireDate:
        profiles.dateRetireLaw != null
          ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(profiles.dateRetireLaw))
          : "",
      appointDate: profiles?.dateAppoint
        ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(profiles.dateAppoint))
        : "",
      citizenId:
        profiles.citizenId != null ? Extension.ToThaiNumber(profiles.citizenId.toString()) : "",
      fatherFullName:
        profileFamilyFather?.fatherPrefix ||
          profileFamilyFather?.fatherFirstName ||
          profileFamilyFather?.fatherLastName
          ? `${profileFamilyFather?.fatherPrefix ?? ""}${profileFamilyFather?.fatherFirstName ?? ""} ${profileFamilyFather?.fatherLastName ?? ""}`.trim()
          : null,
      motherFullName:
        profileFamilyMother?.motherPrefix ||
          profileFamilyMother?.motherFirstName ||
          profileFamilyMother?.motherLastName
          ? `${profileFamilyMother?.motherPrefix ?? ""}${profileFamilyMother?.motherFirstName ?? ""} ${profileFamilyMother?.motherLastName ?? ""}`.trim()
          : null,
      coupleFullName:
        profileFamilyCouple?.couplePrefix ||
          profileFamilyCouple?.coupleFirstName ||
          profileFamilyCouple?.coupleLastNameOld
          ? `${profileFamilyCouple?.couplePrefix ?? ""}${profileFamilyCouple?.coupleFirstName ?? ""} ${profileFamilyCouple?.coupleLastName ?? ""}`.trim()
          : null,
      coupleLastNameOld: profileFamilyCouple?.coupleLastNameOld ?? null,
      currentAddress:
        profiles.currentAddress != null ? Extension.ToThaiNumber(profiles.currentAddress) : "",
      currentSubDistrict:
        profiles.currentSubDistrict != null
          ? Extension.ToThaiNumber(profiles.currentSubDistrict.name)
          : "",
      currentDistrict:
        profiles.currentDistrict != null
          ? Extension.ToThaiNumber(profiles.currentDistrict.name)
          : "",
      currentProvince:
        profiles.currentProvince != null
          ? Extension.ToThaiNumber(profiles.currentProvince.name)
          : "",
      telephone: profiles.telephoneNumber != null ? Extension.ToThaiNumber(profiles.phone) : "",
      url: ImgUrl ? ImgUrl : `${process.env.VITE_URL_MGT}`,
      url1: _ImgUrl[0] ? _ImgUrl[0] : null,
      yearUpload1: profiles.profileAvatars[0]
        ? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[0].createdAt))
        : null,
      url2: _ImgUrl[1] ? _ImgUrl[1] : null,
      yearUpload2: profiles.profileAvatars[1]
        ? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[1].createdAt))
        : null,
      url3: _ImgUrl[2] ? _ImgUrl[2] : null,
      yearUpload3: profiles.profileAvatars[2]
        ? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[2].createdAt))
        : null,
      url4: _ImgUrl[3] ? _ImgUrl[3] : null,
      yearUpload4: profiles.profileAvatars[3]
        ? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[3].createdAt))
        : null,
      url5: _ImgUrl[4] ? _ImgUrl[4] : null,
      yearUpload5: profiles.profileAvatars[4]
        ? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[4].createdAt))
        : null,
      url6: _ImgUrl[5] ? _ImgUrl[5] : null,
      yearUpload6: profiles.profileAvatars[5]
        ? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[5].createdAt))
        : null,
      url7: _ImgUrl[6] ? _ImgUrl[6] : null,
      yearUpload7: profiles.profileAvatars[6]
        ? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[6].createdAt))
        : null,
      insignias,
      leaves: filteredLeaves,
      certs,
      trainings,
      disciplines,
      educations,
      salarys,
    };

    return new HttpSuccess({
      template: "kk1-emp",
      reportName: "docx-report",
      data: data,
    });
  }

  /**
   * รายงาน ก.ก.1 (ลูกจ้างประจำ) ใหม่
   *
   * @summary รายงาน ก.ก.1 (ลูกจ้างประจำ) ใหม่
   *
   * @param {string} id  Id โปรไฟล์
   */
  @Get("kk1/{id}")
  public async getKk1new(@Path() id: string, @Request() req: RequestWithUser) {
    const profiles = await this.profileRepo.findOne({
      relations: [
        "posType",
        "posLevel",
        "currentSubDistrict",
        "currentDistrict",
        "currentProvince",
        "registrationSubDistrict",
        "registrationDistrict",
        "registrationProvince",
        "profileAvatars",
        "current_holders",
        "current_holders.orgRoot",
        "current_holders.orgChild1",
        "current_holders.orgChild2",
        "current_holders.orgChild3",
        "current_holders.orgChild4",
      ],
      order: {
        profileAvatars: { createdAt: "ASC" },
      },
      where: { id: id },
    });
    if (!profiles) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    let ImgUrl: any = null;
    let _ImgUrl: any = [];
    if (profiles?.avatar != null && profiles?.avatarName != null) {
      let req_: any = req;
      const token_ = "Bearer " + req_.headers.authorization.replace("Bearer ", "");

      await Promise.all(
        await profiles.profileAvatars.slice(-7).map(async (x, i) => {
          if (x == null) {
            _ImgUrl[i] = null;
          } else {
            const url = process.env.API_URL + `/salary/file/${x?.avatar}/${x?.avatarName}`;
            try {
              const response_ = await axios.get(url, {
                headers: {
                  Authorization: `${token_}`,
                  "Content-Type": "application/json",
                  api_key: process.env.API_KEY,
                },
              });
              _ImgUrl[i] = response_.data.downloadUrl;
            } catch { }
          }
        }),
      );
      const url = process.env.API_URL + `/salary/file/${profiles?.avatar}/${profiles?.avatarName}`;
      try {
        const response_ = await axios.get(url, {
          headers: {
            Authorization: `${token_}`,
            "Content-Type": "application/json",
            api_key: process.env.API_KEY,
          },
        });
        ImgUrl = response_.data.downloadUrl;
      } catch { }
    }

    const orgRevision = await this.orgRevisionRepo.findOne({
      where: { orgRevisionIsCurrent: true },
    });

    const profileFamilyCouple = await this.profileFamilyCoupleRepository.findOne({
      where: { profileEmployeeId: id },
      select: ["couplePrefix", "coupleFirstName", "coupleLastName", "coupleLastNameOld"],
      order: { lastUpdatedAt: "DESC" },
    });

    const profileFamilyMother = await this.profileFamilyMotherRepository.findOne({
      where: { profileEmployeeId: id },
      select: ["motherPrefix", "motherFirstName", "motherLastName"],
      order: { lastUpdatedAt: "DESC" },
    });

    const profileFamilyFather = await this.profileFamilyFatherRepository.findOne({
      where: { profileEmployeeId: id },
      select: ["fatherPrefix", "fatherFirstName", "fatherLastName"],
      order: { lastUpdatedAt: "DESC" },
    });

    // const posMasterId =
    //   profiles.current_holders == null ||
    //   profiles.current_holders.length == 0 ||
    //   profiles.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
    //     ? null
    //     : profiles.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.id;

    const root =
      profiles.current_holders == null ||
        profiles.current_holders.length == 0 ||
        profiles.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
        ? null
        : profiles.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgRoot;

    const child1 =
      profiles.current_holders == null ||
        profiles.current_holders.length == 0 ||
        profiles.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
        ? null
        : profiles.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild1;

    const child2 =
      profiles.current_holders == null ||
        profiles.current_holders.length == 0 ||
        profiles.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
        ? null
        : profiles.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild2;

    const child3 =
      profiles.current_holders == null ||
        profiles.current_holders.length == 0 ||
        profiles.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
        ? null
        : profiles.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild3;

    const child4 =
      profiles.current_holders == null ||
        profiles.current_holders.length == 0 ||
        profiles.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
        ? null
        : profiles.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild4;

    // Construct org path
    let _root = root?.orgRootName;
    let _child1 = child1?.orgChild1Name;
    let _child2 = child2?.orgChild2Name;
    let _child3 = child3?.orgChild3Name;
    let _child4 = child4?.orgChild4Name;

    const cert_raw = await this.certificateRepository.find({
      select: [
        "certificateType",
        "issuer",
        "certificateNo",
        "issueDate",
        "expireDate",
        "isDeleted",
      ],
      where: { profileEmployeeId: id, isDeleted: false },
      order: { createdAt: "ASC" },
    });
    const certs =
      cert_raw.length > 0
        ? cert_raw.map((item) => ({
          certificateType: item.certificateType ?? null,
          issuer: item.issuer ?? null,
          certificateNo: item.certificateNo ? Extension.ToThaiNumber(item.certificateNo) : null,
          detail: Extension.ToThaiNumber(
            `${item.issuer ?? ""} ${item.certificateNo ?? ""}`.trim(),
          ),
          issueToExpireDate: item.issueDate
            ? item.expireDate
              ? Extension.ToThaiNumber(
                `${Extension.ToThaiFullDate2(item.issueDate)} - ${Extension.ToThaiFullDate2(item.expireDate)}`,
              )
              : Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.issueDate))
            : item.expireDate
              ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.expireDate))
              : "",
        }))
        : [
          {
            certificateType: "",
            issuer: "",
            certificateNo: "",
            detail: "",
            issueToExpireDate: "",
          },
        ];
    const training_raw = await this.trainingRepository.find({
      select: ["place", "department", "name", "duration", "isDeleted", "startDate", "endDate"],
      where: { profileEmployeeId: id, isDeleted: false },
      order: { createdAt: "ASC" },
    });
    const trainings =
      training_raw.length > 0
        ? training_raw.map((item) => ({
          institute: item.department ?? "",
          degree: item.name ? Extension.ToThaiNumber(item.name) : "",
          place: item.place ? Extension.ToThaiNumber(item.place) : "",
          duration: item.duration ? Extension.ToThaiNumber(item.duration) : "",
          date: Extension.ToThaiNumber(
            `${Extension.ToThaiFullDate2(item.startDate)} - ${Extension.ToThaiFullDate2(item.endDate)}`,
          ),
        }))
        : [
          {
            institute: "",
            degree: "",
            place: "",
            duration: "",
            date: "",
          },
        ];

    const discipline_raw = await this.disciplineRepository.find({
      select: ["refCommandDate", "refCommandNo", "detail", "level", "isDeleted"],
      where: { profileEmployeeId: id, isDeleted: false },
      order: { createdAt: "ASC" },
    });
    const disciplines =
      discipline_raw.length > 0
        ? discipline_raw.map((item) => ({
          disciplineYear: item.refCommandDate
            ? Extension.ToThaiNumber(Extension.ToThaiShortYear(new Date(item.refCommandDate)))
            : null,
          disciplineDetail: item.detail ?? null,
          refNo: Extension.ToThaiNumber(item.refCommandNo) ?? null,
          level: item.level ?? "",
        }))
        : [
          {
            disciplineYear: "",
            disciplineDetail: "",
            refNo: "",
            level: "",
          },
        ];

    const education_raw = await this.profileEducationRepo
      .createQueryBuilder("education")
      .where("education.profileEmployeeId = :profileId", { profileId: id })
      .andWhere("education.isDeleted = :isDeleted", { isDeleted: false })
      .orderBy("CASE WHEN education.isEducation = true THEN 1 ELSE 2 END", "ASC")
      .addOrderBy("education.level", "ASC")
      .getMany();
    const educations =
      education_raw.length > 0
        ? education_raw.map((item) => ({
          institute: item.institute,
          date: item.isDate
            ? `${item.startDate ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.startDate)) : ""} - ${item.endDate ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.endDate)) : ""}`
            : `${item.startDate ? Extension.ToThaiNumber(Extension.ToThaiShortYear(new Date(item.startDate))) : ""} - ${item.endDate ? Extension.ToThaiNumber(Extension.ToThaiShortYear(new Date(item.endDate))) : ""}`,
          degree: `${item.degree ?? ""} ${item.field ?? ""}`.trim(),
          level: item.educationLevel,
        }))
        : [
          {
            institute: "",
            date: "",
            degree: "",
            level: "",
          },
        ];
    const salary_raw = await this.salaryRepo.find({
      select: [
        "commandName",
        "commandDateAffect",
        "positionName",
        "posNoAbb",
        "posNo",
        "amount",
        "amountSpecial",
        "positionLevel",
        "positionCee",
        "remark",
        "positionType",
        "positionSalaryAmount",
        "order",
      ],
      where: {
        profileEmployeeId: id,
        commandCode: In(["5", "6"]),
        // isEntry: false,
      },
      order: { order: "ASC" },
    });

    const salarys =
      salary_raw.length > 0
        ? salary_raw.map((item) => ({
          commandName: item.commandName ?? "",
          salaryDate: item.commandDateAffect
            ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.commandDateAffect))
            : null,
          position: item.positionName != null ? Extension.ToThaiNumber(item.positionName) : null,
          posNo:
            item.posNoAbb && item.posNo
              ? Extension.ToThaiNumber(`${item.posNoAbb}${item.posNo}`)
              : null,
          salary:
            item.amount != null ? Extension.ToThaiNumber(item.amount.toLocaleString()) : null,
          special:
            item.amountSpecial != null
              ? Extension.ToThaiNumber(item.amountSpecial.toLocaleString())
              : null,
          rank: item.positionLevel != null ? Extension.ToThaiNumber(item.positionLevel) : null,
          refAll: item.remark ? Extension.ToThaiNumber(item.remark) : null,
          positionLevel: item.positionLevel
            ? Extension.ToThaiNumber(item.positionLevel)
            : item.positionCee
              ? Extension.ToThaiNumber(item.positionCee)
              : null,
          positionType: item.positionType ?? null,
          positionAmount:
            item.positionSalaryAmount == null
              ? null
              : Extension.ToThaiNumber(item.positionSalaryAmount.toLocaleString()),
          fullName: `${profiles?.prefix}${profiles?.firstName} ${profiles?.lastName}`,
          ocFullPath:
            (_child4 == null ? "" : _child4 + "\n") +
            (_child3 == null ? "" : _child3 + "\n") +
            (_child2 == null ? "" : _child2 + "\n") +
            (_child1 == null ? "" : _child1 + "\n") +
            (_root == null ? "" : _root),
        }))
        : [
          {
            commandName: "",
            salaryDate: "",
            position: "",
            posNo: "",
            salary: "",
            special: "",
            rank: "",
            refAll: "",
            positionLevel: "",
            positionType: "",
            positionAmount: "",
            fullName: "",
            ocFullPath: "",
          },
        ];

    const insignia_raw = await this.profileInsigniaRepo.find({
      select: [
        "receiveDate",
        "no",
        "issue",
        "volumeNo",
        "volume",
        "section",
        "page",
        "refCommandDate",
        "note",
        "isDeleted",
      ],
      relations: {
        insignia: {
          insigniaType: true,
        },
      },
      where: { profileEmployeeId: id, isDeleted: false },
      order: { receiveDate: "ASC" },
    });
    const insignias =
      insignia_raw.length > 0
        ? insignia_raw.map((item) => ({
          receiveDate: item.receiveDate
            ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.receiveDate))
            : "",
          insigniaName: item.insignia?.name ?? "",
          insigniaShortName: item.insignia?.shortName ?? "",
          insigniaTypeName: item.insignia?.insigniaType?.name ?? "",
          no: item.no ? Extension.ToThaiNumber(item.no) : "",
          issue: item.issue ? Extension.ToThaiNumber(item.issue) : "",
          volumeNo: item.volumeNo ? Extension.ToThaiNumber(item.volumeNo) : "",
          volume: item.volume ? Extension.ToThaiNumber(item.volume) : "",
          section: item.section ? Extension.ToThaiNumber(item.section) : "",
          page: item.page ? Extension.ToThaiNumber(item.page) : "",
          refCommandDate: item.refCommandDate
            ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.refCommandDate))
            : "",
          note: item.note ? Extension.ToThaiNumber(item.note) : "",
        }))
        : [
          {
            receiveDate: "",
            insigniaName: "",
            insigniaShortName: "",
            insigniaTypeName: "",
            no: "",
            issue: "",
            volumeNo: "",
            volume: "",
            section: "",
            page: "",
            refCommandDate: "",
          },
        ];

    const leave_raw = await this.profileLeaveRepository
      .createQueryBuilder("profileLeave")
      .leftJoinAndSelect("profileLeave.leaveType", "leaveType")
      .select([
        "profileLeave.isDeleted",
        "profileLeave.leaveTypeId",
        "leaveType.name as name",
        "leaveType.code as code",
        "profileLeave.status",
        "profileLeave.profileEmployeeId",
        "MAX(profileLeave.dateLeaveStart) as maxDateLeaveStart",
      ])
      .addSelect("SUM(profileLeave.leaveDays)", "totalLeaveDays")
      .where("profileLeave.profileEmployeeId = :profileId", { profileId: id })
      .andWhere("profileLeave.isDeleted = :isDeleted", { isDeleted: false })
      .andWhere("profileLeave.status = :status", { status: "approve" })
      .groupBy("profileLeave.leaveTypeId")
      .orderBy("code", "ASC")
      .addOrderBy("maxDateLeaveStart", "ASC")
      .getRawMany();

    const leaves: any[] = [];

    leave_raw.forEach((item) => {
      const leaveTypeCode = item.code ? item.code.trim().toUpperCase() : "";
      if (leaveTypeCode.startsWith("LV-")) {
        const lvIndex = parseInt(leaveTypeCode.split("-")[1], 10);

        if (lvIndex >= 1 && lvIndex <= 11) {
          const leaveTypeCodeKey = `leaveTypeCodeLv${lvIndex}`;
          const totalLeaveDaysKey = `totalLeaveDaysLv${lvIndex}`;
          const leaveTypeNameKey = `leaveTypeNameLv${lvIndex}`;

          const leaveDate = item.maxDateLeaveStart ? new Date(item.maxDateLeaveStart) : null;
          const year = leaveDate
            ? Extension.ToThaiNumber(Extension.ToThaiShortYear(leaveDate))
            : "";

          let yearData = leaves.find((data) => data.year === year);
          if (!yearData) {
            yearData = { year };

            for (let i = 1; i <= 11; i++) {
              yearData[`leaveTypeCodeLv${i}`] = "";
              yearData[`totalLeaveDaysLv${i}`] = "";
              yearData[`leaveTypeNameLv${i}`] = "";
            }

            leaves.push(yearData);
          }

          yearData[leaveTypeCodeKey] = item.code ? item.code : "";
          yearData[totalLeaveDaysKey] = item.totalLeaveDays
            ? Extension.ToThaiNumber(item.totalLeaveDays.toString())
            : "";
          yearData[leaveTypeNameKey] = item.name ? item.name : "";
        }
      }
    });

    // Query มาสาย/ขาดราชการ และ merge ตามปี
    const absentLate_raw = await this.profileEmployeeAbsentLateRepo
      .createQueryBuilder("absentLate")
      .select([
        "YEAR(absentLate.stampDate) as year",
        "absentLate.status as status",
        "SUM(absentLate.stampAmount) as totalAmount",
      ])
      .where("absentLate.profileEmployeeId = :profileId", { profileId: id })
      .andWhere("absentLate.isDeleted = :isDeleted", { isDeleted: false })
      .groupBy("YEAR(absentLate.stampDate), absentLate.status")
      .orderBy("year", "DESC")
      .getRawMany();

    // Merge มาสาย/ขาดราชการเข้า leaves array
    absentLate_raw.forEach((item) => {
      const year = item.year ? Extension.ToThaiNumber((item.year + 543).toString()) : "";

      let yearData = leaves.find((data) => data.year === year);

      // ถ้าไม่มีปีนั้นใน leaves ให้สร้างใหม่
      if (!yearData) {
        yearData = { year };
        for (let i = 1; i <= 11; i++) {
          yearData[`leaveTypeCodeLv${i}`] = "";
          yearData[`totalLeaveDaysLv${i}`] = "";
          yearData[`leaveTypeNameLv${i}`] = "";
        }
        leaves.push(yearData);
      }

      // เพิ่มข้อมูลมาสาย/ขาดราชการ
      if (item.status === "LATE") {
        yearData.lateAmount = item.totalAmount
          ? Extension.ToThaiNumber(parseFloat(item.totalAmount).toFixed(1))
          : "";
      } else if (item.status === "ABSENT") {
        yearData.absentAmount = item.totalAmount
          ? Extension.ToThaiNumber(parseFloat(item.totalAmount).toFixed(1))
          : "";
      }
    });

    // // เติมค่า "" ถ้าไม่มีข้อมูลมาสาย/ขาดราชการ
    // leaves.forEach((yearData) => {
    //   if (!yearData.lateAmount) yearData.lateAmount = "";
    //   if (!yearData.absentAmount) yearData.absentAmount = "";
    // });

    if (leaves.length === 0) {
      leaves.push({ year: "" });
    }

    const leave2_raw = await this.profileLeaveRepository
      .createQueryBuilder("profileLeave")
      .leftJoinAndSelect("profileLeave.leaveType", "leaveType")
      .select([
        "profileLeave.leaveSubTypeName AS leaveSubTypeName",
        "profileLeave.coupleDayLevelCountry AS coupleDayLevelCountry",
        "profileLeave.isDeleted AS isDeleted",
        "profileLeave.dateLeaveStart AS dateLeaveStart",
        "profileLeave.dateLeaveEnd AS dateLeaveEnd",
        "profileLeave.leaveDays AS leaveDays",
        "profileLeave.reason AS reason",
        "leaveType.name as name",
        "leaveType.code as code",
      ])
      .where("profileLeave.profileEmployeeId = :profileId", { profileId: id })
      .andWhere("profileLeave.isDeleted = :isDeleted", { isDeleted: false })
      .andWhere("leaveType.code IN (:...codes)", { codes: ["LV-008", "LV-009", "LV-010"] })
      .andWhere("profileLeave.status = :status", { status: "approve" })
      .orderBy("leaveType.code", "ASC")
      .getRawMany();
    const leaves2 =
      leave2_raw.length > 0
        ? leave2_raw.map((item) => {
          const leaveTypeCode = item.code ? item.code.trim().toUpperCase() : "";

          // ข้อที่ 1: LV-008 ให้ใช้ leaveSubTypeName (ประเภทย่อย) แทน name
          const displayType =
            leaveTypeCode === "LV-008" && item.leaveSubTypeName
              ? item.leaveSubTypeName
              : item.name || "-";

          // ข้อที่ 2: แสดง reason ก่อนเสมอ ถ้ามี coupleDayLevelCountry ค่อยแสดงประเทศ
          const displayReason = item.coupleDayLevelCountry
            ? `${item.reason || ""} ลาไปประเทศ ${item.coupleDayLevelCountry}`.trim()
            : item.reason || "-";

          return {
            date:
              item.dateLeaveStart && item.dateLeaveEnd
                ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.dateLeaveStart)) +
                " - " +
                Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.dateLeaveEnd))
                : "-",
            type: displayType,
            leaveDays: item.leaveDays ? Extension.ToThaiNumber(item.leaveDays.toString()) : "-",
            reason: displayReason,
          };
        })
        : [
          {
            date: "",
            type: "",
            leaveDays: "",
            reason: "",
          },
        ];
    const children_raw = await this.profileChildrenRepository.find({
      where: { profileEmployeeId: id, isDeleted: false },
    });
    const children =
      children_raw.length > 0
        ? children_raw.map((item, index) => ({
          no: Extension.ToThaiNumber((index + 1).toString()),
          childrenPrefix: item.childrenPrefix,
          childrenFirstName: item.childrenFirstName,
          childrenLastName: item.childrenLastName,
          childrenFullName: `${item.childrenPrefix}${item.childrenFirstName} ${item.childrenLastName}`,
          childrenLive: item.childrenLive == false ? "ถึงแก่กรรม" : "มีชีวิต",
        }))
        : [
          {
            no: "",
            childrenPrefix: "",
            childrenFirstName: "",
            childrenLastName: "",
            childrenFullName: "",
            childrenLive: "",
          },
        ];
    const changeName_raw = await this.changeNameRepository.find({
      where: { profileEmployeeId: id, isDeleted: false },
      order: { createdAt: "ASC" },
    });
    const changeName =
      changeName_raw.length > 0
        ? changeName_raw.map((item) => ({
          createdAt: item.createdAt
            ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.createdAt))
            : null,
          status: item.status,
          prefix: item.prefix,
          firstName: item.firstName,
          lastName: item.lastName,
        }))
        : [
          {
            createdAt: "",
            status: "",
            prefix: "",
            firstName: "",
            lastName: "",
          },
        ];

    const profileHistory = await this.profileHistoryRepo.find({
      where: { profileEmployeeId: id },
      order: { createdAt: "ASC" },
    });
    const history =
      profileHistory.length > 0
        ? profileHistory.map((item) => ({
          birthDateOld: item.birthDateOld
            ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.birthDateOld))
            : "",
          birthDate: item.birthDate
            ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.birthDate))
            : "",
        }))
        : [
          {
            birthDateOld: "",
            birthDate: "",
          },
        ];

    const position_raw = await this.salaryRepo.find({
      where: [
        {
          profileEmployeeId: id,
          commandCode: In([
            "0",
            "1",
            "2",
            "3",
            "4",
            "8",
            "9",
            "10",
            "11",
            "12",
            "13",
            "14",
            "15",
            "16",
            "20",
          ]),
          // isEntry: false,
        },
        { profileEmployeeId: id, commandCode: IsNull() },
      ],
      order: { order: "ASC" },
    });
    let _commandName: any = "";
    let _commandDateAffect: any = "";
    const positionList =
      position_raw.length > 0
        ? await Promise.all(
          position_raw.map(async (item, idx, arr) => {
            const isLast = idx === arr.length - 1;
            if (isLast) {
              _commandDateAffect = item.commandDateAffect
                ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.commandDateAffect))
                : "";
            }
            const _code = item.commandCode ? Number(item.commandCode) : null;
            if (_code != null) {
              _commandName = await this.commandCodeRepository.findOne({
                select: { name: true, code: true },
                where: { code: _code },
              });
            }
            const codeSitAbb = item.posNumCodeSitAbb ?? "-";
            const commandNo =
              item.commandNo && item.commandYear
                ? item.commandNo +
                "/" +
                (item.commandYear > 2500 ? item.commandYear : item.commandYear + 543)
                : "-";
            const dateAffect = item.commandDateAffect
              ? `${Extension.ToThaiFullDate2(item.commandDateAffect)}`
              : "-";
            return {
              commandName:
                _commandName && _commandName.name ? _commandName.name : item.commandName,
              commandDateAffect: item.commandDateAffect
                ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.commandDateAffect))
                : "",
              commandDateSign: item.commandDateSign
                ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.commandDateSign))
                : "",
              posNo:
                item.posNoAbb && item.posNo
                  ? Extension.ToThaiNumber(`${item.posNoAbb} ${item.posNo}`)
                  : "",
              position: item.positionName,
              posType: item.positionType,
              posLevel: item.positionLevel
                ? Extension.ToThaiNumber(item.positionLevel)
                : item.positionCee
                  ? Extension.ToThaiNumber(item.positionCee)
                  : null,
              amount: item.amount
                ? Extension.ToThaiNumber(Number(item.amount).toLocaleString())
                : "",
              positionSalaryAmount: item.positionSalaryAmount
                ? Extension.ToThaiNumber(Number(item.positionSalaryAmount).toLocaleString())
                : "",
              refDoc: Extension.ToThaiNumber(
                `คำสั่ง ${codeSitAbb} ที่ ${commandNo} ลว. ${dateAffect}`,
              ),
            };
          }),
        )
        : [
          {
            commandName: "",
            commandDateAffect: "",
            commandDateSign: "",
            posNo: "",
            position: "",
            posType: "",
            posLevel: "",
            amount: "",
            positionSalaryAmount: "",
            refDoc: "",
          },
        ];

    // ลูกจ้างยังไม่มีรักษาการและช่วยราชการ
    // const actposition_raw = await this.profileActpositionRepo.find({
    //   select: ["dateStart", "dateEnd", "position", "isDeleted"],
    //   where: { profileEmployeeId: id, isDeleted: false },
    //   order: { createdAt: "ASC" },
    // });
    // const assistance_raw = await this.profileAssistanceRepository.find({
    //   select: ["dateStart", "dateEnd", "commandName", "agency", "document", "isDeleted"],
    //   where: { profileEmployeeId: id, isDeleted: false },
    //   order: { createdAt: "ASC" },
    // });

    // const _actposition =
    //   actposition_raw.length > 0
    //     ? actposition_raw.map((item) => ({
    //         date:
    //           item.dateStart && item.dateEnd
    //             ? Extension.ToThaiNumber(
    //                 `${Extension.ToThaiFullDate2(item.dateStart)} - ${Extension.ToThaiFullDate2(item.dateEnd)}`,
    //               )
    //             : item.dateStart
    //               ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.dateStart))
    //               : item.dateEnd
    //                 ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.dateEnd))
    //                 : "",
    //         position: item.position ? Extension.ToThaiNumber(item.position) : "",
    //         commandName: "รักษาการในตำแหน่ง",
    //         agency: "",
    //         document: "",
    //       }))
    //     : [
    //         {
    //           date: "",
    //           position: "",
    //           commandName: "",
    //           agency: "",
    //           document: "",
    //         },
    //       ];
    // const _assistance =
    //   assistance_raw.length > 0
    //     ? assistance_raw.map((item) => ({
    //         date:
    //           item.dateStart && item.dateEnd
    //             ? Extension.ToThaiNumber(
    //                 `${Extension.ToThaiFullDate2(item.dateStart)} - ${Extension.ToThaiFullDate2(item.dateEnd)}`,
    //               )
    //             : item.dateStart
    //               ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.dateStart))
    //               : item.dateEnd
    //                 ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.dateEnd))
    //                 : "",
    //         position: "",
    //         commandName: item.commandName ? Extension.ToThaiNumber(item.commandName) : "",
    //         agency: item.agency ? Extension.ToThaiNumber(item.agency) : "",
    //         document: item.document ? Extension.ToThaiNumber(item.document) : "",
    //       }))
    //     : [
    //         {
    //           date: "",
    //           position: "",
    //           commandName: "",
    //           agency: "",
    //           document: "",
    //         },
    //       ];
    const actposition = [
      {
        date: "",
        position: "",
        commandName: "",
        agency: "",
        document: "",
      },
    ];
    const duty_raw = await this.dutyRepository.find({
      where: { profileEmployeeId: id, isDeleted: false },
      order: { createdAt: "ASC" },
    });
    const duty =
      duty_raw.length > 0
        ? duty_raw.map((item) => ({
          date:
            item.dateStart && item.dateEnd
              ? Extension.ToThaiNumber(
                `${Extension.ToThaiFullDate2(item.dateStart)} - ${Extension.ToThaiFullDate2(item.dateEnd)}`,
              )
              : item.dateStart
                ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.dateStart))
                : item.dateEnd
                  ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.dateEnd))
                  : "",
          type: "-",
          detail: Extension.ToThaiNumber(item.detail),
          agency: "-",
          refCommandNo: item.refCommandNo
            ? item.refCommandDate
              ? Extension.ToThaiNumber(
                `${item.refCommandNo} ลว. ${Extension.ToThaiFullDate2(item.refCommandDate)}`,
              )
              : Extension.ToThaiNumber(item.refCommandNo)
            : "-",
        }))
        : [
          {
            date: "",
            type: "",
            detail: "",
            agency: "",
            refCommandNo: "",
          },
        ];
    const assessments_raw = await this.profileAssessmentsRepository.find({
      where: { profileEmployeeId: id, isDeleted: false },
      order: { createdAt: "ASC" },
    });
    const assessments =
      assessments_raw.length > 0
        ? assessments_raw.map((item) => ({
          year: item.year ? Extension.ToThaiNumber((parseInt(item.year) + 543).toString()) : "",
          period:
            item.period && item.period == "APR"
              ? Extension.ToThaiNumber(
                `1 เม.ย. ${(parseInt(item.year) + 543 - 1).toString()} - 31 มี.ค. ${(parseInt(item.year) + 543).toString()}`,
              )
              : Extension.ToThaiNumber(
                `1 ต.ค. ${(parseInt(item.year) + 543 - 1).toString()} - 30 ก.ย. ${(parseInt(item.year) + 543).toString()}`,
              ),
          point1: item.point1 ? Extension.ToThaiNumber(item.point1.toString()) : "",
          point1Total: item.point1Total
            ? Extension.ToThaiNumber(item.point1Total.toString())
            : "",
          point2: item.point2 ? Extension.ToThaiNumber(item.point2.toString()) : "",
          point2Total: item.point2Total
            ? Extension.ToThaiNumber(item.point2Total.toString())
            : "",
          pointSum: item.pointSum
            ? Extension.ToThaiNumber(`ร้อยละ ${item.pointSum.toString()}`)
            : "",
          pointSumTh: item.pointSum ? Extension.textPoint(item.pointSum) : "",
          level:
            item.pointSum < 60.0
              ? "ต้องปรับปรุง"
              : item.pointSum <= 69.99 && item.pointSum >= 60.0
                ? "พอใช้"
                : item.pointSum <= 79.99 && item.pointSum >= 70.0
                  ? "ดี"
                  : item.pointSum <= 89.99 && item.pointSum >= 80.0
                    ? "ดีมาก"
                    : "ดีเด่น",
        }))
        : [
          {
            year: "",
            period: "",
            point1: "",
            point2: "",
            pointSum: "",
            pointSumTh: "",
          },
        ];
    const profileAbility_raw = await this.profileAbilityRepo.find({
      where: { profileEmployeeId: id },
      order: { createdAt: "ASC" },
    });
    const profileAbility =
      profileAbility_raw.length > 0
        ? profileAbility_raw.map((item) => ({
          field: item.field ? item.field : "",
          detail: item.detail ? item.detail : "",
        }))
        : [
          {
            field: "",
            detail: "",
          },
        ];

    const otherIncome_raw = await this.salaryRepo.find({
      where: {
        profileEmployeeId: id,
        commandCode: "7",
        // isEntry: false,
      },
      order: { order: "ASC" },
    });
    const otherIncome =
      otherIncome_raw.length > 0
        ? await Promise.all(
          otherIncome_raw.map(async (item) => {
            const codeSitAbb = item.posNumCodeSitAbb ?? "-";
            const commandNo =
              item.commandNo && item.commandYear
                ? item.commandNo +
                "/" +
                (item.commandYear > 2500 ? item.commandYear : item.commandYear + 543)
                : "-";
            const dateAffect = item.commandDateAffect
              ? `${Extension.ToThaiFullDate2(item.commandDateAffect)}`
              : "-";
            return {
              commandName: item.commandName ?? "",
              commandDateAffect: item.commandDateAffect
                ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.commandDateAffect))
                : "",
              commandDateSign: item.commandDateSign
                ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.commandDateSign))
                : "",
              commandNo: item.commandNo ? Extension.ToThaiNumber(item.commandNo) : "",
              position: item.positionName,
              posLevel: item.positionLevel
                ? Extension.ToThaiNumber(item.positionLevel)
                : item.positionCee
                  ? Extension.ToThaiNumber(item.positionCee)
                  : null,
              amount: item.amount
                ? Extension.ToThaiNumber(Number(item.amount).toLocaleString())
                : "",
              refDoc: Extension.ToThaiNumber(
                `คำสั่ง ${codeSitAbb} ที่ ${commandNo} ลว. ${dateAffect}`,
              ),
            };
          }),
        )
        : [
          {
            commandName: "",
            commandDateAffect: "",
            commandDateSign: "",
            commandNo: "",
            position: "",
            posLevel: "",
            amount: "",
            refDoc: "",
          },
        ];

    // ประวัติพ้นจากราชการ
    let retires = [];
    const currentDate = new Date();

    // commandCode ที่ถือว่าออกจากราชการ
    const retireCommandCodes = ["12", "15", "16"];

    // ดึงข้อมูล profileSalary ทั้งหมดเพื่อหาประวัติพ้นจากราชการ
    const salaries = await this.salaryRepo.find({
      where: { profileEmployeeId: id },
      order: { order: "ASC" },
    });

    // มีคำสั่งพ้นราชการหรือไม่
    if (
      salaries.length > 0 &&
      salaries.some((s) => s.commandCode && retireCommandCodes.includes(s.commandCode))
    ) {
      // กรองข้อมูลซ้ำตาม commandDateAffect
      const uniqueSalaries = salaries.filter(
        (item, index, self) =>
          index ===
          self.findIndex(
            (t) => t.commandDateAffect?.getTime() === item.commandDateAffect?.getTime(),
          ),
      );

      // วนลูปหาคู่ของ "ออกราชการ" และ "กลับเข้าราชการ"
      for (let i = 0; i < uniqueSalaries.length; i++) {
        const current = uniqueSalaries[i];

        // เป็นคำสั่งออกจากราชการหรือไม่
        if (current.commandCode && retireCommandCodes.includes(current.commandCode)) {
          const startDate = current.commandDateAffect;
          let endDate: Date | null = null;
          let endRecord = null;

          // หาคำสั่งถัดไปที่ไม่ใช่การออกจากราชการ (ถือว่ากลับเข้าราชการ)
          for (let j = i + 1; j < uniqueSalaries.length; j++) {
            const next = uniqueSalaries[j];
            if (next.commandCode && !retireCommandCodes.includes(next.commandCode)) {
              endDate = next.commandDateAffect;
              endRecord = next;
              break;
            }
          }

          // ถ้าไม่เจอคำสั่งกลับเข้า ให้ใช้วันปัจจุบัน
          if (!endDate) {
            endDate = currentDate;
          }

          // คำนวณจำนวนวัน
          let daysCount = 0;
          if (startDate && endDate) {
            const start = new Date(startDate);
            const end = new Date(endDate);
            daysCount = Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24));
          }

          // สร้าง detail จาก commandName + remark
          const commandName = current.commandName || "";
          const remark = current.remark || "";
          const detail = `${commandName} ${remark}`.trim();

          // แปลงวันที่เป็น format ไทย
          const startDateStr = startDate
            ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(startDate))
            : "-";
          const endDateStr = endDate
            ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(endDate))
            : "-";

          retires.push({
            date: `${startDateStr} - ${endDateStr}`,
            detail: detail || "-",
            day: daysCount > 0 ? Extension.ToThaiNumber(daysCount.toLocaleString()) : "-",
          });
        }
      }
    }

    // กรณีไม่มีข้อมูล
    if (retires.length === 0) {
      retires.push({ date: "", detail: "", day: "" });
    }

    const org =
      (_child4 == null ? "" : _child4 + " ") +
      (_child3 == null ? "" : _child3 + " ") +
      (_child2 == null ? "" : _child2 + " ") +
      (_child1 == null ? "" : _child1 + " ") +
      (_root == null ? "" : _root).trim();
    const _position = (
      profiles?.position != null
        ? profiles.posType != null && profiles?.posLevel != null
          ? Extension.ToThaiNumber(
            `${profiles.position} ${profiles.posType.posTypeShortName} ${profiles.posLevel.posLevelName}`,
          )
          : profiles.position
        : ""
    ).trim();
    const ocAssistance = await this.profileAssistanceRepository.findOne({
      select: ["agency", "profileEmployeeId", "commandName", "status", "isDeleted"],
      where: {
        profileEmployeeId: id,
        commandName: "ให้ช่วยราชการ",
        status: "PENDING",
        isDeleted: false,
      },
      order: { createdAt: "ASC" },
    });

    const sum = profiles
      ? Extension.ToThaiNumber(
        (
          Number(profiles.amount) +
          Number(profiles.positionSalaryAmount) +
          Number(profiles.mouthSalaryAmount) +
          Number(profiles.amountSpecial)
        ).toLocaleString(),
      )
      : "";
    const fullCurrentAddress =
      profiles && profiles.currentAddress
        ? Extension.ToThaiNumber(
          profiles.currentAddress +
          (profiles.currentSubDistrict && profiles.currentSubDistrict.name
            ? " ตำบล/แขวง " + profiles.currentSubDistrict.name
            : "") +
          (profiles.currentDistrict && profiles.currentDistrict.name
            ? " อำเภอ/เขต " + profiles.currentDistrict.name
            : "") +
          (profiles.currentProvince && profiles.currentProvince.name
            ? " จังหวัด " + profiles.currentProvince.name
            : "") +
          (profiles.currentZipCode ? " " + profiles.currentZipCode : ""),
        )
        : "";
    const fullRegistrationAddress =
      profiles && profiles.registrationAddress
        ? Extension.ToThaiNumber(
          profiles.registrationAddress +
          (profiles.registrationSubDistrict && profiles.registrationSubDistrict.name
            ? " ตำบล/แขวง " + profiles.registrationSubDistrict.name
            : "") +
          (profiles.registrationDistrict && profiles.registrationDistrict.name
            ? " อำเภอ/เขต " + profiles.registrationDistrict.name
            : "") +
          (profiles.registrationProvince && profiles.registrationProvince.name
            ? " จังหวัด " + profiles.registrationProvince.name
            : "") +
          (profiles.currentZipCode ? " " + profiles.currentZipCode : ""),
        )
        : "";
    const data = {
      currentDate: Extension.ToThaiNumber(Extension.ToThaiFullDate2(currentDate)),
      fullName: `${profiles?.prefix}${profiles?.firstName} ${profiles?.lastName}`,
      prefix: profiles?.prefix != null ? profiles.prefix : "",
      firstName: profiles?.firstName != null ? profiles.firstName : "",
      lastName: profiles?.lastName != null ? profiles.lastName : "",
      position: _position,
      posAssistance: ocAssistance ? "-" : _position, // ปัจจุบันช่วยราชการยังไม่มีเก็บฟิลด์ตำแหน่ง
      amount:
        profiles?.amount != null ? Extension.ToThaiNumber(profiles.amount.toLocaleString()) : "",
      positionSalaryAmount:
        profiles?.positionSalaryAmount != null
          ? Extension.ToThaiNumber(profiles.positionSalaryAmount.toLocaleString())
          : "",
      mouthSalaryAmount:
        profiles?.mouthSalaryAmount != null
          ? Extension.ToThaiNumber(profiles.mouthSalaryAmount.toLocaleString())
          : "",
      amountSpecial:
        profiles?.amountSpecial != null
          ? Extension.ToThaiNumber(profiles.amountSpecial.toLocaleString())
          : "",
      salarySum: sum,
      ocFullPath: org,
      ocAssistance: ocAssistance?.agency ?? org,
      root: _root == null ? "" : _root,
      agency:
        (_child4 == null ? "" : _child4 + " ") +
        (_child3 == null ? "" : _child3 + " ") +
        (_child2 == null ? "" : _child2 + " ") +
        (_child1 == null ? "" : _child1).trim(),
      birthDate: profiles?.birthDate
        ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(profiles.birthDate))
        : "",
      retireDate:
        profiles.dateRetireLaw != null
          ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(profiles.dateRetireLaw))
          : "",
      appointDate: profiles?.dateAppoint
        ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(profiles.dateAppoint))
        : "",
      positionDate: _commandDateAffect ?? "",
      citizenId:
        profiles.citizenId != null ? Extension.ToThaiNumber(profiles.citizenId.toString()) : "",
      fatherFullName:
        profileFamilyFather?.fatherPrefix ||
          profileFamilyFather?.fatherFirstName ||
          profileFamilyFather?.fatherLastName
          ? `${profileFamilyFather?.fatherPrefix ?? ""}${profileFamilyFather?.fatherFirstName ?? ""} ${profileFamilyFather?.fatherLastName ?? ""}`.trim()
          : null,
      fatherLive:
        profileFamilyFather && profileFamilyFather?.fatherLive == true ? "ถึงแก่กรรม" : "มีชีวิต",
      motherFullName:
        profileFamilyMother?.motherPrefix ||
          profileFamilyMother?.motherFirstName ||
          profileFamilyMother?.motherLastName
          ? `${profileFamilyMother?.motherPrefix ?? ""}${profileFamilyMother?.motherFirstName ?? ""} ${profileFamilyMother?.motherLastName ?? ""}`.trim()
          : null,
      motherLive:
        profileFamilyMother && profileFamilyMother?.motherLive == true ? "ถึงแก่กรรม" : "มีชีวิต",
      coupleFullName:
        profileFamilyCouple?.couplePrefix ||
          profileFamilyCouple?.coupleFirstName ||
          profileFamilyCouple?.coupleLastNameOld
          ? `${profileFamilyCouple?.couplePrefix ?? ""}${profileFamilyCouple?.coupleFirstName ?? ""} ${profileFamilyCouple?.coupleLastName ?? ""}`.trim()
          : null,
      coupleLastNameOld: profileFamilyCouple?.coupleLastNameOld ?? null,
      coupleLive:
        profileFamilyCouple && profileFamilyCouple?.coupleLive == true ? "ถึงแก่กรรม" : "มีชีวิต",
      currentAddress:
        profiles.currentAddress != null ? Extension.ToThaiNumber(profiles.currentAddress) : "",
      currentSubDistrict:
        profiles.currentSubDistrict != null
          ? Extension.ToThaiNumber(profiles.currentSubDistrict.name)
          : "",
      currentDistrict:
        profiles.currentDistrict != null
          ? Extension.ToThaiNumber(profiles.currentDistrict.name)
          : "",
      currentProvince:
        profiles.currentProvince != null
          ? Extension.ToThaiNumber(profiles.currentProvince.name)
          : "",
      currentZipcode:
        profiles.currentZipCode != null ? Extension.ToThaiNumber(profiles.currentZipCode) : "",
      fullCurrentAddress: fullCurrentAddress,
      registrationAddress:
        profiles.registrationAddress != null
          ? Extension.ToThaiNumber(profiles.registrationAddress)
          : "",
      registrationSubDistrict:
        profiles.registrationSubDistrict != null
          ? Extension.ToThaiNumber(profiles.registrationSubDistrict.name)
          : "",
      registrationDistrict:
        profiles.registrationDistrict != null
          ? Extension.ToThaiNumber(profiles.registrationDistrict.name)
          : "",
      registrationProvince:
        profiles.registrationProvince != null
          ? Extension.ToThaiNumber(profiles.registrationProvince.name)
          : "",
      registrationZipcode:
        profiles.registrationZipCode != null
          ? Extension.ToThaiNumber(profiles.registrationZipCode)
          : "",
      fullRegistrationAddress: fullRegistrationAddress,
      updateAt: profiles.lastUpdatedAt
        ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(profiles.lastUpdatedAt))
        : "",
      telephone: profiles.phone != null ? Extension.ToThaiNumber(profiles.phone) : "",
      url: ImgUrl ? ImgUrl : `${process.env.VITE_URL_MGT}`,
      url1: _ImgUrl[0] ? _ImgUrl[0] : null,
      yearUpload1: profiles.profileAvatars[0]
        ? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[0].createdAt))
        : null,
      url2: _ImgUrl[1] ? _ImgUrl[1] : null,
      yearUpload2: profiles.profileAvatars[1]
        ? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[1].createdAt))
        : null,
      url3: _ImgUrl[2] ? _ImgUrl[2] : null,
      yearUpload3: profiles.profileAvatars[2]
        ? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[2].createdAt))
        : null,
      url4: _ImgUrl[3] ? _ImgUrl[3] : null,
      yearUpload4: profiles.profileAvatars[3]
        ? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[3].createdAt))
        : null,
      url5: _ImgUrl[4] ? _ImgUrl[4] : null,
      yearUpload5: profiles.profileAvatars[4]
        ? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[4].createdAt))
        : null,
      url6: _ImgUrl[5] ? _ImgUrl[5] : null,
      yearUpload6: profiles.profileAvatars[5]
        ? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[5].createdAt))
        : null,
      url7: _ImgUrl[6] ? _ImgUrl[6] : null,
      yearUpload7: profiles.profileAvatars[6]
        ? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[6].createdAt))
        : null,
      urlQRcode: "https://seis.ocsc.go.th",
      children,
      insignias,
      leaves,
      leaves2,
      certs,
      trainings,
      disciplines,
      educations,
      salarys,
      changeName,
      history,
      positionList,
      actposition,
      duty,
      assessments,
      profileAbility,
      otherIncome,
      retires,
    };

    return new HttpSuccess({
      template: "new_kk1-emp",
      reportName: "docx-report",
      data: data,
    });
  }

  /**
   * API สร้างทะเบียนประวัติ
   *
   * @summary ORG_065 - สร้างทะเบียนประวัติ (ADMIN) #70
   *
   */
  @Post()
  async createProfile(@Body() body: CreateProfileEmployee, @Request() request: RequestWithUser) {
    //ไม่แน่ใจEMPปิดไว้ก่อน
    if (await this.profileRepo.findOneBy({ citizenId: body.citizenId })) {
      throw new HttpError(
        HttpStatus.INTERNAL_SERVER_ERROR,
        "รหัสบัตรประจำตัวประชาชนนี้มีอยู่ในระบบแล้ว",
      );
    }

    if (body.posLevelId === "") body.posLevelId = null;
    if (body.posTypeId === "") body.posTypeId = null;

    if (body.posLevelId && !(await this.posLevelRepo.findOneBy({ id: body.posLevelId }))) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลระดับตำแหน่งนี้");
    }

    if (body.posTypeId && !(await this.posTypeRepo.findOneBy({ id: body.posTypeId }))) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลประเภทตำแหน่งนี้");
    }

    if (body.citizenId) {
      const citizenIdDigits = body.citizenId.toString().split("").map(Number);
      const cal =
        citizenIdDigits[0] * 13 +
        citizenIdDigits[1] * 12 +
        citizenIdDigits[2] * 11 +
        citizenIdDigits[3] * 10 +
        citizenIdDigits[4] * 9 +
        citizenIdDigits[5] * 8 +
        citizenIdDigits[6] * 7 +
        citizenIdDigits[7] * 6 +
        citizenIdDigits[8] * 5 +
        citizenIdDigits[9] * 4 +
        citizenIdDigits[10] * 3 +
        citizenIdDigits[11] * 2;
      const calStp2 = cal % 11;
      const chkDigit = (11 - calStp2) % 10;

      if (citizenIdDigits[12] !== chkDigit) {
        throw new HttpError(HttpStatus.NOT_FOUND, "ข้อมูลรหัสบัตรประจำตัวประชาชนไม่ถูกต้อง");
      }
    }
    if (body.employeeClass == null || body.employeeClass == undefined || body.employeeClass == "") {
      body.employeeClass = "PERM";
    }
    if (!["PERM", "TEMP"].includes(body.employeeClass.toLocaleUpperCase())) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ประเภทลูกจ้างไม่ถูกต้อง");
    }

    const profile = Object.assign(new ProfileEmployee(), body);
    profile.prefixMain = profile.prefix;
    profile.prefix = profile.rank && profile.rank.length > 0 ? profile.rank : profile.prefixMain;
    profile.createdUserId = request.user.sub;
    profile.createdFullName = request.user.name;
    profile.lastUpdateUserId = request.user.sub;
    profile.lastUpdateFullName = request.user.name;
    profile.createdAt = new Date();
    profile.lastUpdatedAt = new Date();
    profile.dateRetire = calculateRetireDate(profile.birthDate);
    profile.dateRetireLaw = calculateRetireLaw(profile.birthDate);
    profile.citizenId = Extension.CheckCitizen(profile.citizenId);
    profile.statusTemp = profile.employeeClass.toLocaleUpperCase() == "TEMP" ? "WAITTING" : "";
    profile.employeeClass = profile.employeeClass.toLocaleUpperCase();
    await this.profileRepo.save(profile);
    return new HttpSuccess();
  }

  /**
   * API แก้ไขทะเบียนประวัติ
   *
   * @summary ORG_065 - แก้ไขทะเบียนประวัติ (ADMIN) #70
   *
   * @param {string} id  Id ทะเบียนประวัติ
   */
  @Put("{id}")
  async updateProfileEmployee(
    @Request() request: RequestWithUser,
    @Path() id: string,
    @Body() body: UpdateProfileEmployee,
  ) {
    const _record = await this.profileRepo.findOneBy({ id: id });
    if (_record) {
      await new permission().PermissionOrgUserUpdate(request, "SYS_REGISTRY_EMP", _record.id);
    }
    const exists =
      !!body.citizenId &&
      (await this.profileRepo.findOne({
        where: {
          id: Not(id),
          citizenId: body.citizenId,
          employeeClass: String(body.employeeClass),
        },
      }));

    if (exists) {
      throw new HttpError(HttpStatus.CONFLICT, "รหัสบัตรประจำตัวประชาชนนี้มีอยู่ในระบบแล้ว");
    }

    if (body.posLevelId === "") body.posLevelId = null;
    if (body.posTypeId === "") body.posTypeId = null;

    if (body.posLevelId && !(await this.posLevelRepo.findOneBy({ id: body.posLevelId }))) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลระดับตำแหน่งนี้");
    }

    if (body.posTypeId && !(await this.posTypeRepo.findOneBy({ id: body.posTypeId }))) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลประเภทตำแหน่งนี้");
    }

    if (body.citizenId) {
      Extension.CheckCitizen(body.citizenId);
    }
    const record = await this.profileRepo.findOneBy({ id });
    const before = structuredClone(record);
    // เช็คว่ามี profileHistory ของ profile นี้หรือไม่
    const historyCount = await this.profileHistoryRepo.count({
      where: { profileEmployeeId: id },
    });

    // ถ้าไม่มีเลย ให้บันทึกข้อมูลเริ่มต้น (ก่อน update) ลงไปก่อน
    if (historyCount === 0) {
      await this.profileHistoryRepo.save(
        Object.assign(new ProfileEmployeeHistory(), {
          ...before,
          birthDateOld: before?.birthDate,
          profileEmployeeId: id,
          id: undefined,
        }),
      );
    }

    if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์นี้");

    if (body.employeeClass == null || body.employeeClass == undefined || body.employeeClass == "") {
      body.employeeClass = "PERM";
    }
    if (!["PERM", "TEMP"].includes(body.employeeClass.toLocaleUpperCase())) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ประเภทลูกจ้างไม่ถูกต้อง");
    }

    Object.assign(record, body);
    record.dateRetireLaw = calculateRetireLaw(record.birthDate);
    record.prefixMain = record.prefix;
    record.prefix = record.rank && record.rank.length > 0 ? record.rank : record.prefixMain;
    record.createdUserId = request.user.sub;
    record.createdFullName = request.user.name;
    record.createdAt = new Date();
    record.lastUpdateUserId = request.user.sub;
    record.lastUpdateFullName = request.user.name;
    record.lastUpdatedAt = new Date();
    await this.profileHistoryRepo.save(
      Object.assign(new ProfileEmployeeHistory(), {
        ...record,
        birthDateOld: _record?.birthDate,
        lastUpdateUserId: request.user.sub,
        lastUpdateFullName: request.user.name,
        lastUpdatedAt: new Date(),
        profileEmployeeId: id,
        id: undefined,
      }),
    );
    await this.profileRepo.save(record);
    // บันทึกประวัติคนครองตำแหน่ง (ถ้า profile นี้ครองตำแหน่งอยู่)
    await updateHolderProfileHistory(record.id, request, "EMPLOYEE");
    return new HttpSuccess();
  }

  /**
   * API ลบทะเบียนประวัติ
   *
   * @summary ORG_065 - ลบทะเบียนประวัติ (ADMIN) #70
   *
   * @param {string} id  Id ทะเบียนประวัติ
   */
  @Delete("{id}")
  async deleteProfile(@Path() id: string, @Request() request: RequestWithUser) {
    const result = await this.profileRepo.findOne({ where: { id: id } });
    if (!result) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    }
    try {
      await new permission().PermissionOrgUserDelete(request, "SYS_REGISTRY_EMP", result.id);
      await this.informationHistoryRepository.delete({ profileEmployeeId: id });
      await this.profileRepo.remove(result);
    } catch {
      throw new HttpError(
        HttpStatusCode.NOT_FOUND,
        "ไม่สามารถลบข้อมูลได้ เนื่องจากข้อมูลนี้ถูกใช้งานในระบบอื่น",
      );
    }
    return new HttpSuccess();
  }

  /**
   * API รายละเอียดรายการทะเบียนประวัติ
   *
   * @summary ORG_065 - รายละเอียดรายการทะเบียนประวัติ  (ADMIN) #70
   *
   * @param {string} id  Id ทะเบียนประวัติ
   */
  @Get("user")
  async detailProfileUser(@Request() request: RequestWithUser) {
    const profile = await this.profileRepo.findOne({
      relations: {
        posLevel: true,
        posType: true,
        // gender: true,
        // relationship: true,
        // bloodGroup: true,
      },
      where: { keycloak: request.user.sub },
    });

    if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");

    return new HttpSuccess(profile);
  }

  /**
   * API รายการทะเบียนประวัติลูกจ้างชั่วคราว
   *
   * @summary รายการทะเบียนประวัติลูกจ้างชั่วคราว (ADMIN)
   *
   */
  @Get("temp")
  async listProfileEmp() {
    const [record, total] = await this.profileRepo
      .createQueryBuilder("profileEmployee")
      .leftJoinAndSelect("profileEmployee.posLevel", "posLevel")
      .leftJoinAndSelect("profileEmployee.posType", "posType")
      .leftJoinAndSelect("profileEmployee.current_holders", "current_holders")
      .leftJoinAndSelect("profileEmployee.profileEmployeeEmployment", "profileEmployeeEmployment")
      .leftJoinAndSelect("current_holders.positions", "positions")
      .leftJoinAndSelect("current_holders.orgRoot", "orgRoot")
      .leftJoinAndSelect("current_holders.orgChild1", "orgChild1")
      .leftJoinAndSelect("current_holders.orgChild2", "orgChild2")
      .leftJoinAndSelect("current_holders.orgChild3", "orgChild3")
      .leftJoinAndSelect("current_holders.orgChild4", "orgChild4")
      .andWhere("profileEmployee.employeeClass = :employeeClass", { employeeClass: "TEMP" })
      .andWhere("profileEmployee.statusTemp = :statusTemp", { statusTemp: "PENDING" })
      .getManyAndCount();
    const data = await Promise.all(
      record.map((_data) => {
        const shortName =
          _data.current_holders.length == 0
            ? null
            : _data.current_holders[0].orgChild4 != null
              ? `${_data.current_holders[0].orgChild4.orgChild4ShortName} ${_data.current_holders[0].posMasterNo}`
              : _data.current_holders[0].orgChild3 != null
                ? `${_data.current_holders[0].orgChild3.orgChild3ShortName} ${_data.current_holders[0].posMasterNo}`
                : _data.current_holders[0].orgChild2 != null
                  ? `${_data.current_holders[0].orgChild2.orgChild2ShortName} ${_data.current_holders[0].posMasterNo}`
                  : _data.current_holders[0].orgChild1 != null
                    ? `${_data.current_holders[0].orgChild1.orgChild1ShortName} ${_data.current_holders[0].posMasterNo}`
                    : _data.current_holders[0].orgRoot != null
                      ? `${_data.current_holders[0].orgRoot.orgRootShortName} ${_data.current_holders[0].posMasterNo}`
                      : null;
        const dateEmployment =
          _data.profileEmployeeEmployment.length == 0
            ? null
            : _data.profileEmployeeEmployment.reduce((latest, current) => {
              return latest.date > current.date ? latest : current;
            }).date;
        return {
          id: _data.id,
          prefix: _data.prefix,
          rank: _data.rank,
          firstName: _data.firstName,
          lastName: _data.lastName,
          citizenId: _data.citizenId,
          posLevel: _data.posLevel == null ? null : _data.posLevel.posLevelName,
          posType: _data.posType == null ? null : _data.posType.posTypeName,
          posTypeShortName: _data.posType == null ? null : _data.posType.posTypeShortName,
          posLevelId: _data.posLevel == null ? null : _data.posLevel.id,
          posTypeId: _data.posType == null ? null : _data.posType.id,
          positionId: _data.positionIdTemp,
          posmasterId: _data.posmasterIdTemp,
          position: _data.position,
          posNo: _data.employeeClass == "TEMP" ? _data.posMasterNoTemp : shortName,
          employeeClass: _data.employeeClass == null ? null : _data.employeeClass,
          govAge: Extension.CalculateGovAge(_data.dateAppoint, 0, 0),
          age: Extension.CalculateAgeStrV2(_data.birthDate, 0, 0, "GET"),
          dateEmployment: dateEmployment,
          dateAppoint: _data.dateAppoint,
          dateStart: _data.dateStart,
          createdAt: _data.createdAt,
          dateRetireLaw: _data.dateRetireLaw,
          draftOrganizationOrganization:
            _data.nodeTemp == "0"
              ? _data.rootTemp
              : _data.nodeTemp == "1"
                ? _data.child1Temp
                : _data.nodeTemp == "2"
                  ? _data.child2Temp
                  : _data.nodeTemp == "3"
                    ? _data.child3Temp
                    : _data.nodeTemp == "4"
                      ? _data.child4Temp
                      : null,
          draftPositionEmployee: _data.positionTemp,
          draftOrgEmployeeStatus: _data.statusTemp,
          node: _data.nodeTemp,
          nodeId: _data.nodeIdTemp,
          nodeName:
            _data.nodeTemp == "0"
              ? _data.rootTemp
              : _data.nodeTemp == "1"
                ? _data.child1Temp
                : _data.nodeTemp == "2"
                  ? _data.child2Temp
                  : _data.nodeTemp == "3"
                    ? _data.child3Temp
                    : _data.nodeTemp == "4"
                      ? _data.child4Temp
                      : null,
          nodeShortName:
            _data.nodeTemp == "0"
              ? _data.rootShortNameTemp
              : _data.nodeTemp == "1"
                ? _data.child1ShortNameTemp
                : _data.nodeTemp == "2"
                  ? _data.child1ShortNameTemp
                  : _data.nodeTemp == "3"
                    ? _data.child3ShortNameTemp
                    : _data.nodeTemp == "4"
                      ? _data.child4ShortNameTemp
                      : null,
          root: _data.rootTemp ? _data.rootTemp : null,
          rootId: _data.rootIdTemp ? _data.rootIdTemp : null,
          rootShortName: _data.rootShortNameTemp ? _data.rootShortNameTemp : null,
          child1: _data.child1Temp ? _data.child1Temp : null,
          child1Id: _data.child1IdTemp ? _data.child1IdTemp : null,
          child1ShortName: _data.child1ShortNameTemp ? _data.child1ShortNameTemp : null,
          child2: _data.child2Temp ? _data.child2Temp : null,
          child2Id: _data.child2IdTemp ? _data.child2IdTemp : null,
          child2ShortName: _data.child2ShortNameTemp ? _data.child2ShortNameTemp : null,
          child3: _data.child3Temp ? _data.child3Temp : null,
          child3Id: _data.child3IdTemp ? _data.child3IdTemp : null,
          child3ShortName: _data.child3ShortNameTemp ? _data.child3ShortNameTemp : null,
          child4: _data.child4Temp ? _data.child4Temp : null,
          child4Id: _data.child4IdTemp ? _data.child4IdTemp : null,
          child4ShortName: _data.child4ShortNameTemp ? _data.child4ShortNameTemp : null,
        };
      }),
    );

    return new HttpSuccess({ data: data, total });
  }

  /**
   * API ประวัติการแก้ไขรายการทะเบียนประวัติ
   *
   * @summary ประวัติการแก้ไขรายการทะเบียนประวัติ
   *
   * @param {string} id  Id โปรไฟล์
   */
  @Get("history/user")
  async getHistoryProfileByUser(@Request() request: RequestWithUser) {
    const profile = await this.profileRepo.findOne({
      where: { keycloak: request.user.sub },
    });
    if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");

    const profileHistory = await this.profileHistoryRepo.find({
      where: { profileEmployeeId: profile.id },
      order: { createdAt: "ASC" },
    });

    if (profileHistory.length == 0) {
      await this.profileHistoryRepo.save(
        Object.assign(new ProfileEmployeeHistory(), {
          ...profile,
          birthDateOld: profile?.birthDate,
          profileEmployeeId: profile.id,
          id: undefined,
        }),
      );
      const firstRecord = await this.profileHistoryRepo.find({
        where: { profileEmployeeId: profile.id },
        order: { createdAt: "ASC" },
      });
      return new HttpSuccess(firstRecord);
    }

    return new HttpSuccess(profileHistory);
  }

  /**
   * API ออกคำสั่งลูกจ้าง
   *
   * @summary ORG_038 - ออกคำสั่งลูกจ้าง (ADMIN) #
   *
   */
  @Get("report")
  async getReport(@Request() request: RequestWithUser) {
    const profiles = await this.profileRepo.find({
      where: { statusTemp: "REPORT", employeeClass: "TEMP" },
      relations: [
        "posLevel",
        "posType",
        "current_holders",
        "current_holders.orgChild1",
        "current_holders.orgChild2",
        "current_holders.orgChild3",
        "current_holders.orgChild4",
      ],
    });

    if (!profiles) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    }

    const findRevision = await this.orgRevisionRepo.findOne({
      where: { orgRevisionIsCurrent: true },
    });
    if (!findRevision) {
      throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
    }

    const formattedData = profiles.map((profile) => {
      const fullName = `${profile.prefix} ${profile.firstName} ${profile.lastName}`;
      const shortName =
        profile.current_holders.length == 0
          ? null
          : profile.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
            profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4 !=
            null
            ? `${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4.orgChild4ShortName} ${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
            : profile.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
              profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)
                ?.orgChild3 != null
              ? `${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3.orgChild3ShortName} ${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
              : profile.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
                profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)
                  ?.orgChild2 != null
                ? `${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2.orgChild2ShortName} ${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
                : profile.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
                  profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)
                    ?.orgChild1 != null
                  ? `${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1.orgChild1ShortName} ${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
                  : profile.current_holders.find((x) => x.orgRevisionId == findRevision.id) !=
                    null &&
                    profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)
                      ?.orgRoot != null
                    ? `${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot.orgRootShortName} ${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
                    : null;

      const root =
        profile.current_holders.length == 0 ||
          (profile.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
            profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot == null)
          ? null
          : profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot;

      return {
        id: profile.id,
        prefix: profile.prefix,
        firstName: profile.firstName,
        lastName: profile.lastName,
        fullName: fullName,
        birthDate: profile.birthDate,
        rank: profile.rank,
        citizenId: profile.citizenId,
        email: profile.email,
        phone: profile.phone,
        isProbation: profile.isProbation,
        isLeave: profile.isLeave,
        leaveReason: profile.leaveReason,
        dateLeave: profile.dateLeave,
        dateRetire: profile.dateRetire,
        dateRetireLaw: profile.dateRetireLaw,
        salaryLevel: profile.salaryLevel,
        group: profile.group,
        ethnicity: profile.ethnicity,
        telephoneNumber: profile.phone,
        nationality: profile.nationality,
        gender: profile.gender,
        relationship: profile.relationship,
        religion: profile.religion,
        bloodGroup: profile.bloodGroup,
        positionNumber: shortName,
        organization: root == null ? null : root.orgRootShortName,
        positionName: profile.position,
        possitionTypeId: profile.posTypeId,
        positionType: profile.posType?.posTypeName,
        positionLevelId: profile.posLevelId,
        positionLevel: profile.posLevel?.posLevelName,
      };
    });

    return new HttpSuccess(formattedData);
  }

  /**
   * API ออกคำสั่งลูกจ้าง
   *
   * @summary ORG_038 - ออกคำสั่งลูกจ้าง (ADMIN) #
   *
   */
  @Get("report-temp")
  async getReportTemp(@Request() request: RequestWithUser) {
    const profiles = await this.profileRepo.find({
      where: { statusTemp: "REPORT", employeeClass: "TEMP" },
    });

    if (!profiles) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    }

    const findRevision = await this.orgRevisionRepo.findOne({
      where: { orgRevisionIsCurrent: true },
    });
    if (!findRevision) {
      throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
    }

    const formattedData = profiles.map((profile) => {
      const shortName =
        profile.child4Temp != null
          ? `${profile.child4ShortNameTemp} ${profile.posMasterNoTemp}`
          : profile.child3Temp != null
            ? `${profile.child3ShortNameTemp} ${profile.posMasterNoTemp}`
            : profile.child2Temp != null
              ? `${profile.child2ShortNameTemp} ${profile.posMasterNoTemp}`
              : profile.child1Temp != null
                ? `${profile.child1ShortNameTemp} ${profile.posMasterNoTemp}`
                : profile.rootIdTemp != null
                  ? `${profile.rootShortNameTemp} ${profile.posMasterNoTemp}`
                  : null;

      return {
        id: profile.id,
        citizenId: profile.citizenId,
        prefix: profile.prefix,
        firstName: profile.firstName,
        lastName: profile.lastName,
        organization: profile.rootTemp,
        positionName: profile.positionTemp,
        positionType: profile.posTypeNameTemp,
        positionLevel: profile.posLevelNameTemp,
        positionNumber: shortName,
        birthDate: profile.birthDate,
      };
    });

    return new HttpSuccess(formattedData);
  }

  /**
   * API รายการทะเบียนประวัติในระบบอื่น
   *
   * @summary ORG_065 - รายการทะเบียนประวัติในระบบอื่น
   *
   */
  @Get("otherSystem")
  async listProfileNoPermission(
    @Request() request: RequestWithUser,
    @Query("page") page: number = 1,
    @Query("pageSize") pageSize: number = 10,
    @Query()
    searchField?: "firstName" | "lastName" | "fullName" | "citizenId" | "position" | "posNo",
    @Query() searchKeyword: string = "",
    @Query() posType?: string,
    @Query() posLevel?: string,
    @Query() yearLeave?: number,
    @Query() isProbation?: boolean,
    @Query() isRetire?: boolean,
    @Query() nodeId?: string,
  ) {
    let queryLike =
      "CONCAT(profileEmployee.prefix, profileEmployee.firstName, ' ', profileEmployee.lastName) LIKE :keyword";
    if (searchField == "citizenId") {
      queryLike = "profileEmployee.citizenId LIKE :keyword";
    } else if (searchField == "position") {
      queryLike = "profileEmployee.position LIKE :keyword";
    } else if (searchField == "posNo") {
      queryLike = `
      CASE
        WHEN current_holders.orgChild4Id IS NOT NULL THEN CONCAT_WS(' ', orgChild4.orgChild4ShortName, NULLIF(current_holders.posMasterNoPrefix,''), current_holders.posMasterNo, NULLIF(current_holders.posMasterNoSuffix,''))
        WHEN current_holders.orgChild3Id IS NOT NULL THEN CONCAT_WS(' ', orgChild3.orgChild3ShortName, NULLIF(current_holders.posMasterNoPrefix,''), current_holders.posMasterNo, NULLIF(current_holders.posMasterNoSuffix,''))
        WHEN current_holders.orgChild2Id IS NOT NULL THEN CONCAT_WS(' ', orgChild2.orgChild2ShortName, NULLIF(current_holders.posMasterNoPrefix,''), current_holders.posMasterNo, NULLIF(current_holders.posMasterNoSuffix,''))
        WHEN current_holders.orgChild1Id IS NOT NULL THEN CONCAT_WS(' ', orgChild1.orgChild1ShortName, NULLIF(current_holders.posMasterNoPrefix,''), current_holders.posMasterNo, NULLIF(current_holders.posMasterNoSuffix,''))
        ELSE CONCAT_WS(' ', orgRoot.orgRootShortName, NULLIF(current_holders.posMasterNoPrefix,''), current_holders.posMasterNo, NULLIF(current_holders.posMasterNoSuffix,''))
      END LIKE :keyword
    `;
    }
    let posMaster = await this.posMasterRepo.findOne({
      where: {
        current_holder: { keycloak: request.user.sub },
        orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true },
      },
    });
    let revisionId = "";
    if (nodeId == null) {
      const findRevision = await this.orgRevisionRepo.findOne({
        where: { orgRevisionIsCurrent: true },
      });
      if (!findRevision) {
        throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
      }
      revisionId = findRevision.id;
      if (posMaster != null) nodeId = posMaster.orgRootId ?? "";
    } else {
      const findRoot = await this.orgRootRepository.findOne({
        where: { id: nodeId },
      });
      if (!findRoot) {
        throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบสำนักงานนี้ในระบบ");
      }
      revisionId = findRoot.orgRevisionId;
    }
    let nodeCondition = "current_holders.orgRootId = :nodeId";
    const [record, total] = await this.profileRepo
      .createQueryBuilder("profileEmployee")
      .leftJoinAndSelect("profileEmployee.posLevel", "posLevel")
      .leftJoinAndSelect("profileEmployee.posType", "posType")
      .leftJoinAndSelect("profileEmployee.current_holders", "current_holders")
      .leftJoinAndSelect("current_holders.positions", "positions")
      .leftJoinAndSelect("current_holders.orgRevision", "orgRevision")
      .leftJoinAndSelect("current_holders.orgRoot", "orgRoot")
      .leftJoinAndSelect("current_holders.orgChild1", "orgChild1")
      .leftJoinAndSelect("current_holders.orgChild2", "orgChild2")
      .leftJoinAndSelect("current_holders.orgChild3", "orgChild3")
      .leftJoinAndSelect("current_holders.orgChild4", "orgChild4")
      .where("current_holders.orgRevisionId = :orgRevisionId", { orgRevisionId: revisionId })
      .andWhere(
        posType != undefined && posType != null && posType != ""
          ? "posType.posTypeName LIKE :keyword1"
          : "1=1",
        {
          keyword1: `${posType}`,
        },
      )
      .andWhere(
        posLevel != undefined && posLevel != null && posLevel != ""
          ? "posLevel.posLevelName LIKE :keyword2"
          : "1=1",
        {
          keyword2: `${posLevel}`,
        },
      )
      .andWhere(
        isProbation != undefined && isProbation != null
          ? `profile.isProbation = ${isProbation}`
          : "1=1",
      )
      .andWhere(
        isRetire != undefined && isRetire != null
          ? isRetire == false
            ? `profile.dateLeave IS null`
            : `profile.dateLeave IS NOT NULL`
          : "1=1",
      )
      .andWhere(
        searchKeyword != undefined && searchKeyword != null && searchKeyword != ""
          ? queryLike
          : "1=1",
        {
          keyword: `%${searchKeyword}%`,
        },
      )
      .andWhere(nodeCondition, {
        nodeId: nodeId,
      })
      .orderBy("current_holders.posMasterNo", "ASC")
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getManyAndCount();

    const data = await Promise.all(
      record.map((_data) => {
        const shortName =
          _data.current_holders.length == 0
            ? null
            : _data.current_holders.find((x) => x.orgRevisionId == revisionId) != null &&
              _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild4 != null
              ? `${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild4.orgChild4ShortName} ${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.posMasterNo}`
              : _data.current_holders.find((x) => x.orgRevisionId == revisionId) != null &&
                _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild3 !=
                null
                ? `${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild3.orgChild3ShortName} ${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.posMasterNo}`
                : _data.current_holders.find((x) => x.orgRevisionId == revisionId) != null &&
                  _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild2 !=
                  null
                  ? `${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild2.orgChild2ShortName} ${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.posMasterNo}`
                  : _data.current_holders.find((x) => x.orgRevisionId == revisionId) != null &&
                    _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild1 !=
                    null
                    ? `${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild1.orgChild1ShortName} ${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.posMasterNo}`
                    : _data.current_holders.find((x) => x.orgRevisionId == revisionId) != null &&
                      _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRoot !=
                      null
                      ? `${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRoot.orgRootShortName} ${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.posMasterNo}`
                      : null;
        const root =
          _data.current_holders.length == 0 ||
            (_data.current_holders.find((x) => x.orgRevisionId == revisionId) != null &&
              _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRoot == null)
            ? null
            : _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRoot;

        const child1 =
          _data.current_holders == null ||
            _data.current_holders.length == 0 ||
            _data.current_holders.find((x) => x.orgRevisionId == revisionId) == null
            ? null
            : _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild1;

        const child2 =
          _data.current_holders == null ||
            _data.current_holders.length == 0 ||
            _data.current_holders.find((x) => x.orgRevisionId == revisionId) == null
            ? null
            : _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild2;

        const child3 =
          _data.current_holders == null ||
            _data.current_holders.length == 0 ||
            _data.current_holders.find((x) => x.orgRevisionId == revisionId) == null
            ? null
            : _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild3;

        const child4 =
          _data.current_holders == null ||
            _data.current_holders.length == 0 ||
            _data.current_holders.find((x) => x.orgRevisionId == revisionId) == null
            ? null
            : _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild4;

        let _root = root?.orgRootName;
        let _child1 = child1?.orgChild1Name;
        let _child2 = child2?.orgChild2Name;
        let _child3 = child3?.orgChild3Name;
        let _child4 = child4?.orgChild4Name;

        return {
          id: _data.id,
          avatar: _data.avatar,
          avatarName: _data.avatarName,
          prefix: _data.prefix,
          rank: _data.rank,
          firstName: _data.firstName,
          lastName: _data.lastName,
          citizenId: _data.citizenId,
          posLevel: `${_data.posType?.posTypeShortName ?? ""} ${_data.posLevel?.posLevelName ?? ""}`,
          posType: _data.posType == null ? null : _data.posType.posTypeName,
          posLevelId: _data.posLevel == null ? null : _data.posLevel.id,
          posTypeId: _data.posType == null ? null : _data.posType.id,
          position: _data.position,
          posNo: shortName,
          rootId: root == null ? null : root.id,
          root: root == null ? null : root.orgRootName,
          orgRootShortName: root == null ? null : root.orgRootShortName,
          orgRevisionId: root == null ? null : root.orgRevisionId,
          org:
            (_child4 == null ? "" : _child4 + "\n") +
            (_child3 == null ? "" : _child3 + "\n") +
            (_child2 == null ? "" : _child2 + "\n") +
            (_child1 == null ? "" : _child1 + "\n") +
            (_root == null ? "" : _root),
        };
      }),
    );

    return new HttpSuccess({ data: data, total });
  }

  /**
   * API Update amount
   *
   * @summary Update amount (ADMIN)
   *
   */
  @Get("update-amount")
  async updateProfileAmount(@Request() request: RequestWithUser) {
    const profiles = await this.profileRepo.find({
      order: { profileSalary: { order: "DESC" } },
      relations: ["profileSalary"],
    });
    profiles.map(async (x) => {
      const amount = x.profileSalary[0];
      x.amount = amount?.amount ?? 0;
      x.amountSpecial = amount?.amountSpecial ?? 0;
      x.positionSalaryAmount = amount?.positionSalaryAmount ?? 0;
      await this.profileRepo.save(x);
    });
    return new HttpSuccess();
  }

  /**
   * API ค้นหาและแสดงผู้พ้นจากราชการ ลูกจ้างประจำ กทม.
   *
   * @summary ค้นหาและแสดงผู้พ้นจากราชการ ลูกจ้างประจำ กทม.
   *
   */
  @Get("profileLeave")
  @Example({
    status: 200,
    message: "สำเร็จ",
    result: {
      data: [
        {
          page: 1,
          pageSize: 12,
          posLevel: "บ 1",
          posType: "บริการพื้นฐาน",
          isProbation: false,
          isRetire: true,
          node: 0,
          nodeId: "8349b6b6-d005-4eb7-9960-ceb5b96e1962",
          isAll: true,
          sortBy: "profile.dateAppoint",
          sort: "DESC",
          retireType: "RETIRE_DECEASED",
        },
      ],
      total: 1,
    },
  })
  async listProfileLeave(
    @Request() request: RequestWithUser,
    @Query("page") page: number = 1,
    @Query("pageSize") pageSize: number = 10,
    @Query()
    searchField?: "firstName" | "lastName" | "fullName" | "citizenId" | "position" | "posNo",
    @Query() searchKeyword: string = "",
    @Query() posType?: string,
    @Query() posLevel?: string,
    @Query() isProbation?: boolean,
    @Query() node?: number,
    @Query() nodeId?: string,
    @Query() isAll?: boolean,
    @Query() retireType?: string,
    @Query() sortBy: string = "profileEmployee.dateLeave",
    @Query() sort: "ASC" | "DESC" = "DESC",
  ) {
    let _data = await new permission().PermissionOrgList(request, "SYS_REGISTRY_RETIRE_EMP");

    const { data, total } = await this.profileLeaveService.getLeaveEmployees(request, {
      page,
      pageSize,
      searchField,
      searchKeyword,
      posType,
      posLevel,
      isProbation,
      node,
      nodeId,
      isAll,
      retireType,
      sortBy,
      sort,
      _data,
    });

    return new HttpSuccess({ data, total });
  }

  /**
   * API รายละเอียดรายการทะเบียนประวัติ
   *
   * @summary ORG_065 - รายละเอียดรายการทะเบียนประวัติ  (ADMIN) #70
   *
   * @param {string} id  Id ทะเบียนประวัติ
   */
  @Get("{id}")
  async detailProfile(@Path() id: string, @Request() req: RequestWithUser) {
    let _workflow = await new permission().Workflow(req, id, "SYS_REGISTRY_EMP");
    if (_workflow == false)
      await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_EMP", id);
    const profile: any = await this.profileRepo.findOne({
      relations: {
        posLevel: true,
        posType: true,
        // gender: true,
        // relationship: true,
        // bloodGroup: true,
      },
      where: { id },
    });

    if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    profile.profileType = "EMPLOYEE";

    return new HttpSuccess(profile);
  }

  @Get("admin/{id}")
  async detailProfileAdmin(@Path() id: string) {
    const profile = await this.profileRepo.findOne({
      relations: {
        posLevel: true,
        posType: true,
      },
      where: { id },
    });

    if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");

    return new HttpSuccess(profile);
  }

  /**
   * API รายการทะเบียนประวัติ
   *
   * @summary ORG_065 - รายการทะเบียนประวัติ (ADMIN) #70
   *
   */
  @Get()
  async listProfile(
    @Request() request: RequestWithUser,
    @Query("page") page: number = 1,
    @Query("pageSize") pageSize: number = 10,
    @Query()
    searchField?: "firstName" | "lastName" | "fullName" | "citizenId" | "position" | "posNo",
    @Query() searchKeyword: string = "",
    @Query() posType?: string,
    @Query() posLevel?: string,
    @Query() isProbation?: boolean,
    @Query() isRetire?: boolean,
    @Query() node?: number,
    @Query() nodeId?: string,
    @Query() isAll?: boolean,
    @Query() retireType?: string,
    @Query() sortBy?: string,
    @Query() sort: "ASC" | "DESC" = "ASC",
  ) {
    let _data = await new permission().PermissionOrgList(request, "SYS_REGISTRY_EMP");
    let queryLike =
      "CONCAT(profileEmployee.prefix, profileEmployee.firstName, ' ', profileEmployee.lastName) LIKE :keyword";
    if (searchField == "citizenId") {
      queryLike = "profileEmployee.citizenId LIKE :keyword";
    } else if (searchField == "position") {
      queryLike = "profileEmployee.position LIKE :keyword";
    } else if (searchField == "posNo") {
      queryLike = `
      CASE
        WHEN current_holders.orgChild4Id IS NOT NULL THEN CONCAT_WS(' ', orgChild4.orgChild4ShortName, NULLIF(current_holders.posMasterNoPrefix,''), current_holders.posMasterNo, NULLIF(current_holders.posMasterNoSuffix,''))
        WHEN current_holders.orgChild3Id IS NOT NULL THEN CONCAT_WS(' ', orgChild3.orgChild3ShortName, NULLIF(current_holders.posMasterNoPrefix,''), current_holders.posMasterNo, NULLIF(current_holders.posMasterNoSuffix,''))
        WHEN current_holders.orgChild2Id IS NOT NULL THEN CONCAT_WS(' ', orgChild2.orgChild2ShortName, NULLIF(current_holders.posMasterNoPrefix,''), current_holders.posMasterNo, NULLIF(current_holders.posMasterNoSuffix,''))
        WHEN current_holders.orgChild1Id IS NOT NULL THEN CONCAT_WS(' ', orgChild1.orgChild1ShortName, NULLIF(current_holders.posMasterNoPrefix,''), current_holders.posMasterNo, NULLIF(current_holders.posMasterNoSuffix,''))
        ELSE CONCAT_WS(' ', orgRoot.orgRootShortName, NULLIF(current_holders.posMasterNoPrefix,''), current_holders.posMasterNo, NULLIF(current_holders.posMasterNoSuffix,''))
      END LIKE :keyword
    `;
    }
    let nodeCondition = "1=1";
    let nodeAll = "";
    if (node === 0 && nodeId) {
      nodeCondition = "current_holders.orgRootId = :nodeId";
      if (isAll == false) nodeAll = " AND current_holders.orgChild1Id IS NULL";
    } else if (node === 1 && nodeId) {
      nodeCondition = "current_holders.orgChild1Id = :nodeId";
      if (isAll == false) nodeAll = " AND current_holders.orgChild2Id IS NULL";
    } else if (node === 2 && nodeId) {
      nodeCondition = "current_holders.orgChild2Id = :nodeId";
      if (isAll == false) nodeAll = " AND current_holders.orgChild3Id IS NULL";
    } else if (node === 3 && nodeId) {
      nodeCondition = "current_holders.orgChild3Id = :nodeId";
      if (isAll == false) nodeAll = " AND current_holders.orgChild4Id IS NULL";
    } else if (node === 4 && nodeId) {
      nodeCondition = "current_holders.orgChild4Id = :nodeId";
    }
    nodeCondition = nodeCondition + nodeAll;
    const findRevision = await this.orgRevisionRepo.findOne({
      where: { orgRevisionIsCurrent: true },
    });
    if (!findRevision) {
      throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
    }
    const [record, total] = await this.profileRepo
      .createQueryBuilder("profileEmployee")
      .leftJoinAndSelect("profileEmployee.posLevel", "posLevel")
      .leftJoinAndSelect("profileEmployee.posType", "posType")
      .leftJoinAndSelect("profileEmployee.current_holders", "current_holders")
      .leftJoinAndSelect("profileEmployee.profileEmployeeEmployment", "profileEmployeeEmployment")
      .leftJoinAndSelect("current_holders.positions", "positions")
      .leftJoinAndSelect("current_holders.orgRevision", "orgRevision")
      .leftJoinAndSelect("current_holders.orgRoot", "orgRoot")
      .leftJoinAndSelect("current_holders.orgChild1", "orgChild1")
      .leftJoinAndSelect("current_holders.orgChild2", "orgChild2")
      .leftJoinAndSelect("current_holders.orgChild3", "orgChild3")
      .leftJoinAndSelect("current_holders.orgChild4", "orgChild4")
      .where(node && nodeId ? "current_holders.orgRevisionId = :orgRevisionId" : "1=1", {
        orgRevisionId: node && nodeId ? findRevision.id : undefined,
      })
      .andWhere(
        _data.root != undefined && _data.root != null
          ? _data.root[0] != null
            ? `current_holders.orgRootId IN (:...root)`
            : `current_holders.orgRootId is null`
          : "1=1",
        {
          root: _data.root,
        },
      )
      .andWhere(
        _data.child1 != undefined && _data.child1 != null
          ? _data.child1[0] != null
            ? `current_holders.orgChild1Id IN (:...child1)`
            : // : `current_holders.orgChild1Id is ${_data.privilege == "PARENT" ? "not null" : "null"}`
            `current_holders.orgChild1Id is null`
          : "1=1",
        {
          child1: _data.child1,
        },
      )
      .andWhere(
        _data.child2 != undefined && _data.child2 != null
          ? _data.child2[0] != null
            ? `current_holders.orgChild2Id IN (:...child2)`
            : `current_holders.orgChild2Id is null`
          : "1=1",
        {
          child2: _data.child2,
        },
      )
      .andWhere(
        _data.child3 != undefined && _data.child3 != null
          ? _data.child3[0] != null
            ? `current_holders.orgChild3Id IN (:...child3)`
            : `current_holders.orgChild3Id is null`
          : "1=1",
        {
          child3: _data.child3,
        },
      )
      .andWhere(
        _data.child4 != undefined && _data.child4 != null
          ? _data.child4[0] != null
            ? `current_holders.orgChild4Id IN (:...child4)`
            : `current_holders.orgChild4Id is null`
          : "1=1",
        {
          child4: _data.child4,
        },
      )
      .andWhere(
        posType != undefined && posType != null && posType != ""
          ? "posType.posTypeName LIKE :keyword1"
          : "1=1",
        {
          keyword1: `${posType}`,
        },
      )
      .andWhere(
        posLevel != undefined && posLevel != null && posLevel != ""
          ? `CONCAT(posType.posTypeShortName,' ',posLevel.posLevelName) LIKE :keyword2`
          : "1=1",
        {
          keyword2: `${posLevel}`,
        },
      )
      .andWhere(
        isProbation != undefined && isProbation != null
          ? `profileEmployee.isProbation = ${isProbation}`
          : "1=1",
      )
      .andWhere(
        isRetire != undefined && isRetire != null
          ? isRetire == false
            ? `profileEmployee.isLeave IS FALSE`
            : isRetire == true && retireType != undefined && retireType != null
              ? `profileEmployee.isLeave IS TRUE AND profileEmployee.leaveType = '${retireType}'`
              : `profileEmployee.isLeave IS TRUE`
          : "1=1",
      )
      .andWhere("profileEmployee.employeeClass LIKE :type", {
        type: "PERM",
      })
      .andWhere(
        searchKeyword != undefined && searchKeyword != null && searchKeyword != ""
          ? queryLike
          : "1=1",
        {
          keyword: `%${searchKeyword}%`,
        },
      )
      .andWhere(nodeCondition, {
        nodeId: nodeId,
      })
      .addSelect("CASE WHEN current_holders.posMasterNo IS NULL THEN 1 ELSE 0 END", "sort_order")
      .orderBy(sortBy ? sortBy : "sort_order", sort)
      .addOrderBy("orgRoot.orgRootOrder", sort)
      .addOrderBy("orgChild1.orgChild1Order", sort)
      .addOrderBy("orgChild2.orgChild2Order", sort)
      .addOrderBy("orgChild3.orgChild3Order", sort)
      .addOrderBy("orgChild4.orgChild4Order", sort)
      .addOrderBy("current_holders.posMasterNo", sort)
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getManyAndCount();
    const data = await Promise.all(
      record.map((_data) => {
        const holder = _data.current_holders.find((x) => x.orgRevisionId == findRevision.id);
        const numPart = holder ? [holder.posMasterNoPrefix, holder.posMasterNo, holder.posMasterNoSuffix].filter((p) => p !== null && p !== undefined && p !== '').join(' ') : '';
        const shortName = !holder
          ? null
          : holder.orgChild4 != null
            ? `${holder.orgChild4.orgChild4ShortName} ${numPart}`
            : holder.orgChild3 != null
              ? `${holder.orgChild3.orgChild3ShortName} ${numPart}`
              : holder.orgChild2 != null
                ? `${holder.orgChild2.orgChild2ShortName} ${numPart}`
                : holder.orgChild1 != null
                  ? `${holder.orgChild1.orgChild1ShortName} ${numPart}`
                  : holder.orgRoot != null
                    ? `${holder.orgRoot.orgRootShortName} ${numPart}`
                    : null;
        const dateEmployment =
          _data.profileEmployeeEmployment.length == 0
            ? null
            : _data.profileEmployeeEmployment.reduce((latest, current) => {
              return latest.date > current.date ? latest : current;
            }).date;
        const root =
          _data.current_holders.length == 0 ||
            (_data.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
              _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot == null)
            ? null
            : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot;

        const child1 =
          _data.current_holders == null ||
            _data.current_holders.length == 0 ||
            _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) == null
            ? null
            : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1;

        const child2 =
          _data.current_holders == null ||
            _data.current_holders.length == 0 ||
            _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) == null
            ? null
            : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2;

        const child3 =
          _data.current_holders == null ||
            _data.current_holders.length == 0 ||
            _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) == null
            ? null
            : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3;

        const child4 =
          _data.current_holders == null ||
            _data.current_holders.length == 0 ||
            _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) == null
            ? null
            : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4;

        let _root = root?.orgRootName;
        let _child1 = child1?.orgChild1Name;
        let _child2 = child2?.orgChild2Name;
        let _child3 = child3?.orgChild3Name;
        let _child4 = child4?.orgChild4Name;
        return {
          id: _data.id,
          avatar: _data.avatar,
          avatarName: _data.avatarName,
          prefix: _data.prefix,
          rank: _data.rank,
          firstName: _data.firstName,
          lastName: _data.lastName,
          citizenId: _data.citizenId,
          posLevel: _data.posLevel == null ? null : _data.posLevel.posLevelName,
          posType: _data.posType == null ? null : _data.posType.posTypeName,
          posTypeShortName: _data.posType == null ? null : _data.posType.posTypeShortName,

          posLevelTemp: _data.posLevelNameTemp,
          posTypeTemp: _data.posTypeNameTemp,
          posTypeShortNameTemp: _data.posTypeShortNameTemp,

          posLevelId: _data.posLevel == null ? null : _data.posLevel.id,
          posTypeId: _data.posType == null ? null : _data.posType.id,
          positionId: _data.positionIdTemp,
          posmasterId: _data.posmasterIdTemp,

          position: _data.position,
          positionTemp: _data.positionTemp,

          posNo: _data.employeeClass == "TEMP" ? _data.posMasterNoTemp : shortName,
          employeeClass: _data.employeeClass == null ? null : _data.employeeClass,
          govAge: Extension.CalculateGovAge(_data.dateAppoint, 0, 0),
          age: Extension.CalculateAgeStrV2(_data.birthDate, 0, 0, "GET"),
          dateEmployment: dateEmployment,
          dateAppoint: _data.dateAppoint,
          dateStart: _data.dateStart,
          createdAt: _data.createdAt,
          dateRetireLaw: _data.dateRetireLaw,
          draftOrganizationOrganization:
            _data.nodeTemp == "0"
              ? _data.rootTemp
              : _data.nodeTemp == "1"
                ? _data.child1Temp
                : _data.nodeTemp == "2"
                  ? _data.child2Temp
                  : _data.nodeTemp == "3"
                    ? _data.child3Temp
                    : _data.nodeTemp == "4"
                      ? _data.child4Temp
                      : null,
          draftPositionEmployee: _data.positionTemp,
          draftOrgEmployeeStatus: _data.statusTemp,
          node: _data.nodeTemp,
          nodeId: _data.nodeIdTemp,
          nodeName:
            _data.nodeTemp == "0"
              ? _data.rootTemp
              : _data.nodeTemp == "1"
                ? _data.child1Temp
                : _data.nodeTemp == "2"
                  ? _data.child2Temp
                  : _data.nodeTemp == "3"
                    ? _data.child3Temp
                    : _data.nodeTemp == "4"
                      ? _data.child4Temp
                      : null,
          nodeShortName:
            _data.nodeTemp == "0"
              ? _data.rootShortNameTemp
              : _data.nodeTemp == "1"
                ? _data.child1ShortNameTemp
                : _data.nodeTemp == "2"
                  ? _data.child1ShortNameTemp
                  : _data.nodeTemp == "3"
                    ? _data.child3ShortNameTemp
                    : _data.nodeTemp == "4"
                      ? _data.child4ShortNameTemp
                      : null,
          root: _data.rootTemp ? _data.rootTemp : null,
          rootId: _data.rootIdTemp ? _data.rootIdTemp : null,
          rootShortName: _data.rootShortNameTemp ? _data.rootShortNameTemp : null,
          child1: _data.child1Temp ? _data.child1Temp : null,
          child1Id: _data.child1IdTemp ? _data.child1IdTemp : null,
          child1ShortName: _data.child1ShortNameTemp ? _data.child1ShortNameTemp : null,
          child2: _data.child2Temp ? _data.child2Temp : null,
          child2Id: _data.child2IdTemp ? _data.child2IdTemp : null,
          child2ShortName: _data.child2ShortNameTemp ? _data.child2ShortNameTemp : null,
          child3: _data.child3Temp ? _data.child3Temp : null,
          child3Id: _data.child3IdTemp ? _data.child3IdTemp : null,
          child3ShortName: _data.child3ShortNameTemp ? _data.child3ShortNameTemp : null,
          child4: _data.child4Temp ? _data.child4Temp : null,
          child4Id: _data.child4IdTemp ? _data.child4IdTemp : null,
          child4ShortName: _data.child4ShortNameTemp ? _data.child4ShortNameTemp : null,
          org:
            (_child4 == null ? "" : _child4 + "\n") +
            (_child3 == null ? "" : _child3 + "\n") +
            (_child2 == null ? "" : _child2 + "\n") +
            (_child1 == null ? "" : _child1 + "\n") +
            (_root == null ? "" : _root),
          orgTemp:
            (_data.child4Temp == null ? "" : _data.child4Temp + "\n") +
            (_data.child3Temp == null ? "" : _data.child3Temp + "\n") +
            (_data.child2Temp == null ? "" : _data.child2Temp + "\n") +
            (_data.child1Temp == null ? "" : _data.child1Temp + "\n") +
            (_data.rootTemp == null ? "" : _data.rootTemp),
        };
      }),
    );

    return new HttpSuccess({ data: data, total });
  }

  @Get("history/{id}")
  async getProfileHistory(@Path() id: string, @Request() req: RequestWithUser) {
    //await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_EMP", id); ไม่แน่ใจEMPปิดไว้ก่อน;
    const profile = await this.profileRepo.findOne({
      where: { id: id },
    });
    if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");

    const profileHistory = await this.profileHistoryRepo.find({
      where: { profileEmployeeId: id },
      order: { createdAt: "ASC" },
    });

    if (profileHistory.length == 0) {
      await this.profileHistoryRepo.save(
        Object.assign(new ProfileEmployeeHistory(), {
          ...profile,
          birthDateOld: profile?.birthDate,
          profileEmployeeId: id,
          id: undefined,
        }),
      );
      const firstRecord = await this.profileHistoryRepo.find({
        where: { profileEmployeeId: id },
        order: { createdAt: "ASC" },
      });
      return new HttpSuccess(firstRecord);
    }

    return new HttpSuccess(profileHistory);
  }

  /**
   * API ค้นหารายชื่อไปครองตำแหน่ง
   *
   * @summary ORG_063 - ค้นหารายชื่อไปครองตำแหน่ง (ADMIN) #68
   *
   */
  @Post("search")
  async searchProfileOrg(
    @Body()
    requestBody: {
      position?: string;
      posLevelId?: string;
      posTypeId?: string;
      page: number;
      pageSize: number;
      keyword?: string;
    },
  ) {
    const orgRevision = await this.orgRevisionRepo.findOne({
      where: {
        orgRevisionIsDraft: false,
        orgRevisionIsCurrent: true,
      },
      relations: ["employeePosMasters"],
    });
    if (!orgRevision) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบแบบร่างโครงสร้าง");
    }
    const [profiles, total] = await this.profileRepo
      .createQueryBuilder("profileEmployee")
      .leftJoinAndSelect("profileEmployee.current_holders", "current_holders")
      .leftJoinAndSelect("profileEmployee.posLevel", "posLevel")
      .leftJoinAndSelect("profileEmployee.posType", "posType")
      .where(
        requestBody.position != null && requestBody.position != ""
          ? "profileEmployee.position LIKE :position"
          : "1=1",
        {
          position: `%${requestBody.position}%`,
        },
      )
      .andWhere("profileEmployee.isLeave IS FALSE")
      .andWhere(
        new Brackets((qb) => {
          qb.where(
            requestBody.keyword != null && requestBody.keyword != ""
              ? "profileEmployee.prefix LIKE :keyword"
              : "1=1",
            {
              keyword: `%${requestBody.keyword}%`,
            },
          )
            .orWhere(
              requestBody.keyword != null && requestBody.keyword != ""
                ? "profileEmployee.firstName LIKE :keyword"
                : "1=1",
              {
                keyword: `%${requestBody.keyword}%`,
              },
            )
            .orWhere(
              requestBody.keyword != null && requestBody.keyword != ""
                ? "profileEmployee.lastName LIKE :keyword"
                : "1=1",
              {
                keyword: `%${requestBody.keyword}%`,
              },
            )
            .orWhere(
              requestBody.keyword != null && requestBody.keyword != ""
                ? "CONCAT(profileEmployee.prefix,profileEmployee.firstName,' ',profileEmployee.lastName) LIKE :keyword"
                : "1=1",
              {
                keyword: `%${requestBody.keyword}%`,
              },
            )
            .orWhere(
              requestBody.keyword != null && requestBody.keyword != ""
                ? "CONCAT(profileEmployee.firstName,' ',profileEmployee.lastName) LIKE :keyword"
                : "1=1",
              {
                keyword: `%${requestBody.keyword}%`,
              },
            )
            .orWhere(
              requestBody.keyword != null && requestBody.keyword != ""
                ? "profileEmployee.citizenId LIKE :keyword"
                : "1=1",
              {
                keyword: `%${requestBody.keyword}%`,
              },
            );
        }),
      )
      .andWhere(
        requestBody.posTypeId != null && requestBody.posTypeId != ""
          ? "profileEmployee.posTypeId LIKE :posTypeId"
          : "1=1",
        {
          posTypeId: `%${requestBody.posTypeId}%`,
        },
      )
      .andWhere(
        requestBody.posLevelId != null && requestBody.posLevelId != ""
          ? "profileEmployee.posLevelId LIKE :posLevelId"
          : "1=1",
        {
          posLevelId: `%${requestBody.posLevelId}%`,
        },
      )
      .andWhere(
        new Brackets((qb) => {
          qb.where("profileEmployee.id NOT IN (:...ids)", {
            ids:
              orgRevision.employeePosMasters
                .filter((x) => x.current_holderId != null)
                .map((x) => x.current_holderId).length == 0
                ? ["zxc"]
                : orgRevision.employeePosMasters
                  .filter((x) => x.current_holderId != null)
                  .map((x) => x.current_holderId),
          });
        }),
      )
      .andWhere("profileEmployee.employeeClass = :employeeClass", { employeeClass: "PERM" })
      .skip((requestBody.page - 1) * requestBody.pageSize)
      .take(requestBody.pageSize)
      .orderBy("posType.posTypeRank", "ASC")
      .addOrderBy("posLevel.posLevelRank", "ASC")
      .getManyAndCount();

    const data = profiles.map((_data) => ({
      id: _data.id,
      prefix: _data.prefix,
      rank: _data.rank,
      firstName: _data.firstName,
      lastName: _data.lastName,
      citizenId: _data.citizenId,
      posLevel:
        _data.posLevel == null
          ? null
          : `${_data?.posType?.posTypeShortName ?? ""} ${_data?.posLevel?.posLevelName ?? ""}`,
      posType: _data.posType == null ? null : _data.posType.posTypeName,
      position: _data.position,
    }));

    return new HttpSuccess({ data: data, total });
  }

  // /**
  //  * API ค้นหาประวัติการครองตำแหน่ง ลูกจ้าง
  //  *
  //  * @summary ค้นหาประวัติการครองตำแหน่ง ลูกจ้าง
  //  *
  //  */
  // @Post("search/history/oc")
  // async searchHistoryOC(
  //   @Body()
  //   requestBody: {
  //     posNo?: string;
  //     position?: string;
  //   },
  // ) {
  //   const profiles = await this.profileRepo
  //     .createQueryBuilder("profileEmployee")
  //     .leftJoinAndSelect("profileEmployee.profileSalary", "profileSalary")
  //     .select([
  //       "profileEmployee.id",
  //       "profileEmployee.prefix",
  //       "profileEmployee.firstName",
  //       "profileEmployee.lastName",
  //       "profileEmployee.citizenId",
  //       "profileSalary.position",
  //       "profileSalary.posNo",
  //       "profileSalary.date",
  //     ])
  //     .andWhere(
  //       requestBody.position != null && requestBody.position != "" && requestBody.posNo == undefined
  //         ? "profileSalary.position LIKE :position"
  //         : "1=2",
  //       {
  //         position: `%${requestBody.position}%`,
  //       },
  //     )
  //     .orWhere(
  //       requestBody.posNo != null && requestBody.posNo != "" && requestBody.position == undefined
  //         ? "profileSalars.posNo LIKE :posNo"
  //         : "1=2",
  //       {
  //         posNo: `%${requestBody.posNo}%`,
  //       },
  //     )
  //     .getMany();

  //   const mapData = profiles.map((profile) => {
  //     let profileSalary;
  //     if (profile.profileSalary && profile.profileSalary.length > 0) {
  //       profileSalary = profile.profileSalary.reduce((latest, current) => {
  //         return new Date(current.date) > new Date(latest.date) ? current : latest;
  //       });
  //     }
  //     return {
  //       id: profile.id,
  //       fullName: `${profile.prefix}${profile.firstName} ${profile.lastName}`,
  //       citizenId: profile.citizenId,
  //       position: profileSalary ? profileSalary.position : null,
  //       posNo: profileSalary ? profileSalary.posNo : null,
  //       date: profileSalary ? profileSalary.date : null,
  //     };
  //   });

  //   return new HttpSuccess(mapData);
  // }

  /**
   * API ค้นหาประวัติการครองตำแหน่ง ข้าราชการ
   *
   * @summary ค้นหาประวัติการครองตำแหน่ง ข้าราชการ
   *
   */
  @Post("search/history/oc")
  async searchOC(
    @Body()
    requestBody: {
      posNo?: string;
      position?: string;
    },
  ) {
    let queryLike = `
        CASE 
          WHEN current_holders.orgChild4Id IS NOT NULL THEN CONCAT(orgChild4.orgChild4ShortName, " ", current_holders.posMasterNo)
          WHEN current_holders.orgChild3Id IS NOT NULL THEN CONCAT(orgChild3.orgChild3ShortName, " ", current_holders.posMasterNo)
          WHEN current_holders.orgChild2Id IS NOT NULL THEN CONCAT(orgChild2.orgChild2ShortName, " ", current_holders.posMasterNo)
          WHEN current_holders.orgChild1Id IS NOT NULL THEN CONCAT(orgChild1.orgChild1ShortName, " ", current_holders.posMasterNo)
          ELSE CONCAT(orgRoot.orgRootShortName, " ", current_holders.posMasterNo)
        END LIKE :keyword
      `;

    const profiles = await this.profileRepo
      .createQueryBuilder("profileEmployee")
      .leftJoinAndSelect("profileEmployee.current_holders", "current_holders")
      .leftJoinAndSelect("current_holders.positions", "positions")
      .leftJoinAndSelect("current_holders.orgRoot", "orgRoot")
      .leftJoinAndSelect("current_holders.orgChild1", "orgChild1")
      .leftJoinAndSelect("current_holders.orgChild2", "orgChild2")
      .leftJoinAndSelect("current_holders.orgChild3", "orgChild3")
      .leftJoinAndSelect("current_holders.orgChild4", "orgChild4")
      .where("positions.positionIsSelected = :posIsSelected", { posIsSelected: true })
      .andWhere(
        new Brackets((qb) => {
          qb.orWhere(
            requestBody.posNo != undefined && requestBody.posNo != null && requestBody.posNo != ""
              ? queryLike
              : "1=1",
            {
              keyword: `%${requestBody.posNo}%`,
            },
          );
        }),
      )
      .andWhere(
        requestBody.position != null && requestBody.position !== ""
          ? "positions.positionName LIKE :positionName"
          : "1=1",
        { positionName: `%${requestBody.position}%` },
      )
      .getMany();

    const mapData = profiles
      .map((profile) => {
        const shortNames = profile.current_holders.map((holder) => {
          const shortName =
            holder.orgChild4?.orgChild4ShortName ||
            holder.orgChild3?.orgChild3ShortName ||
            holder.orgChild2?.orgChild2ShortName ||
            holder.orgChild1?.orgChild1ShortName ||
            holder.orgRoot?.orgRootShortName;
          return `${shortName || ""} ${[holder.posMasterNoPrefix, holder.posMasterNo, holder.posMasterNoSuffix].filter((p) => p !== null && p !== undefined && p !== '').join(' ')}`;
        });
        return profile.current_holders.map((holder, index) => {
          const position = holder.positions.find((position) => position.posMasterId === holder.id);
          const positionName = position ? position.positionName : null;

          return {
            id: profile.id,
            posMasterId: holder.id,
            fullName: `${profile.prefix}${profile.firstName} ${profile.lastName}`,
            citizenId: profile.citizenId,
            posNo: shortNames[index],
            positionName: positionName,
            date: holder.createdAt,
          };
        });
      })
      .flat();

    return new HttpSuccess(mapData);
  }

  /**
   * API ข้อมูลทะเบียนประวัติตาม keycloak
   *
   * @summary ORG_065 - ข้อมูลทะเบียนประวัติตาม keycloak (ADMIN) #70
   *
   */
  @Get("keycloak/position")
  async getProfileByKeycloak(
    @Request() request: { user: Record<string, any> },
    @Query("revisionId") revisionId?: string,
  ) {
    const profile = await this.profileRepo.findOne({
      where: { keycloak: request.user.sub },
      relations: [
        "posLevel",
        "posType",
        "current_holders",
        "current_holders.orgRoot",
        "current_holders.orgChild1",
        "current_holders.orgChild2",
        "current_holders.orgChild3",
        "current_holders.orgChild4",
        // "profileSalary",
      ],
      // order: {
      //   profileSalary: {
      //     order: "DESC",
      //   },
      // },
    });
    if (!profile) {
      if (request.user.role.includes("SUPER_ADMIN")) {
        return new HttpSuccess(null);
      } else {
        throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลบุคคลนี้ในระบบ");
      }
    }

    let orgRevisionPublish: any = await this.orgRevisionRepo
      .createQueryBuilder("orgRevision")
      .where("orgRevision.orgRevisionIsDraft = false")
      .andWhere("orgRevision.orgRevisionIsCurrent = true")
      .getOne();
    if (!orgRevisionPublish) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบแบบร่างโครงสร้าง");
    }

    if (revisionId) {
      orgRevisionPublish = await this.orgRevisionRepo
        .createQueryBuilder("orgRevision")
        .where("orgRevision.id = :revisionId", { revisionId })
        .getOne();
      if (!orgRevisionPublish) {
        throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบแบบร่างโครงสร้าง");
      }
    }

    const posMaster =
      profile.current_holders == null ||
        profile.current_holders.length == 0 ||
        profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) == null
        ? null
        : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id);

    const root =
      profile.current_holders == null ||
        profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgRoot == null
        ? null
        : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgRoot;
    const child1 =
      profile.current_holders == null ||
        profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild1 ==
        null
        ? null
        : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild1;
    const child2 =
      profile.current_holders == null ||
        profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild2 ==
        null
        ? null
        : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild2;
    const child3 =
      profile.current_holders == null ||
        profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild3 ==
        null
        ? null
        : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild3;
    const child4 =
      profile.current_holders == null ||
        profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild4 ==
        null
        ? null
        : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild4;

    const position = await this.employeePositionRepository.findOne({
      where: {
        posMasterId: posMaster?.id,
      },
    });

    const _profile: any = {
      profileId: profile.id,
      prefix: profile.prefix,
      rank: profile.rank,
      avatar: profile.avatar,
      isProbation: profile.isProbation,
      avatarName: profile.avatarName,
      firstName: profile.firstName,
      lastName: profile.lastName,
      citizenId: profile.citizenId,
      birthDate: profile.birthDate,
      position: profile.position,
      leaveDate: profile.dateLeave,
      dateStart: profile.dateStart,
      dateRetireLaw: profile.dateRetireLaw,
      posMaster: posMaster == null ? null : posMaster.posMasterNo,
      posMasterNo: posMaster == null ? null : posMaster.posMasterNo,
      posLevelName:
        profile.posLevel == null && profile.posType == null
          ? null
          : `${profile.posType.posTypeShortName} ${profile.posLevel.posLevelName}`,
      posLevelRank: profile.posLevel == null ? null : profile.posLevel.posLevelRank,
      posLevelId: profile.posLevel == null ? null : profile.posLevel.id,
      posTypeName: profile.posType == null ? null : profile.posType.posTypeName,
      posTypeShortName: profile.posType == null ? null : profile.posType.posTypeShortName,
      posTypeRank: profile.posType == null ? null : profile.posType.posTypeRank,
      posTypeId: profile.posType == null ? null : profile.posType.id,
      posExecutiveName: null,
      posExecutivePriority: null,
      posExecutiveId: null,
      rootId: root == null ? null : root.id,
      rootDnaId: root == null ? null : root.ancestorDNA,
      root: root == null ? null : root.orgRootName,
      rootShortName: root == null ? null : root.orgRootShortName,
      child1Id: child1 == null ? null : child1.id,
      child1DnaId: child1 == null ? null : child1.ancestorDNA,
      child1: child1 == null ? null : child1.orgChild1Name,
      child1ShortName: child1 == null ? null : child1.orgChild1ShortName,
      child2Id: child2 == null ? null : child2.id,
      child2DnaId: child2 == null ? null : child2.ancestorDNA,
      child2: child2 == null ? null : child2.orgChild2Name,
      child2ShortName: child2 == null ? null : child2.orgChild2ShortName,
      child3Id: child3 == null ? null : child3.id,
      child3DnaId: child3 == null ? null : child3.ancestorDNA,
      child3: child3 == null ? null : child3.orgChild3Name,
      child3ShortName: child3 == null ? null : child3.orgChild3ShortName,
      child4Id: child4 == null ? null : child4.id,
      child4DnaId: child4 == null ? null : child4.ancestorDNA,
      child4: child4 == null ? null : child4.orgChild4Name,
      child4ShortName: child4 == null ? null : child4.orgChild4ShortName,
      node: null,
      nodeId: null,
      nodeDnaId: null,
      salary: profile ? profile.amount : null,
      amountSpecial: profile ? profile.amountSpecial : null,
      posNo: null,
    };
    const _numPart = posMaster ? [posMaster.posMasterNoPrefix, posMaster.posMasterNo, posMaster.posMasterNoSuffix].filter((p) => p !== null && p !== undefined && p !== '').join(' ') : '';
    if (_profile.child4Id != null) {
      _profile.node = 4;
      _profile.nodeId = _profile.child4Id;
      _profile.nodeDnaId = _profile.child4DnaId;
      _profile.nodeShortName = _profile.child4ShortName;
      _profile.posNo = `${_profile.child4ShortName} ${_numPart}`;
    } else if (_profile.child3Id != null) {
      _profile.node = 3;
      _profile.nodeId = _profile.child3Id;
      _profile.nodeDnaId = _profile.child3DnaId;
      _profile.nodeShortName = _profile.child3ShortName;
      _profile.posNo = `${_profile.child3ShortName} ${_numPart}`;
    } else if (_profile.child2Id != null) {
      _profile.node = 2;
      _profile.nodeId = _profile.child2Id;
      _profile.nodeDnaId = _profile.child2DnaId;
      _profile.nodeShortName = _profile.child2ShortName;
      _profile.posNo = `${_profile.child2ShortName} ${_numPart}`;
    } else if (_profile.child1Id != null) {
      _profile.node = 1;
      _profile.nodeId = _profile.child1Id;
      _profile.nodeDnaId = _profile.child1DnaId;
      _profile.nodeShortName = _profile.child1ShortName;
      _profile.posNo = `${_profile.child1ShortName} ${_numPart}`;
    } else if (_profile.rootId != null) {
      _profile.node = 0;
      _profile.nodeId = _profile.rootId;
      _profile.nodeDnaId = _profile.rootDnaId;
      _profile.nodeShortName = _profile.rootShortName;
      _profile.posNo = `${_profile.rootShortName} ${_numPart}`;
    }
    return new HttpSuccess(_profile);
  }

  /**
   * API ค้นหาข้อมูลทะเบียนประวัติ
   *
   * @summary ORG_065 - ค้นหาข้อมูลทะเบียนประวัติ (ADMIN) #70
   *
   */
  @Post("search-personal")
  async getProfileBySearchKeyword(
    @Request() request: RequestWithUser,
    @Query("page") page: number = 1,
    @Query("pageSize") pageSize: number = 10,
    @Body()
    body: {
      fieldName: string;
      keyword?: string;
      system?: string;
    },
  ) {
    // ค้นหารายชื่อถ้าไม่ส่ง system มาให้ default ตามทะเบียนประวัติ
    let _system: string = "SYS_REGISTRY_EMP";
    if (body.system) _system = body.system;
    let _data = await new permission().PermissionOrgList(request, _system);
    const findRevision = await this.orgRevisionRepo.findOne({
      where: { orgRevisionIsCurrent: true },
    });
    if (!findRevision) {
      throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
    }
    let queryLike = "1=1";
    switch (body.fieldName) {
      case "citizenId":
        queryLike = "profile.citizenId LIKE :keyword";
        break;

      case "fullName":
        queryLike =
          "CONCAT(profile.prefix, profile.firstName, ' ', profile.lastName) LIKE :keyword";
        break;

      case "position":
        queryLike = "profile.position LIKE :keyword";
        break;

      case "posNo":
        queryLike = `
          CASE 
            WHEN current_holders.orgChild4Id IS NOT NULL THEN CONCAT(orgChild4.orgChild4ShortName, " ", current_holders.posMasterNo)
            WHEN current_holders.orgChild3Id IS NOT NULL THEN CONCAT(orgChild3.orgChild3ShortName, " ", current_holders.posMasterNo)
            WHEN current_holders.orgChild2Id IS NOT NULL THEN CONCAT(orgChild2.orgChild2ShortName, " ", current_holders.posMasterNo)
            WHEN current_holders.orgChild1Id IS NOT NULL THEN CONCAT(orgChild1.orgChild1ShortName, " ", current_holders.posMasterNo)
            ELSE CONCAT(orgRoot.orgRootShortName, " ", current_holders.posMasterNo)
          END LIKE :keyword
        `;
        break;

      case "posType":
        queryLike = "posType.posTypeName LIKE :keyword";
        break;

      case "posLevel":
        queryLike = "posLevel.posLevelName LIKE :keyword";
        break;

      case "organization":
        queryLike = "orgRoot.orgRootName LIKE :keyword";
        break;

      default:
        queryLike = "1=1";
        break;
    }

    const [findProfile, total] = await this.profileRepo
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.posType", "posType")
      .leftJoinAndSelect("profile.posLevel", "posLevel")
      .leftJoinAndSelect("profile.current_holders", "current_holders")
      .leftJoinAndSelect("current_holders.orgRoot", "orgRoot")
      .leftJoinAndSelect("current_holders.orgChild1", "orgChild1")
      .leftJoinAndSelect("current_holders.orgChild2", "orgChild2")
      .leftJoinAndSelect("current_holders.orgChild3", "orgChild3")
      .leftJoinAndSelect("current_holders.orgChild4", "orgChild4")
      .where("current_holders.orgRevision = :revisionId", { revisionId: findRevision?.id })
      .andWhere(
        _data.root != undefined && _data.root != null
          ? _data.root[0] != null
            ? `current_holders.orgRootId IN (:...root)`
            : `current_holders.orgRootId is null`
          : "1=1",
        { root: _data.root },
      )
      .andWhere(
        _data.child1 != undefined && _data.child1 != null
          ? _data.child1[0] != null
            ? `current_holders.orgChild1Id IN (:...child1)`
            : // : `current_holders.orgChild1Id is ${_data.privilege == "PARENT" ? "not null" : "null"}`
            `current_holders.orgChild1Id is null`
          : "1=1",
        { child1: _data.child1 },
      )
      .andWhere(
        _data.child2 != undefined && _data.child2 != null
          ? _data.child2[0] != null
            ? `current_holders.orgChild2Id IN (:...child2)`
            : `current_holders.orgChild2Id is null`
          : "1=1",
        { child2: _data.child2 },
      )
      .andWhere(
        _data.child3 != undefined && _data.child3 != null
          ? _data.child3[0] != null
            ? `current_holders.orgChild3Id IN (:...child3)`
            : `current_holders.orgChild3Id is null`
          : "1=1",
        { child3: _data.child3 },
      )
      .andWhere(
        _data.child4 != undefined && _data.child4 != null
          ? _data.child4[0] != null
            ? `current_holders.orgChild4Id IN (:...child4)`
            : `current_holders.orgChild4Id is null`
          : "1=1",
        { child4: _data.child4 },
      )
      .andWhere(
        new Brackets((qb) => {
          qb.orWhere(body.keyword ? queryLike : "1=1", { keyword: `%${body.keyword}%` });
        }),
      )
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getManyAndCount();

    const mapDataProfile = await Promise.all(
      findProfile.map(async (item: ProfileEmployee) => {
        const fullName = `${item.prefix}${item.firstName} ${item.lastName}`;
        const shortName =
          item.current_holders.length == 0
            ? null
            : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
              item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4 !=
              null
              ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4.orgChild4ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
              : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
                item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3 !=
                null
                ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3.orgChild3ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
                : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
                  item.current_holders.find((x) => x.orgRevisionId == findRevision.id)
                    ?.orgChild2 != null
                  ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2.orgChild2ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
                  : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
                    item.current_holders.find((x) => x.orgRevisionId == findRevision.id)
                      ?.orgChild1 != null
                    ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1.orgChild1ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
                    : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) !=
                      null &&
                      item.current_holders.find((x) => x.orgRevisionId == findRevision.id)
                        ?.orgRoot != null
                      ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot.orgRootShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
                      : null;

        const root =
          item.current_holders.length == 0 ||
            (item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
              item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot == null)
            ? null
            : item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot;

        const rootHolder = item.current_holders?.find(
          (x) => x.orgRevisionId == findRevision.id,
        )?.orgRoot;
        const child1Holder = item.current_holders?.find(
          (x) => x.orgRevisionId == findRevision.id,
        )?.orgChild1;
        const child2Holder = item.current_holders?.find(
          (x) => x.orgRevisionId == findRevision.id,
        )?.orgChild2;
        const child3Holder = item.current_holders?.find(
          (x) => x.orgRevisionId == findRevision.id,
        )?.orgChild3;
        const child4Holder = item.current_holders?.find(
          (x) => x.orgRevisionId == findRevision.id,
        )?.orgChild4;
        const posMasterNo = item.current_holders?.find(
          (x) => x.orgRevisionId == findRevision.id,
        )?.posMasterNo;

        const latestProfileEducation = await this.profileEducationRepo.findOne({
          where: { profileEmployeeId: item.id, isDeleted: false },
          order: { level: "ASC" },
        });

        return {
          id: item.id,
          prefix: item.prefix,
          rank: item.rank,
          firstName: item.firstName,
          lastName: item.lastName,
          position: item.position,
          citizenId: item.citizenId,
          email: item.email,
          phone: item.phone,
          name: fullName,
          birthDate: item.birthDate,
          positionLevel: item.posLevelId,
          positionLevelName: item.posLevel?.posLevelName,
          positionType: item.posTypeId,
          positionTypeName: item.posType?.posTypeName,
          posNo: shortName,
          organization: root == null ? null : root.orgRootName,
          salary: item.amount,
          root: rootHolder?.orgRootName ?? null,
          rootId: rootHolder?.id ?? null,
          rootDnaId: rootHolder?.ancestorDNA ?? null,
          rootShortName: rootHolder?.orgRootShortName ?? null,
          child1: child1Holder?.orgChild1Name ?? null,
          child1Id: child1Holder?.id ?? null,
          child1DnaId: child1Holder?.ancestorDNA ?? null,
          child1ShortName: child1Holder?.orgChild1ShortName ?? null,
          child2: child2Holder?.orgChild2Name ?? null,
          child2Id: child2Holder?.id ?? null,
          child2DnaId: child2Holder?.ancestorDNA ?? null,
          child2ShortName: child2Holder?.orgChild2ShortName ?? null,
          child3: child3Holder?.orgChild3Name ?? null,
          child3Id: child3Holder?.id ?? null,
          child3DnaId: child3Holder?.ancestorDNA ?? null,
          child3ShortName: child3Holder?.orgChild3ShortName ?? null,
          child4: child4Holder?.orgChild4Name ?? null,
          child4Id: child4Holder?.id ?? null,
          child4DnaId: child4Holder?.ancestorDNA ?? null,
          child4ShortName: child4Holder?.orgChild4ShortName ?? null,
          posMasterNo: posMasterNo ?? null,
          posTypeId: item.posTypeId,
          posTypeName: item.posType?.posTypeName,
          posLevelId: item.posLevelId,
          posLevelName:
            item.posLevel == null && item.posType == null
              ? null
              : `${item.posType?.posTypeShortName} ${item.posLevel?.posLevelName}`,
          educationDegree:
            latestProfileEducation != null && latestProfileEducation.educationLevel != null
              ? latestProfileEducation.educationLevel
              : null,
        };
      }),
    );

    return new HttpSuccess({ data: mapDataProfile, total });
  }

  /**
   * API ค้นหาผู้บังคับบัญชา
   *
   * @summary ORG_069 - ค้นหาผู้บังคับบัญชา (ADMIN) #75
   *
   */
  @Get("search/commander")
  async searchCommander(@Request() request: { user: Record<string, any> }) {
    let fullName_: any = {};
    let position_: any = {};
    let commanderAboveFullname_: any = {};
    let commanderAbovePosition_: any = {};
    let commanderFullname_: any = {};
    let commanderPosition_: any = {};

    const findProfile = await this.profileRepo.findOne({
      where: { keycloak: request.user.sub },
    });

    const findRevision = await this.orgRevisionRepo.findOne({
      where: {
        orgRevisionIsCurrent: true,
      },
    });

    const findPosMaster = await this.posMasterRepo.findOne({
      where: {
        current_holderId: findProfile?.id,
        orgRevisionId: findRevision?.id,
      },
    });

    let node = 4;
    let childId = findPosMaster?.orgChild4Id;
    let condition: any = { orgChild4Id: childId };

    if (findPosMaster?.orgChild4Id == null && findPosMaster?.orgChild3Id != null) {
      node = 3;
      childId = findPosMaster?.orgChild3Id;
      condition = { orgChild3Id: childId, orgChild4Id: IsNull() };
    } else if (findPosMaster?.orgChild3Id == null && findPosMaster?.orgChild2Id != null) {
      node = 2;
      childId = findPosMaster?.orgChild2Id;
      condition = { orgChild2Id: childId, orgChild3Id: IsNull() };
    } else if (findPosMaster?.orgChild2Id == null && findPosMaster?.orgChild1Id != null) {
      node = 1;
      childId = findPosMaster?.orgChild1Id;
      condition = { orgChild1Id: childId, orgChild2Id: IsNull() };
    } else if (findPosMaster?.orgChild1Id == null) {
      node = 0;
      childId = findPosMaster?.orgRootId;
      condition = { orgRootId: childId, orgChild1Id: IsNull() };
    }

    const findCmd = await this.posMasterRepo.findOne({
      where: {
        current_holderId: Not(IsNull()) || Not(""),
        orgRevisionId: findRevision?.id,
        ...condition,
      },
      relations: ["current_holder"],
      order: { posMasterOrder: "ASC" },
    });
    let findOSAB: EmployeePosMaster | null = null;
    let findTSAB: EmployeePosMaster | null = null;
    //หาผู้บังคับบัญชาที่เหนือขึ้นไปอีก 1 ขั้น
    if (node !== 0) {
      findOSAB = await AppDataSource.getRepository(EmployeePosMaster)
        .createQueryBuilder("posMaster")
        .leftJoinAndSelect("posMaster.current_holder", "current_holder")
        .where("posMaster.current_holderId IS NOT NULL")
        .andWhere("posMaster.orgRevisionId = :revisionId", { revisionId: findRevision?.id })
        .andWhere(
          new Brackets((qb) => {
            if (node === 4) {
              qb.andWhere("posMaster.orgChild4Id IS NULL");
              qb.andWhere("posMaster.orgChild3Id = :childId", {
                childId: findPosMaster?.orgChild3Id,
              });
            } else if (node === 3) {
              qb.andWhere("posMaster.orgChild3Id IS NULL");
              qb.andWhere("posMaster.orgChild2Id = :childId", {
                childId: findPosMaster?.orgChild2Id,
              });
            } else if (node === 2) {
              qb.andWhere("posMaster.orgChild2Id IS NULL");
              qb.andWhere("posMaster.orgChild1Id = :childId", {
                childId: findPosMaster?.orgChild1Id,
              });
            } else if (node === 1) {
              qb.andWhere("posMaster.orgChild1Id IS NULL");
              qb.andWhere("posMaster.orgRootId = :childId", { childId: findPosMaster?.orgRootId });
            }
          }),
        )
        .orderBy("posMaster.posMasterOrder", "ASC")
        .getOne();
    }

    //หาผู้บังคับบัญชาที่เหนือขึ้นไปอีก 2 ขั้น
    if (node !== 0 && node !== 1) {
      findTSAB = await AppDataSource.getRepository(EmployeePosMaster)
        .createQueryBuilder("posMaster")
        .leftJoinAndSelect("posMaster.current_holder", "current_holder")
        .where("posMaster.current_holderId IS NOT NULL")
        .andWhere("posMaster.orgRevisionId = :revisionId", { revisionId: findRevision?.id })
        .andWhere(
          new Brackets((qb) => {
            if (node === 4) {
              qb.andWhere("posMaster.orgChild3Id IS NULL");
              qb.andWhere("posMaster.orgChild2Id = :childId", {
                childId: findPosMaster?.orgChild2Id,
              });
            } else if (node === 3) {
              qb.andWhere("posMaster.orgChild2Id IS NULL");
              qb.andWhere("posMaster.orgChild1Id = :childId", {
                childId: findPosMaster?.orgChild1Id,
              });
            } else if (node === 2) {
              qb.andWhere("posMaster.orgChild1Id IS NULL");
              qb.andWhere("posMaster.orgRootId = :childId", {
                childId: findPosMaster?.orgRootId,
              });
            }
          }),
        )
        .orderBy("posMaster.posMasterOrder", "ASC")
        .getOne();
    }
    fullName_ =
      (findProfile?.prefix ?? "") +
      (findProfile?.firstName ?? "") +
      (findProfile?.firstName ? " " : "") +
      (findProfile?.lastName ?? "");
    position_ = findProfile?.position ?? "";
    commanderFullname_ =
      (findCmd?.current_holder?.prefix ?? "") +
      (findCmd?.current_holder?.firstName ?? "") +
      (findCmd?.current_holder?.firstName ? " " : "") +
      (findCmd?.current_holder?.lastName ?? "");
    commanderPosition_ = findCmd?.current_holder?.position ?? "";
    commanderAboveFullname_ =
      (findOSAB?.current_holder?.prefix ?? "") +
      (findOSAB?.current_holder?.firstName ?? "") +
      (findOSAB?.current_holder?.firstName ? " " : "") +
      (findOSAB?.current_holder?.lastName ?? "");
    commanderAbovePosition_ = findOSAB?.current_holder?.position ?? "";

    if (findCmd?.current_holderId == findProfile?.id) {
      commanderFullname_ =
        (findOSAB?.current_holder?.prefix ?? "") +
        (findOSAB?.current_holder?.firstName ?? "") +
        (findOSAB?.current_holder?.firstName ? " " : "") +
        (findOSAB?.current_holder?.lastName ?? "");
      commanderPosition_ = findOSAB?.current_holder?.position ?? "";
      commanderAboveFullname_ =
        (findTSAB?.current_holder?.prefix ?? "") +
        (findTSAB?.current_holder?.firstName ?? "") +
        (findTSAB?.current_holder?.firstName ? " " : "") +
        (findTSAB?.current_holder?.lastName ?? "");
      commanderAbovePosition_ = findTSAB?.current_holder?.position ?? "";

      const formattedDataTSAB = {
        fullname: fullName_,
        position: position_,
        commanderAboveFullname: commanderAboveFullname_,
        commanderAbovePosition: commanderAbovePosition_,
        commanderFullname: commanderFullname_,
        commanderPosition: commanderPosition_,
      };
      return new HttpSuccess(formattedDataTSAB);
    }

    const formattedData = {
      fullname: fullName_,
      position: position_,
      commanderAboveFullname: commanderAboveFullname_,
      commanderAbovePosition: commanderAbovePosition_,
      commanderFullname: commanderFullname_,
      commanderPosition: commanderPosition_,
    };
    return new HttpSuccess(formattedData);
  }

  /**
   * API บันทึกตำแหน่งลูกจ้างชั่วคราว
   *
   * @summary บันทึกตำแหน่งลูกจ้างชั่วคราว (ADMIN)
   *
   * @param {string} id  Id ทะเบียนประวัติลูกจ้างชั่วคราว
   */
  @Put("position/{id}")
  async positionProfileEmployee(
    @Request() request: RequestWithUser,
    @Path() id: string,
    @Body() body: UpdatePositionTempProfileEmployee,
  ) {
    // await new permission().PermissionOrgUserUpdate(request, "SYS_REGISTRY_EMP", id);//ไม่แน่ใจEMPปิดไว้ก่อน
    if (body.posLevelId === "") body.posLevelId = null;
    if (body.posTypeId === "") body.posTypeId = null;

    if (body.posLevelId && !(await this.posLevelRepo.findOneBy({ id: body.posLevelId }))) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลระดับตำแหน่งนี้");
    }
    if (body.posTypeId && !(await this.posTypeRepo.findOneBy({ id: body.posTypeId }))) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลประเภทตำแหน่งนี้");
    }
    const profileEmp = await this.profileRepo.findOneBy({ id });
    if (!profileEmp) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์นี้");

    switch (body.node) {
      case 0: {
        const data = await this.orgRootRepository.findOne({
          where: { id: body.nodeId },
        });
        if (data != null) {
          profileEmp.rootIdTemp = data.id;
          profileEmp.rootTemp = data.orgRootName;
          profileEmp.rootShortNameTemp = data.orgRootShortName;
        }
      }
      case 1: {
        const data = await this.child1Repository.findOne({
          where: { id: body.nodeId },
          relations: ["orgRoot"],
        });
        if (data != null) {
          profileEmp.rootIdTemp = data.orgRoot.id;
          profileEmp.rootTemp = data.orgRoot.orgRootName;
          profileEmp.rootShortNameTemp = data.orgRoot.orgRootShortName;
          profileEmp.child1IdTemp = data.id;
          profileEmp.child1Temp = data.orgChild1Name;
          profileEmp.child1ShortNameTemp = data.orgChild1ShortName;
        }
      }
      case 2: {
        const data = await this.child2Repository.findOne({
          where: { id: body.nodeId },
          relations: ["orgRoot", "orgChild1"],
        });
        if (data != null) {
          profileEmp.rootIdTemp = data.orgRoot.id;
          profileEmp.rootTemp = data.orgRoot.orgRootName;
          profileEmp.rootShortNameTemp = data.orgRoot.orgRootShortName;
          profileEmp.child1IdTemp = data.orgChild1.id;
          profileEmp.child1Temp = data.orgChild1.orgChild1Name;
          profileEmp.child1ShortNameTemp = data.orgChild1.orgChild1ShortName;
          profileEmp.child2IdTemp = data.id;
          profileEmp.child2Temp = data.orgChild2Name;
          profileEmp.child2ShortNameTemp = data.orgChild2ShortName;
        }
      }
      case 3: {
        const data = await this.child3Repository.findOne({
          where: { id: body.nodeId },
          relations: ["orgRoot", "orgChild1", "orgChild2"],
        });
        if (data != null) {
          profileEmp.rootIdTemp = data.orgRoot.id;
          profileEmp.rootTemp = data.orgRoot.orgRootName;
          profileEmp.rootShortNameTemp = data.orgRoot.orgRootShortName;
          profileEmp.child1IdTemp = data.orgChild1.id;
          profileEmp.child1Temp = data.orgChild1.orgChild1Name;
          profileEmp.child1ShortNameTemp = data.orgChild1.orgChild1ShortName;
          profileEmp.child2IdTemp = data.orgChild2.id;
          profileEmp.child2Temp = data.orgChild2.orgChild2Name;
          profileEmp.child2ShortNameTemp = data.orgChild2.orgChild2ShortName;
          profileEmp.child3IdTemp = data.id;
          profileEmp.child3Temp = data.orgChild3Name;
          profileEmp.child3ShortNameTemp = data.orgChild3ShortName;
        }
      }
      case 4: {
        const data = await this.child4Repository.findOne({
          where: { id: body.nodeId },
          relations: ["orgRoot", "orgChild1", "orgChild2", "orgChild3"],
        });
        if (data != null) {
          profileEmp.rootIdTemp = data.orgRoot.id;
          profileEmp.rootTemp = data.orgRoot.orgRootName;
          profileEmp.rootShortNameTemp = data.orgRoot.orgRootShortName;
          profileEmp.child1IdTemp = data.orgChild1.id;
          profileEmp.child1Temp = data.orgChild1.orgChild1Name;
          profileEmp.child1ShortNameTemp = data.orgChild1.orgChild1ShortName;
          profileEmp.child2IdTemp = data.orgChild2.id;
          profileEmp.child2Temp = data.orgChild2.orgChild2Name;
          profileEmp.child2ShortNameTemp = data.orgChild2.orgChild2ShortName;
          profileEmp.child3IdTemp = data.orgChild3.id;
          profileEmp.child3Temp = data.orgChild3.orgChild3Name;
          profileEmp.child3ShortNameTemp = data.orgChild3.orgChild3ShortName;
          profileEmp.child4IdTemp = data.id;
          profileEmp.child4Temp = data.orgChild4Name;
          profileEmp.child4ShortNameTemp = data.orgChild4ShortName;
        }
      }
    }

    profileEmp.lastUpdateUserId = request.user.sub;
    profileEmp.lastUpdateFullName = request.user.name;
    profileEmp.lastUpdatedAt = new Date();
    profileEmp.nodeTemp = String(body.node);
    profileEmp.nodeIdTemp = body.nodeId;
    profileEmp.orgRevisionIdTemp = body.orgRevisionId;
    profileEmp.posmasterIdTemp = body.posmasterId;
    profileEmp.posMasterNoTemp = body.posMasterNo;
    profileEmp.positionIdTemp = body.positionId;
    profileEmp.positionTemp = body.position;
    profileEmp.positionFieldTemp = body.positionField;
    profileEmp.posTypeIdTemp = String(body.posTypeId);
    profileEmp.posTypeNameTemp = body.posTypeName;
    if (body.posTypeId != null) {
      const posTypeTemp = await this.posTypeRepo.findOne({
        where: { id: body.posTypeId },
      });
      if (posTypeTemp != null) {
        profileEmp.posTypeShortNameTemp = posTypeTemp.posTypeShortName;
      }
    }
    profileEmp.posLevelIdTemp = String(body.posLevelId);
    profileEmp.posLevelNameTemp = body.posLevelName;
    profileEmp.statusTemp = "PENDING";
    // this.profileRepo.merge(profileEmp, body);
    await this.profileRepo.save(profileEmp);
    return new HttpSuccess();
  }

  /**
   * API เช็คเลขบัตร
   *
   * @summary เช็คเลขบัตร  (ADMIN)
   *
   * @param {string} id  Id ทะเบียนประวัติ
   */
  @Put("citizenId/{id}")
  async checkCitizenIdProfile(
    @Path() id: string,
    @Request() req: RequestWithUser,
    @Body()
    requestBody: { citizenId: string },
  ) {
    const profile = await this.profileRepo.findOne({
      where: { id: Not(id), citizenId: requestBody.citizenId },
    });
    if (profile) {
      throw new HttpError(
        HttpStatus.INTERNAL_SERVER_ERROR,
        "เลขประจำตัวประชาชนนี้มีอยู่ในระบบแล้ว",
      );
    }
    return new HttpSuccess();
  }

  /**
   * API ค้นหาข้อมูลทะเบียนประวัติ ทดลองปฏิบัติหน้าที่ราชการ
   *
   * @summary ค้นหาข้อมูลทะเบียนประวัติ ทดลองปฏิบัติหน้าที่ราชการ (ADMIN)
   *
   */
  @Post("probation")
  async getProfileBySearchKeywordProbation(
    @Request() request: RequestWithUser,
    @Body()
    body: {
      page: number;
      pageSize: number;
      keyword?: string;
    },
  ) {
    let _data: any = {
      root: null,
      child1: null,
      child2: null,
      child3: null,
      child4: null,
    };
    if (!request.user.role.includes("SUPER_ADMIN")) {
      _data = await new permission().PermissionOrgCreate(request, "SYS_PROBATION");
    }
    const [findProfile, total] = await AppDataSource.getRepository(ProfileEmployee)
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.posLevel", "posLevel")
      .leftJoinAndSelect("profile.current_holders", "current_holders")
      .leftJoinAndSelect("current_holders.orgRevision", "orgRevision")
      .leftJoinAndSelect("current_holders.orgRoot", "orgRoot")
      .leftJoinAndSelect("current_holders.orgChild1", "orgChild1")
      .leftJoinAndSelect("current_holders.orgChild2", "orgChild2")
      .leftJoinAndSelect("current_holders.orgChild3", "orgChild3")
      .leftJoinAndSelect("current_holders.orgChild4", "orgChild4")
      .andWhere("profile.isLeave = false")
      .andWhere(
        _data.root != undefined && _data.root != null
          ? _data.root[0] != null
            ? `current_holders.orgRootId IN (:...root)`
            : `current_holders.orgRootId is null`
          : "1=1",
        {
          root: _data.root,
        },
      )
      .andWhere(
        _data.child1 != undefined && _data.child1 != null
          ? _data.child1[0] != null
            ? `current_holders.orgChild1Id IN (:...child1)`
            : // : `current_holders.orgChild1Id is ${_data.privilege == "PARENT" ? "not null" : "null"}`
            `current_holders.orgChild1Id is null`
          : "1=1",
        {
          child1: _data.child1,
        },
      )
      .andWhere(
        _data.child2 != undefined && _data.child2 != null
          ? _data.child2[0] != null
            ? `current_holders.orgChild2Id IN (:...child2)`
            : `current_holders.orgChild2Id is null`
          : "1=1",
        {
          child2: _data.child2,
        },
      )
      .andWhere(
        _data.child3 != undefined && _data.child3 != null
          ? _data.child3[0] != null
            ? `current_holders.orgChild3Id IN (:...child3)`
            : `current_holders.orgChild3Id is null`
          : "1=1",
        {
          child3: _data.child3,
        },
      )
      .andWhere(
        _data.child4 != undefined && _data.child4 != null
          ? _data.child4[0] != null
            ? `current_holders.orgChild4Id IN (:...child4)`
            : `current_holders.orgChild4Id is null`
          : "1=1",
        {
          child4: _data.child4,
        },
      )
      .andWhere(
        new Brackets((qb) => {
          qb.orWhere(
            "CONCAT(profile.prefix, profile.firstName, ' ', profile.lastName) LIKE :keyword",
            { keyword: `%${body.keyword}%` },
          )
            // .orWhere("profile.firstName LIKE :keyword", { keyword: `%${body.keyword}%` })
            // .orWhere("profile.lastName LIKE :keyword", { keyword: `%${body.keyword}%` })
            .orWhere("profile.position LIKE :keyword", { keyword: `%${body.keyword}%` })
            .orWhere("posLevel.posLevelName LIKE :keyword", { keyword: `%${body.keyword}%` });
        }),
      )
      .orderBy("profile.citizenId", "ASC")
      .skip((body.page - 1) * body.pageSize)
      .take(body.pageSize)
      .getManyAndCount();

    const orgRevisionActive = await this.orgRevisionRepo.findOne({
      where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false },
    });

    const mapDataProfile = await Promise.all(
      findProfile.map(async (item: ProfileEmployee) => {
        return {
          id: item.id,
          rank: item.rank,
          prefix: item.prefix,
          firstName: item.firstName,
          lastName: item.lastName,
          position: item.position,
          idcard: item.citizenId,
          posLevelName: item.posLevel == null ? null : item.posLevel.posLevelName,
          isProbation: item.isProbation,
          orgRootName:
            item.current_holders == null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgRoot ==
              null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgRoot
                ?.orgRootName == null
              ? null
              : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgRoot
                ?.orgRootName,
          orgChild1Name:
            item.current_holders == null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild1 ==
              null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild1
                ?.orgChild1Name == null
              ? null
              : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)
                ?.orgChild1?.orgChild1Name,
          orgChild2Name:
            item.current_holders == null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild2 ==
              null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild2
                ?.orgChild2Name == null
              ? null
              : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)
                ?.orgChild2?.orgChild2Name,
          orgChild3Name:
            item.current_holders == null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild3 ==
              null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild3
                ?.orgChild3Name == null
              ? null
              : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)
                ?.orgChild3?.orgChild3Name,
          orgChild4Name:
            item.current_holders == null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild4 ==
              null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild4
                ?.orgChild4Name == null
              ? null
              : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)
                ?.orgChild4?.orgChild4Name,
        };
      }),
    );

    return new HttpSuccess({ data: mapDataProfile, total });
  }

  /**
   * API ค้นหาข้อมูลทะเบียนประวัติ เกษียณข้าราชการ
   *
   * @summary ค้นหาข้อมูลทะเบียนประวัติ เกษียณข้าราชการ (ADMIN)
   *
   */
  @Post("retire")
  async getProfileBySearchKeywordRetire(
    @Body()
    body: {
      page: number;
      pageSize: number;
      keyword?: string;
      type?: string;
    },
  ) {
    const orgRevisionActive = await this.orgRevisionRepo.findOne({
      where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false },
    });
    if (!orgRevisionActive) {
      throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
    }
    let query = AppDataSource.getRepository(ProfileEmployee)
      .createQueryBuilder("profileEmployee")
      .leftJoinAndSelect("profileEmployee.posLevel", "posLevel")
      .leftJoinAndSelect("profileEmployee.posType", "posType")
      .leftJoinAndSelect("profileEmployee.current_holders", "current_holders")
      .leftJoinAndSelect("current_holders.orgRevision", "orgRevision")
      .leftJoinAndSelect("current_holders.orgRoot", "orgRoot")
      .leftJoinAndSelect("current_holders.orgChild1", "orgChild1")
      .leftJoinAndSelect("current_holders.orgChild2", "orgChild2")
      .leftJoinAndSelect("current_holders.orgChild3", "orgChild3")
      .leftJoinAndSelect("current_holders.orgChild4", "orgChild4")
      .leftJoinAndSelect("current_holders.positions", "positions")
      .andWhere(
        new Brackets((qb) => {
          qb.where("profileEmployee.position LIKE :keyword", { keyword: `%${body.keyword}%` })
            .orWhere("posLevel.posLevelName LIKE :keyword", { keyword: `%${body.keyword}%` })
            .orWhere("posType.posTypeName LIKE :keyword", { keyword: `%${body.keyword}%` })
            .orWhere(
              "CONCAT(profileEmployee.prefix, profileEmployee.firstName, ' ', profileEmployee.lastName) LIKE :keyword",
              { keyword: `%${body.keyword}%` },
            );
        }),
      )
      .andWhere("profileEmployee.isLeave = false")
      .andWhere("current_holders.orgRevisionId = :orgRevisionId", {
        orgRevisionId: orgRevisionActive.id,
      });

    if (body.type) {
      const typeUpper = body.type.trim().toUpperCase();
      if (typeUpper === "EMPLOYEE") {
        query = query.andWhere("profileEmployee.employeeClass = 'PERM'");
      } else if (typeUpper === "TEMP") {
        query = query.andWhere("profileEmployee.employeeClass = 'TEMP'");
      }
    }

    const [findProfile, total] = await query
      .orderBy("profileEmployee.citizenId", "ASC")
      .skip((body.page - 1) * body.pageSize)
      .take(body.pageSize)
      .getManyAndCount();

    const mapDataProfile = await Promise.all(
      findProfile.map(async (item: ProfileEmployee) => {
        const posMaster =
          item.current_holders == null ||
            item.current_holders.length == 0 ||
            item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive.id) == null
            ? null
            : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive.id);
        const position =
          posMaster == null ||
            item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive.id)?.positions ==
            null ||
            item.current_holders?.find((x) => x.orgRevisionId == orgRevisionActive.id)?.positions
              .length == 0 ||
            item.current_holders
              .find((x) => x.orgRevisionId == orgRevisionActive.id)
              ?.positions?.find((position) => position.positionIsSelected == true) == null
            ? null
            : item.current_holders
              .find((x) => x.orgRevisionId == orgRevisionActive.id)
              ?.positions?.find((position) => position.positionIsSelected == true);

        const shortName =
          item.current_holders.length == 0
            ? null
            : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive.id) != null &&
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive.id)
                ?.orgChild4 != null
              ? `${item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive.id)?.orgChild4.orgChild4ShortName} ${item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive.id)?.posMasterNo}`
              : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive.id) != null &&
                item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive.id)
                  ?.orgChild3 != null
                ? `${item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive.id)?.orgChild3.orgChild3ShortName} ${item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive.id)?.posMasterNo}`
                : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive.id) !=
                  null &&
                  item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive.id)
                    ?.orgChild2 != null
                  ? `${item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive.id)?.orgChild2.orgChild2ShortName} ${item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive.id)?.posMasterNo}`
                  : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive.id) !=
                    null &&
                    item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive.id)
                      ?.orgChild1 != null
                    ? `${item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive.id)?.orgChild1.orgChild1ShortName} ${item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive.id)?.posMasterNo}`
                    : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive.id) !=
                      null &&
                      item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive.id)
                        ?.orgRoot != null
                      ? `${item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive.id)?.orgRoot.orgRootShortName} ${item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive.id)?.posMasterNo}`
                      : null;

        return {
          id: item.id,
          prefix: item.prefix,
          rank: item.rank,
          firstName: item.firstName,
          lastName: item.lastName,
          position: item.position,
          idcard: item.citizenId,
          posLevelName: item.posLevel == null ? null : item.posLevel.posLevelName,
          posTypeName: item.posType == null ? null : item.posType.posTypeName,
          posNo: `${shortName} ${posMaster == null ? null : posMaster.posMasterNo}`,
          isProbation: item.isProbation,
          orgRootName:
            item.current_holders == null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgRoot ==
              null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgRoot
                ?.orgRootName == null
              ? null
              : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgRoot
                ?.orgRootName,
          orgChild1Name:
            item.current_holders == null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild1 ==
              null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild1
                ?.orgChild1Name == null
              ? null
              : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)
                ?.orgChild1?.orgChild1Name,
          orgChild2Name:
            item.current_holders == null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild2 ==
              null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild2
                ?.orgChild2Name == null
              ? null
              : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)
                ?.orgChild2?.orgChild2Name,
          orgChild3Name:
            item.current_holders == null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild3 ==
              null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild3
                ?.orgChild3Name == null
              ? null
              : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)
                ?.orgChild3?.orgChild3Name,
          orgChild4Name:
            item.current_holders == null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild4 ==
              null ||
              item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild4
                ?.orgChild4Name == null
              ? null
              : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)
                ?.orgChild4?.orgChild4Name,
        };
      }),
    );

    return new HttpSuccess({ data: mapDataProfile, total });
  }

  /**
   * API รายชื่อราชการที่เลื่อนเงินเดือน
   *
   * @summary ORG_072 - รายชื่อราชการที่เลื่อนเงินเดือน #76
   *
   */
  @Post("salary/gen")
  async salaryGen(
    @Body()
    body: {
      page: number;
      pageSize: number;
      keyword?: string;
      rootId?: string;
      year: number;
      period: string;
      sortBy?: string;
      descending?: boolean;
    },
  ) {
    const findRevision = await this.orgRevisionRepo.findOne({
      where: { orgRevisionIsCurrent: true },
    });
    if (!findRevision) {
      throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
    }

    let query = await AppDataSource.getRepository(EmployeePosMaster)
      .createQueryBuilder("employeePosMaster")
      .leftJoinAndSelect("employeePosMaster.current_holder", "current_holder")
      .leftJoinAndSelect("employeePosMaster.orgRoot", "orgRoot")
      .leftJoinAndSelect("employeePosMaster.orgChild1", "orgChild1")
      .leftJoinAndSelect("employeePosMaster.orgChild2", "orgChild2")
      .leftJoinAndSelect("employeePosMaster.orgChild3", "orgChild3")
      .leftJoinAndSelect("employeePosMaster.orgChild4", "orgChild4")
      .leftJoinAndSelect("employeePosMaster.positions", "positions")
      .leftJoinAndSelect("current_holder.profileSalary", "profileSalary")
      .leftJoinAndSelect("current_holder.profileDisciplines", "profileDisciplines")
      .leftJoinAndSelect("current_holder.posLevel", "posLevel")
      .leftJoinAndSelect("current_holder.posType", "posType")
      .where((qb) => {
        if (body.rootId) {
          qb.andWhere("employeePosMaster.orgRootId = :rootId", { rootId: body.rootId });
        } else {
          qb.andWhere("employeePosMaster.orgRevisionId = :orgRevisionId", {
            orgRevisionId: findRevision?.id,
          });
        }
        qb.andWhere("employeePosMaster.current_holderId IS NOT NULL");
      })
      .andWhere(
        new Brackets((qb) => {
          qb.where(
            body.keyword != null && body.keyword != ""
              ? "current_holder.prefix LIKE :keyword"
              : "1=1",
            {
              keyword: `%${body.keyword}%`,
            },
          )
            .orWhere(
              body.keyword != null && body.keyword != ""
                ? "current_holder.firstName LIKE :keyword"
                : "1=1",
              {
                keyword: `%${body.keyword}%`,
              },
            )
            .orWhere(
              body.keyword != null && body.keyword != ""
                ? "current_holder.lastName LIKE :keyword"
                : "1=1",
              {
                keyword: `%${body.keyword}%`,
              },
            )
            .orWhere(
              body.keyword != null && body.keyword != ""
                ? "CONCAT(current_holder.prefix,current_holder.firstName,' ',current_holder.lastName) LIKE :keyword"
                : "1=1",
              {
                keyword: `%${body.keyword}%`,
              },
            )
            .orWhere(
              body.keyword != null && body.keyword != ""
                ? "CONCAT(orgRoot.orgRootShortName,' ',employeePosMaster.posMasterNo) LIKE :keyword"
                : "1=1",
              {
                keyword: `%${body.keyword}%`,
              },
            )
            .orWhere(
              body.keyword != null && body.keyword != ""
                ? "CONCAT(orgChild1.orgChild1ShortName,' ',employeePosMaster.posMasterNo) LIKE :keyword"
                : "1=1",
              {
                keyword: `%${body.keyword}%`,
              },
            )
            .orWhere(
              body.keyword != null && body.keyword != ""
                ? "CONCAT(orgChild2.orgChild2ShortName,' ',employeePosMaster.posMasterNo) LIKE :keyword"
                : "1=1",
              {
                keyword: `%${body.keyword}%`,
              },
            )
            .orWhere(
              body.keyword != null && body.keyword != ""
                ? "CONCAT(orgChild3.orgChild3ShortName,' ',employeePosMaster.posMasterNo) LIKE :keyword"
                : "1=1",
              {
                keyword: `%${body.keyword}%`,
              },
            )
            .orWhere(
              body.keyword != null && body.keyword != ""
                ? "CONCAT(orgChild4.orgChild4ShortName,' ',employeePosMaster.posMasterNo) LIKE :keyword"
                : "1=1",
              {
                keyword: `%${body.keyword}%`,
              },
            )
            .orWhere(
              body.keyword != null && body.keyword != ""
                ? "current_holder.position LIKE :keyword"
                : "1=1",
              {
                keyword: `%${body.keyword}%`,
              },
            )

            .orWhere(
              body.keyword != null && body.keyword != ""
                ? "current_holder.citizenId LIKE :keyword"
                : "1=1",
              {
                keyword: `%${body.keyword}%`,
              },
            )
            .orWhere(
              body.keyword != null && body.keyword != ""
                ? "posType.posTypeName LIKE :keyword"
                : "1=1",
              {
                keyword: `%${body.keyword}%`,
              },
            )
            .orWhere(
              body.keyword != null && body.keyword != ""
                ? "CONCAT(posType.posTypeShortName,' ',posLevel.posLevelName) LIKE :keyword"
                : "1=1",
              {
                keyword: `%${body.keyword}%`,
              },
            );
        }),
      );

    if (body.sortBy) {
      if (body.sortBy === "posType") {
        query = query.orderBy(`posType.posTypeName`, body.descending ? "DESC" : "ASC");
      } else if (body.sortBy === "posLevel") {
        query = query
          .orderBy(`posType.posTypeShortName`, body.descending ? "DESC" : "ASC")
          .addOrderBy(`posLevel.posLevelName`, body.descending ? "DESC" : "ASC");
      } else if (body.sortBy === "orgShortName" || body.sortBy === "posMasterNo") {
        query = query
          .orderBy(`orgRoot.orgRootShortName`, body.descending ? "DESC" : "ASC")
          .addOrderBy(`orgChild1.orgChild1ShortName`, body.descending ? "DESC" : "ASC")
          .addOrderBy(`orgChild2.orgChild2ShortName`, body.descending ? "DESC" : "ASC")
          .addOrderBy(`orgChild3.orgChild3ShortName`, body.descending ? "DESC" : "ASC")
          .addOrderBy(`orgChild4.orgChild4ShortName`, body.descending ? "DESC" : "ASC")
          .addOrderBy(`employeePosMaster.posMasterNo`, body.descending ? "DESC" : "ASC");
      } else {
        query = query.orderBy(`current_holder.${body.sortBy}`, body.descending ? "DESC" : "ASC");
      }
    } else {
      query = query.orderBy("current_holder.citizenId", "ASC");
    }

    const [findPosMaster, total] = await query
      .skip((body.page - 1) * body.pageSize)
      .take(body.pageSize)
      .getManyAndCount();

    if (!findPosMaster) {
      throw new HttpError(HttpStatus.NOT_FOUND, "not found. PosMaster");
    }

    const formattedData = findPosMaster.map((item) => {
      let orgShortName = "";

      if (item.orgChild1Id === null) {
        orgShortName = item.orgRoot?.orgRootShortName;
      } else if (item.orgChild2Id === null) {
        orgShortName = item.orgChild1?.orgChild1ShortName;
      } else if (item.orgChild3Id === null) {
        orgShortName = item.orgChild2?.orgChild2ShortName;
      } else if (item.orgChild4Id === null) {
        orgShortName = item.orgChild3?.orgChild3ShortName;
      } else {
        orgShortName = item.orgChild4?.orgChild4ShortName;
      }

      // const amount =
      //   item.current_holder == null || item.current_holder.profileSalary.length == 0
      //     ? null
      //     : item.current_holder.profileSalary.sort((a: any, b: any) => b.date - a.date)[0].amount;
      const amount = item.current_holder ? item.current_holder.amount : null;
      let datePeriodStart = new Date(
        `${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, "0")}-${String(new Date().getDate() + 1).padStart(2, "0")}T00:00:00.000Z`,
      );
      let datePeriodEnd = new Date(
        `${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, "0")}-${String(new Date().getDate() + 1).padStart(2, "0")}T00:00:00.000Z`,
      );
      if (body.period.toLocaleUpperCase() == "APR") {
        datePeriodStart = new Date(`${body.year}-03-31T00:00:00.000Z`);
        datePeriodEnd = new Date(`${body.year}-03-31T00:00:00.000Z`);
      }
      if (body.period.toLocaleUpperCase() == "OCT") {
        datePeriodStart = new Date(`${body.year}-09-30T00:00:00.000Z`);
        datePeriodEnd = new Date(`${body.year}-09-30T00:00:00.000Z`);
      }
      datePeriodStart = new Date(
        new Date(datePeriodStart.setDate(datePeriodStart.getDate() + 1)).setMonth(
          datePeriodStart.getMonth() - 6,
        ),
      );
      //   const specialPosition = item.positions.find(
      //     (position) => position.positionIsSelected === true,
      //   );
      //   const isSpecial = specialPosition ? specialPosition.isSpecial : null;

      return {
        profileId: item.current_holder.id,
        salaryLevel: item.current_holder.salaryLevel,
        group: item.current_holder.group,
        rank: item.current_holder.rank,
        prefix: item.current_holder.prefix,
        firstName: item.current_holder.firstName,
        lastName: item.current_holder.lastName,
        citizenId: item.current_holder.citizenId,
        posMasterNoPrefix: item.posMasterNoPrefix,
        posMasterNo: item.posMasterNo,
        posMasterNoSuffix: item.posMasterNoSuffix,
        orgShortName: orgShortName,
        position: item.current_holder.position,
        posType:
          item.current_holder.posType == null ? null : item.current_holder.posType.posTypeName,
        posTypeShort:
          item.current_holder.posType == null ? null : item.current_holder.posType.posTypeShortName,
        posLevel:
          item.current_holder.posLevel == null ? null : item.current_holder.posLevel.posLevelName,
        amount: amount ? amount : null,
        rootId: item.orgRootId,
        root: item.orgRoot?.orgRootName ? item.orgRoot.orgRootName : null,
        child1Id: item.orgChild1Id,
        child1: item.orgChild1?.orgChild1Name ? item.orgChild1.orgChild1Name : null,
        child2Id: item.orgChild2Id,
        child2: item.orgChild2?.orgChild2Name ? item.orgChild2.orgChild2Name : null,
        child3Id: item.orgChild3Id,
        child3: item.orgChild3?.orgChild3Name ? item.orgChild3.orgChild3Name : null,
        child4Id: item.orgChild4Id,
        child4: item.orgChild4?.orgChild4Name ? item.orgChild4.orgChild4Name : null,
        result: null,
        duration: null,
        isPunish:
          item.current_holder.profileDisciplines.filter(
            (x: any) =>
              new Date(
                `${new Date(x.date).getFullYear()}-${String(new Date(x.date).getMonth() + 1).padStart(2, "0")}-${String(new Date(x.date).getDate() + 1).padStart(2, "0")}T00:00:00.000Z`,
              ) >= datePeriodStart &&
              new Date(
                `${new Date(x.date).getFullYear()}-${String(new Date(x.date).getMonth() + 1).padStart(2, "0")}-${String(new Date(x.date).getDate() + 1).padStart(2, "0")}T00:00:00.000Z`,
              ) <= datePeriodEnd,
          ).length > 0
            ? true
            : false,
        isSuspension: item.current_holder.dateRetire == null ? false : true,
        isAbsent: false,
        isLeave: false,
        isRetired:
          item.current_holder.birthDate == null ||
            calculateRetireDate(item.current_holder.birthDate).getFullYear() != body.year
            ? false
            : true,
        isSpecial: false,
      };
    });

    return new HttpSuccess({ data: formattedData, total: total });
  }

  /**
   * API ข้อมูลทะเบียนประวัติตาม keycloak by revisionId
   *
   * @summary ข้อมูลทะเบียนประวัติตาม keycloak by revisionId (ADMIN)
   *
   */
  @Get("keycloak/position/{revisionId}")
  async getProfileByKeycloakByRevision(
    @Path() revisionId: string,
    @Request() request: { user: Record<string, any> },
  ) {
    const profile = await this.profileRepo.findOne({
      where: { keycloak: request.user.sub },
      relations: [
        "posLevel",
        "posType",
        "current_holders",
        "current_holders.orgRoot",
        "current_holders.orgChild1",
        "current_holders.orgChild2",
        "current_holders.orgChild3",
        "current_holders.orgChild4",
      ],
    });
    if (!profile) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลบุคคลนี้ในระบบ");
    }
    const _profile = {
      profileId: profile.id,
      rank: profile.rank,
      prefix: profile.prefix,
      firstName: profile.firstName,
      lastName: profile.lastName,
      citizenId: profile.citizenId,
      position: profile.position,
      posLevelName: profile.posLevel == null ? null : profile.posLevel.posLevelName,
      posLevelRank: profile.posLevel == null ? null : profile.posLevel.posLevelRank,
      posLevelId: profile.posLevel == null ? null : profile.posLevel.id,
      posTypeName: profile.posType == null ? null : profile.posType.posTypeName,
      posTypeShortName: profile.posType == null ? null : profile.posType.posTypeShortName,
      posTypeRank: profile.posType == null ? null : profile.posType.posTypeRank,
      posTypeId: profile.posType == null ? null : profile.posType.id,
      rootId:
        profile.current_holders == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRoot == null
          ? null
          : profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRootId,
      rootDnaId:
        profile.current_holders == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRoot == null
          ? null
          : profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.ancestorDNA,
      root:
        profile.current_holders == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRoot == null
          ? null
          : profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRoot.orgRootName,
      child1Id:
        profile.current_holders == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild1 == null
          ? null
          : profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild1Id,
      child1DnaId:
        profile.current_holders == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild1 == null
          ? null
          : profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.ancestorDNA,
      child1:
        profile.current_holders == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild1 == null
          ? null
          : profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild1
            .orgChild1Name,
      child2Id:
        profile.current_holders == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild2 == null
          ? null
          : profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild2Id,
      child2DnaId:
        profile.current_holders == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild2 == null
          ? null
          : profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.ancestorDNA,
      child2:
        profile.current_holders == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild2 == null
          ? null
          : profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild2
            .orgChild2Name,
      child3Id:
        profile.current_holders == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild3 == null
          ? null
          : profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild3Id,
      child3DnaId:
        profile.current_holders == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild3 == null
          ? null
          : profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.ancestorDNA,
      child3:
        profile.current_holders == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild3 == null
          ? null
          : profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild3
            .orgChild3Name,
      child4Id:
        profile.current_holders == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild4 == null
          ? null
          : profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild4Id,
      child4DnaId:
        profile.current_holders == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild4 == null
          ? null
          : profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.ancestorDNA,
      child4:
        profile.current_holders == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
          profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild4 == null
          ? null
          : profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild4
            .orgChild4Name,
    };
    return new HttpSuccess(_profile);
  }

  /**
   * API ข้อมูลบุลคลที่มีอายุเกษียณราชการตามปี
   *
   * @summary ข้อมูลบุลคลที่มีอายุเกษียณราชการตามปี
   *
   */
  @Get("profileid/retire/{year}")
  async getProfileByRetireYear(@Path() year: number, @Request() req: RequestWithUser) {
    // await new permission().PermissionOrgUserList(req, "SYS_REGISTRY_EMP", id);//ไม่แน่ใจEMPปิดไว้ก่อน
    const profiles = await this.profileRepo
      .createQueryBuilder("profileEmployee")
      .leftJoinAndSelect("profileEmployee.posLevel", "posLevel")
      .leftJoinAndSelect("profileEmployee.posType", "posType")
      .leftJoinAndSelect("profileEmployee.current_holders", "current_holders")
      .leftJoinAndSelect("current_holders.orgRoot", "orgRoot")
      .leftJoinAndSelect("current_holders.orgChild1", "orgChild1")
      .leftJoinAndSelect("current_holders.orgChild2", "orgChild2")
      .leftJoinAndSelect("current_holders.orgChild3", "orgChild3")
      .leftJoinAndSelect("current_holders.orgChild4", "orgChild4")
      .leftJoinAndSelect("current_holders.positions", "positions")
      // calculate range: start = 2 Oct of (year-1), end = 1 Oct of year (inclusive)
      .where("profileEmployee.dateRetire BETWEEN :start AND :end", {
        start: `${year - 1}-10-01`,
        end: `${year}-09-30`,
      })
      .andWhere(
        "profileEmployee.isLeave = :isLeave AND profileEmployee.isRetirement = :isRetirement",
        {
          isLeave: false,
          isRetirement: false,
        },
      )
      .getMany();

    if (!profiles || profiles.length === 0) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลบุคคลที่มีอายุเกษียณราชการในปีนี้");
    }

    const findRevision = await this.orgRevisionRepo.findOne({
      where: { orgRevisionIsCurrent: true },
    });
    if (!findRevision) {
      throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
    }
    const formattedData = profiles.map((item) => {
      const posMaster =
        item.current_holders == null ||
          item.current_holders.length == 0 ||
          item.current_holders.find((x) => x.orgRevisionId == findRevision.id) == null
          ? null
          : item.current_holders.find((x) => x.orgRevisionId == findRevision.id);

      const shortName =
        item.current_holders.length == 0
          ? null
          : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
            item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4 !=
            null
            ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4.orgChild4ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
            : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
              item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3 !=
              null
              ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3.orgChild3ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
              : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
                item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2 !=
                null
                ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2.orgChild2ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
                : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
                  item.current_holders.find((x) => x.orgRevisionId == findRevision.id)
                    ?.orgChild1 != null
                  ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1.orgChild1ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
                  : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
                    item.current_holders.find((x) => x.orgRevisionId == findRevision.id)
                      ?.orgRoot != null
                    ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot.orgRootShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
                    : null;
      const root =
        item.current_holders == null ||
          item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot == null
          ? null
          : item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot;
      const child1 =
        item.current_holders == null ||
          item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1 == null
          ? null
          : item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1;
      const child2 =
        item.current_holders == null ||
          item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2 == null
          ? null
          : item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2;
      const child3 =
        item.current_holders == null ||
          item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3 == null
          ? null
          : item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3;
      const child4 =
        item.current_holders == null ||
          item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4 == null
          ? null
          : item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4;

      let node = null;
      let nodeId = null;
      let nodeShortName = null;

      if (root) {
        node = 0;
        nodeId = root.id;
        nodeShortName = root.orgRootShortName;
      }
      if (child1) {
        node = 1;
        nodeId = child1.id;
        nodeShortName = child1.orgChild1ShortName;
      }
      if (child2) {
        node = 2;
        nodeId = child2.id;
        nodeShortName = child2.orgChild2ShortName;
      }
      if (child3) {
        node = 3;
        nodeId = child3.id;
        nodeShortName = child3.orgChild3ShortName;
      }
      if (child4) {
        node = 4;
        nodeId = child4.id;
        nodeShortName = child4.orgChild4ShortName;
      }

      return {
        profileId: item.id,
        prefix: item.prefix,
        rank: item.rank,
        firstName: item.firstName,
        lastName: item.lastName,
        citizenId: item.citizenId,
        root: root == null ? null : root.orgRootName,
        rootId: root == null ? null : root.id,
        rootShortName: root == null ? null : root.orgRootShortName,
        child1: child1 == null ? null : child1.orgChild1Name,
        child1Id: child1 == null ? null : child1.id,
        child1ShortName: child1 == null ? null : child1.orgChild1ShortName,
        child2: child2 == null ? null : child2.orgChild2Name,
        child2Id: child2 == null ? null : child2.id,
        child2ShortName: child2 == null ? null : child2.orgChild2ShortName,
        child3: child3 == null ? null : child3.orgChild3Name,
        child3Id: child3 == null ? null : child3.id,
        child3ShortName: child3 == null ? null : child3.orgChild3ShortName,
        child4: child4 == null ? null : child4.orgChild4Name,
        child4Id: child4 == null ? null : child4.id,
        child4ShortName: child4 == null ? null : child4.orgChild4ShortName,
        dateRetire: item.dateRetire,
        posLevelId: item.posLevel == null ? null : item.posLevel.id,
        posLevelName: item.posLevel == null ? null : item.posLevel.posLevelName,
        posLevelRank: item.posLevel == null ? null : item.posLevel.posLevelRank,
        posTypeId: item.posType == null ? null : item.posType.id,
        posTypeName: item.posType == null ? null : item.posType.posTypeName,
        posTypeRank: item.posType == null ? null : item.posType.posTypeRank,
        posNo: shortName,
        posMasterNo: posMaster == null ? null : posMaster.posMasterNo,
        position: item.position,
        node: node,
        nodeId: nodeId,
        nodeShortName: nodeShortName,
        positionExecutiveField: null,
        positionArea: null,
      };
    });
    return new HttpSuccess(formattedData);
  }

  /**
   * API อัพเดทถึงแก่กรรม
   *
   * @summary อัพเดทถึงแก่กรรม (ADMIN)
   *
   * @param {string} id  Id ทะเบียนประวัติ
   */
  @Post("leave/{id}")
  async updateLeaveUser(
    @Path() id: string,
    @Body()
    requestBody: { isLeave: boolean; leaveReason: string; dateLeave: Date },
    @Request() request: RequestWithUser,
  ) {
    const profile = await this.profileRepo.findOne({
      where: { id: id },
      relations: [
        "posType",
        "posLevel",
        "current_holders",
        "current_holders.orgRoot",
        "current_holders.orgChild1",
        "current_holders.orgChild2",
        "current_holders.orgChild3",
        "current_holders.orgChild4",
        "current_holders.positions",
      ],
    });
    if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");

    const orgRevision = await this.orgRevisionRepo.findOne({
      where: {
        orgRevisionIsCurrent: true,
        orgRevisionIsDraft: false,
      },
    });
    const orgRevisionRef =
      profile?.current_holders?.find((x) => x.orgRevisionId == orgRevision?.id) ?? null;
    const orgRootRef = orgRevisionRef?.orgRoot ?? null;
    const orgChild1Ref = orgRevisionRef?.orgChild1 ?? null;
    const orgChild2Ref = orgRevisionRef?.orgChild2 ?? null;
    const orgChild3Ref = orgRevisionRef?.orgChild3 ?? null;
    const orgChild4Ref = orgRevisionRef?.orgChild4 ?? null;
    const shortName =
      !profile.current_holders || profile.current_holders.length == 0
        ? null
        : profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) != null &&
          profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild4 !=
          null
          ? `${profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild4.orgChild4ShortName}`
          : profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) != null &&
            profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild3 !=
            null
            ? `${profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild3.orgChild3ShortName}`
            : profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) != null &&
              profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)
                ?.orgChild2 != null
              ? `${profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild2.orgChild2ShortName}`
              : profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) != null &&
                profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)
                  ?.orgChild1 != null
                ? `${profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild1.orgChild1ShortName}`
                : profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) != null &&
                  profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)
                    ?.orgRoot != null
                  ? `${profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgRoot.orgRootShortName}`
                  : null;
    const dest_item = await this.salaryRepo.findOne({
      where: { profileEmployeeId: id },
      order: { order: "DESC" },
    });
    const data: any = {
      order: dest_item == null ? 1 : dest_item.order + 1,
      amount: profile.amount,
      positionSalaryAmount: profile.positionSalaryAmount,
      mouthSalaryAmount: profile.mouthSalaryAmount,
      profileEmployeeId: profile.id,
      posNo: orgRevisionRef?.posMasterNo,
      positionExecutive: "",
      positionType: profile.posType?.posTypeName,
      positionLevel:
        profile.posType && profile.posLevel
          ? `${profile.posType?.posTypeShortName} ${profile.posLevel?.posLevelName}`
          : "",
      amountSpecial: profile.amountSpecial,
      orgRoot: orgRootRef?.orgRootName,
      orgChild1: orgChild1Ref?.orgChild1Name,
      orgChild2: orgChild2Ref?.orgChild2Name,
      orgChild3: orgChild3Ref?.orgChild3Name,
      orgChild4: orgChild4Ref?.orgChild4Name,
      commandYear: new Date().getFullYear() + 543,
      // commandDateSign: new Date(),
      commandDateAffect: requestBody.dateLeave,
      commandCode: "16",
      commandName: "พ้นจากราชการ",
      posNoAbb: shortName,
      isEntry: false,
      positionName: profile.position,
      createdUserId: request.user.sub,
      createdFullName: request.user.name,
      lastUpdateUserId: request.user.sub,
      lastUpdateFullName: request.user.name,
      createdAt: new Date(),
      lastUpdatedAt: new Date(),
      remark: "ถึงแก่กรรม",
      isGovernment: false,
    };
    delete data.id;

    const history = new ProfileSalaryHistory();
    Object.assign(history, { ...data, id: undefined });
    data.dateGovernment = data.createdAt;
    await this.salaryRepo.save(data);
    history.profileSalaryId = data.id;
    await this.salaryHistoryRepo.save(history);

    let _null: any = null;
    profile.isLeave = requestBody.isLeave;
    profile.leaveReason = requestBody.leaveReason;
    profile.dateLeave = requestBody.dateLeave;
    profile.leaveDate = requestBody.dateLeave;
    profile.leaveType = "RETIRE_DECEASED";
    // profile.position = _null;
    // profile.posLevelId = _null;
    // profile.posTypeId = _null;
    if (profile.keycloak != null && profile.keycloak != "" && profile.isDelete === false) {
      const delUserKeycloak = await deleteUser(profile.keycloak);
      if (delUserKeycloak) {
        // Task #228
        // profile.keycloak = _null;
        profile.roleKeycloaks = [];
        profile.isActive = false;
        profile.isDelete = true;
      }
    }
    await this.profileRepo.save(profile);
    if (requestBody.isLeave == true) {
      if (orgRevisionRef) {
        await CreatePosMasterHistoryEmployee(orgRevisionRef.id, request, "DELETE");
      }
      await removeProfileInOrganize(profile.id, "EMPLOYEE");
    }
    let organizeName = "";
    if (orgRootRef) {
      const names = [
        orgChild4Ref?.orgChild4Name,
        orgChild3Ref?.orgChild3Name,
        orgChild2Ref?.orgChild2Name,
        orgChild1Ref?.orgChild1Name,
        orgRootRef?.orgRootName,
      ].filter(Boolean);
      organizeName = names.join(" ");
    }
    return new HttpSuccess();
  }

  /**
   * API แก้ไขข้อมูลลูกจ้างชั่วคราว
   *
   * @summary แก้ไขข้อมูลลูกจ้างชั่วคราว (ADMIN)
   *
   * @param {string} profileEmployeeId  profileEmployeeId ทะเบียนประวัติลูกจ้างชั่วคราว
   */
  @Put("information/{profileEmployeeId}")
  async ProfileEmployeeInformation(
    @Request() request: RequestWithUser,
    @Path() profileEmployeeId: string,
    @Body() body: UpdateInformationProfileEmployee,
  ) {
    await new permission().PermissionOrgUserUpdate(request, "SYS_REGISTRY_EMP", profileEmployeeId);
    const profileEmp = await this.profileRepo.findOneBy({ id: profileEmployeeId });
    if (!profileEmp) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์นี้");

    const history = new ProfileEmployeeInformationHistory();
    Object.assign(profileEmp, body);
    Object.assign(history, { ...profileEmp, id: undefined });
    history.profileEmployeeId = profileEmployeeId;
    history.lastUpdateFullName = request.user.name;
    history.lastUpdateUserId = request.user.sub;
    history.lastUpdatedAt = new Date();
    history.createdUserId = request.user.sub;
    history.createdFullName = request.user.name;
    history.createdAt = new Date();
    profileEmp.lastUpdateUserId = request.user.sub;
    profileEmp.lastUpdateFullName = request.user.name;
    profileEmp.lastUpdatedAt = new Date();

    await Promise.all([
      this.profileRepo.save(profileEmp),
      this.informationHistoryRepository.save(history),
    ]);
    return new HttpSuccess();
  }

  /**
   * API ข้อมูลลูกจ้างชั่วคราว
   *
   * @summary ข้อมูลลูกจ้างชั่วคราว (ADMIN)
   *
   * @param {string} profileEmployeeId profileEmployeeId ทะเบียนประวัติลูกจ้างชั่วคราว
   */
  @Get("information/{profileEmployeeId}")
  async getInformationById(@Path() profileEmployeeId: string, @Request() req: RequestWithUser) {
    // let _workflow = await new permission().Workflow(req, profileEmployeeId, "SYS_REGISTRY_EMP");
    // if (_workflow == false)
    //   await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_EMP", profileEmployeeId);
    const profileInformation = await this.profileRepo.findOne({
      where: { id: profileEmployeeId },
    });
    if (!profileInformation) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");

    const mapData = {
      id: profileInformation.id,
      positionEmployeeGroupId: profileInformation.positionEmployeeGroupId,
      positionEmployeeLineId: profileInformation.positionEmployeeLineId,
      positionEmployeePositionId: profileInformation.positionEmployeePositionId,
      employeeOc: profileInformation.employeeOc,
      employeeTypeIndividual: profileInformation.employeeTypeIndividual,
      employeeWage: profileInformation.employeeWage,
      employeeMoneyIncrease: profileInformation.employeeMoneyIncrease,
      employeeMoneyAllowance: profileInformation.employeeMoneyAllowance,
      employeeMoneyEmployee: profileInformation.employeeMoneyEmployee,
      employeeMoneyEmployer: profileInformation.employeeMoneyEmployer,
    };
    return new HttpSuccess(mapData);
  }

  /**
   * API ประวัติการแก้ไขข้อมูลลูกจ้างชั่วคราว
   *
   * @summary ประวัติการแก้ไขข้อมูลลูกจ้างชั่วคราว (ADMIN)
   *
   * @param {string} profileEmployeeId profileEmployeeId ทะเบียนประวัติลูกจ้างชั่วคราว
   */
  @Get("information/history/{profileEmployeeId}")
  async getInformationHistory(@Path() profileEmployeeId: string, @Request() req: RequestWithUser) {
    let _workflow = await new permission().Workflow(req, profileEmployeeId, "SYS_REGISTRY_EMP");
    if (_workflow == false)
      await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_EMP", profileEmployeeId);
    const profileInformation = await this.informationHistoryRepository.find({
      where: { profileEmployeeId: profileEmployeeId },
      order: {
        createdAt: "DESC",
      },
    });
    return new HttpSuccess(profileInformation);
  }

  /**
   * API รายการข้อมูลการจ้าง
   *
   * @summary รายการข้อมูลการจ้าง
   *
   * @param {string} profileEmployeeId profileEmployeeId ทะเบียนประวัติลูกจ้างชั่วคราว
   */
  @Get("employment/{profileEmployeeId}")
  async ProfileEmployeeEmployment(
    @Path() profileEmployeeId: string,
    @Request() req: RequestWithUser,
  ) {
    let _workflow = await new permission().Workflow(req, profileEmployeeId, "SYS_REGISTRY_EMP");
    if (_workflow == false)
      await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_EMP", profileEmployeeId);
    const employment = await this.employmentRepository.find({
      where: { profileEmployeeId: profileEmployeeId },
      order: { createdAt: "ASC" },
    });
    const mapData = employment.map((employment) => ({
      id: employment.id,
      date: employment.date,
      command: employment.command,
    }));
    return new HttpSuccess(mapData);
  }

  /**
   * API รายละเอียดข้อมูลการจ้าง
   *
   * @summary รายละเอียดข้อมูลการจ้าง
   *
   * @param {string} id Id ข้อมูลการจ้าง
   */
  @Get("employment/id/{id}")
  async GetEmploymentById(@Path() id: string, @Request() req: RequestWithUser) {
    const employment = await this.employmentRepository.findOne({
      where: { id: id },
    });
    if (employment) {
      let _workflow = await new permission().Workflow(req, id, "SYS_REGISTRY_EMP");
      if (_workflow == false)
        await new permission().PermissionOrgUserGet(
          req,
          "SYS_REGISTRY_EMP",
          employment.profileEmployeeId,
        );
    }
    return new HttpSuccess(employment);
  }

  /**
   * API ประวัติของข้อมูลการจ้าง
   *
   * @summary ประวัติของข้อมูลการจ้าง
   *
   * @param {string} id Id ข้อมูลการจ้าง
   */
  @Get("employment/history/{id}")
  async GetHistoryEmploymentById(@Path() id: string, @Request() req: RequestWithUser) {
    const employment = await this.employmentRepository.findOne({
      where: { id: id },
    });
    if (employment) {
      let _workflow = await new permission().Workflow(req, id, "SYS_REGISTRY_EMP");
      if (_workflow == false)
        await new permission().PermissionOrgUserGet(
          req,
          "SYS_REGISTRY_EMP",
          employment.profileEmployeeId,
        );
    }
    const employmentHistory = await this.employmentHistoryRepository.find({
      where: { profileEmployeeEmploymentId: id },
      order: { lastUpdatedAt: "ASC" },
    });
    return new HttpSuccess(employmentHistory);
  }

  /**
   * API เพิ่มข้อมูลการจ้าง
   *
   * @summary เพิ่มข้อมูลการจ้าง
   *
   * @param {string} profileEmployeeId  profileEmployeeId ทะเบียนประวัติลูกจ้างชั่วคราว
   */
  @Post("employment/{profileEmployeeId}")
  async CreateEmployment(
    @Path() profileEmployeeId: string,
    @Body() body: CreateEmploymentProfileEmployee,
    @Request() request: RequestWithUser,
  ) {
    const profile = await this.profileRepo.findOne({
      where: { id: profileEmployeeId },
    });
    if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    await new permission().PermissionOrgUserUpdate(request, "SYS_REGISTRY_EMP", profile.id);

    const data = new ProfileEmployeeEmployment();

    const meta = {
      createdUserId: request.user.sub,
      createdFullName: request.user.name,
      lastUpdateUserId: request.user.sub,
      lastUpdateFullName: request.user.name,
      createdAt: new Date(),
      lastUpdatedAt: new Date(),
      profileEmployeeId: profileEmployeeId,
    };

    Object.assign(data, { ...body, ...meta });
    const history = new ProfileEmployeeEmploymentHistory();
    Object.assign(history, { ...data, id: undefined });

    await this.employmentRepository.save(data);
    history.profileEmployeeEmploymentId = data.id;
    await this.employmentHistoryRepository.save(history);

    return new HttpSuccess();
  }

  /**
   * API ลบข้อมูลการจ้าง
   *
   * @summary ลบข้อมูลการจ้าง  (ADMIN)
   *
   * @param {string} id  Id ข้อมูลการจ้าง
   */
  @Delete("employment/{id}")
  async DeleteEmployment(@Path() id: string, @Request() request: RequestWithUser) {
    const employment = await this.employmentRepository.findOne({
      where: { id: id },
    });
    if (employment) {
      await new permission().PermissionOrgUserDelete(
        request,
        "SYS_REGISTRY_EMP",
        employment.profileEmployeeId,
      );
    }
    await this.employmentHistoryRepository.delete({
      profileEmployeeEmploymentId: id,
    });

    const result = await this.employmentRepository.delete({ id });
    if (result.affected == undefined || result.affected <= 0) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    }
    return new HttpSuccess();
  }

  /**
   * API แก้ไขข้อมูลการจ้าง
   *
   * @summary แก้ไขข้อมูลการจ้าง (ADMIN)
   *
   * @param {string} id  Id ข้อมูลการจ้าง
   */
  @Put("employment/{id}")
  async UpdateEmployment(
    @Request() request: RequestWithUser,
    @Path() id: string,
    @Body() body: UpdateEmploymentProfileEmployee,
  ) {
    const employment = await this.employmentRepository.findOneBy({ id });
    if (!employment) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    await new permission().PermissionOrgUserUpdate(
      request,
      "SYS_REGISTRY_EMP",
      employment.profileEmployeeId,
    );

    const history = new ProfileEmployeeEmploymentHistory();
    Object.assign(employment, body);
    Object.assign(history, { ...employment, id: undefined });

    employment.lastUpdateUserId = request.user.sub;
    employment.lastUpdateFullName = request.user.name;
    employment.lastUpdatedAt = new Date();
    history.profileEmployeeEmploymentId = id;
    history.lastUpdateUserId = request.user.sub;
    history.lastUpdateFullName = request.user.name;
    history.createdUserId = request.user.sub;
    history.createdFullName = request.user.name;
    history.createdAt = new Date();
    history.lastUpdatedAt = new Date();

    await Promise.all([
      this.employmentRepository.save(employment),
      this.employmentHistoryRepository.save(history),
    ]);

    return new HttpSuccess();
  }

  /**
   * API ออกคำสั่งลูกจ้าง
   *
   * @summary ORG_038 - ออกคำสั่งลูกจ้าง (ADMIN) #
   *
   */
  @Post("report")
  async sendReport(@Request() request: RequestWithUser, @Body() requestBody: { id: string[] }) {
    const profiles = await this.profileRepo.find({ where: { id: In(requestBody.id) } });

    const _profiles = await Promise.all(
      profiles.map(async (item: any) => {
        return {
          ...item,
          statusTemp: "REPORT",
          lastUpdateUserId: request.user.sub,
          lastUpdateFullName: request.user.name,
          lastUpdatedAt: new Date(),
        };
      }),
    );
    await this.profileRepo.save(_profiles);
    return new HttpSuccess();
  }

  /**
   * API ออกคำสั่งลูกจ้าง
   *
   * @summary ORG_038 - ออกคำสั่งลูกจ้าง (ADMIN) #
   *
   */
  @Post("report/resume")
  async doneReport(
    @Body()
    body: {
      result: {
        id: string;
        remark: string;
        amount: Double | null;
        positionSalaryAmount: Double | null;
        mouthSalaryAmount: Double | null;
        refCommandNo: string;
      }[];
    },
    @Request() request: { user: Record<string, any> },
  ) {
    await Promise.all(
      body.result.map(async (v) => {
        const profile = await this.profileRepo.findOne({
          where: {
            id: v.id,
          },
          relations: ["posType", "posLevel"],
        });
        if (profile != null) {
          await new CallAPI()
            .PostData(request, "/org/profile-employee/salary", {
              profileEmployeeId: profile.id,
              date: new Date(),
              amount: v.amount,
              positionSalaryAmount: v.positionSalaryAmount,
              mouthSalaryAmount: v.mouthSalaryAmount,
              posNo: profile.posMasterNoTemp,
              position: profile.positionTemp,
              positionType: profile.posTypeNameTemp,
              positionLevel: profile.posLevelNameTemp,
              refCommandNo: v.refCommandNo,
              remark: v.remark,
            })
            .then(async () => {
              profile.statusTemp = "DONE";
              profile.employeeClass = "PERM";
              const _null: any = null;
              profile.employeeWage = v.amount == null ? _null : v.amount.toString();
              await this.profileRepo.save(profile);
            });
          await new CallAPI()
            .PostData(request, "/org/employee/pos/report/current", {
              posmasterId: profile.posmasterIdTemp,
              positionId: profile.positionIdTemp,
              profileId: profile.id,
            })
            .then(async () => { });
        }
      }),
    );
    return new HttpSuccess();
  }

  /**
   * API ค้นหาข้อมูลทะเบียนประวัติที่ยังไม่เชื่อม keycloak
   *
   * @summary ค้นหาข้อมูลทะเบียนประวัติที่ยังไม่เชื่อม keycloak
   *
   */
  @Post("search-personal-no-keycloak")
  async getProfileBySearchKeywordNoKeyCloak(
    @Query("page") page: number = 1,
    @Query("pageSize") pageSize: number = 10,
    @Body()
    body: {
      fieldName: string;
      keyword?: string;
      system?: string;
    },
  ) {
    const findRevision = await this.orgRevisionRepo.findOne({
      where: { orgRevisionIsCurrent: true },
    });
    if (!findRevision) {
      throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
    }

    let queryLike = "1=1";
    switch (body.fieldName) {
      case "citizenId":
        queryLike = "profile.citizenId LIKE :keyword";
        break;

      case "fullname":
      case "fullName":
        queryLike =
          "CONCAT(profile.prefix, profile.firstName, ' ', profile.lastName) LIKE :keyword";
        break;

      case "firstname":
      case "firstName":
        queryLike = "profile.firstName LIKE :keyword";
        break;

      case "lastname":
      case "lastName":
        queryLike = "profile.lastName LIKE :keyword";
        break;

      default:
        queryLike = "1=1";
        break;
    }

    let query = await this.profileRepo
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.posType", "posType")
      .leftJoinAndSelect("profile.posLevel", "posLevel")
      .leftJoinAndSelect("profile.current_holders", "current_holders")
      .leftJoinAndSelect("current_holders.orgRoot", "orgRoot")
      .leftJoinAndSelect("current_holders.orgChild1", "orgChild1")
      .leftJoinAndSelect("current_holders.orgChild2", "orgChild2")
      .leftJoinAndSelect("current_holders.orgChild3", "orgChild3")
      .leftJoinAndSelect("current_holders.orgChild4", "orgChild4")
      .where(body.system ? "profile.isActive = :isActive" : "profile.isDelete = :isDelete", {
        isActive: false,
        isDelete: true,
      })
      .andWhere(
        new Brackets((qb) => {
          qb.orWhere(body.keyword ? queryLike : "1=1", { keyword: `%${body.keyword}%` });
        }),
      );

    const [findProfile, total] = await query
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getManyAndCount();

    const mapDataProfile = await Promise.all(
      findProfile.map(async (item: ProfileEmployee) => {
        const fullName = `${item.prefix} ${item.firstName} ${item.lastName}`;
        let shortName = null;
        let root = null;
        let posMasterNo = null;
        if (item.isLeave == false) {
          shortName =
            item.current_holders.length == 0
              ? null
              : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
                item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4 !=
                null
                ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4.orgChild4ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
                : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
                  item.current_holders.find((x) => x.orgRevisionId == findRevision.id)
                    ?.orgChild3 != null
                  ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3.orgChild3ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
                  : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
                    item.current_holders.find((x) => x.orgRevisionId == findRevision.id)
                      ?.orgChild2 != null
                    ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2.orgChild2ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
                    : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) !=
                      null &&
                      item.current_holders.find((x) => x.orgRevisionId == findRevision.id)
                        ?.orgChild1 != null
                      ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1.orgChild1ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
                      : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) !=
                        null &&
                        item.current_holders.find((x) => x.orgRevisionId == findRevision.id)
                          ?.orgRoot != null
                        ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot.orgRootShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
                        : null;

          root =
            item.current_holders.length == 0 ||
              (item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
                item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot == null)
              ? null
              : item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot;
          root = root == null ? null : root.orgRootName;
          posMasterNo = item.current_holders?.find(
            (x) => x.orgRevisionId == findRevision.id,
          )?.posMasterNo;
        } else {
          const profileSalary = await this.salaryRepo
            .createQueryBuilder("s")
            .where("s.profileEmployeeId = :profileId", { profileId: item.id })
            .andWhere("s.commandCode IN (:...codes)", {
              codes: [
                "0",
                "9",
                "1",
                "2",
                "3",
                "4",
                "8",
                "10",
                "11",
                "12",
                "13",
                "14",
                "15",
                "16",
                "20",
              ],
            })
            .orderBy("s.order", "DESC")
            .addOrderBy("s.createdAt", "DESC")
            .take(2)
            .getMany();
          if (profileSalary.length > 0) {
            shortName = item.isRetirement
              ? profileSalary.length > 1
                ? `${profileSalary[1]?.posNoAbb} ${profileSalary[1]?.posNo}`
                : `${profileSalary[0]?.posNoAbb} ${profileSalary[0]?.posNo}`
              : `${profileSalary[0]?.posNoAbb} ${profileSalary[0]?.posNo}`;
            posMasterNo = item.isRetirement
              ? profileSalary.length > 1
                ? profileSalary[1]?.posNo
                : profileSalary[0]?.posNo
              : profileSalary[0]?.posNo;
            root = item.isRetirement
              ? profileSalary.length > 1
                ? profileSalary[1]?.orgRoot
                : profileSalary[0]?.orgRoot
              : profileSalary[0]?.orgRoot;
          }
        }

        const latestProfileEducation = await this.profileEducationRepo.findOne({
          where: { profileEmployeeId: item.id, isDeleted: false },
          order: { level: "ASC" },
        });

        return {
          id: item.id,
          prefix: item.prefix,
          rank: item.rank,
          firstName: item.firstName,
          lastName: item.lastName,
          position: item.position,
          citizenId: item.citizenId,
          email: item.email,
          phone: item.phone,
          name: fullName,
          birthDate: item.birthDate,
          positionLevel: item.posLevelId,
          positionLevelName: item.posLevel?.posLevelName,
          positionType: item.posTypeId,
          positionTypeName: item.posType?.posTypeName,
          posNo: shortName,
          organization: root,
          salary: item.amount,
          posMasterNo: posMasterNo ?? null,
          posTypeId: item.posTypeId,
          posTypeName: item.posType?.posTypeName,
          posLevelId: item.posLevelId,
          posLevelName:
            item.posLevel == null && item.posType == null
              ? null
              : `${item.posType?.posTypeShortName} ${item.posLevel?.posLevelName}`,
          educationDegree:
            latestProfileEducation != null && latestProfileEducation.educationLevel != null
              ? latestProfileEducation.educationLevel
              : null,
        };
      }),
    );

    return new HttpSuccess({ data: mapDataProfile, total });
  }
  /**
   * API ข้อมูลทะเบียนประวัติตาม profileid
   *
   * @summary ORG_065 - ข้อมูลทะเบียนประวัติตาม profileid (ADMIN) #70
   *
   */
  @Get("profileid/position/{id}")
  async getProfileByProfileid(@Request() request: RequestWithUser, @Path() id: string) {
    const profile = await this.profileRepo.findOne({
      where: { id: id },
      relations: [
        "posLevel",
        "posType",
        "current_holders",
        "current_holders.orgRoot",
        "current_holders.orgChild1",
        "current_holders.orgChild2",
        "current_holders.orgChild3",
        "current_holders.orgChild4",
        // "profileSalary",
        "profileEducations",
      ],
      order: {
        // profileSalary: {
        //   order: "DESC",
        // },
        profileEducations: {
          level: "ASC",
        },
      },
    });
    if (!profile) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลบุคคลนี้ในระบบ");
    }
    //await new permission().PermissionOrgUserGet(request, "SYS_REGISTRY_EMP", profile.id); //ไม่แน่ใจEMPปิดไว้ก่อน

    const orgRevisionPublish = await this.orgRevisionRepo
      .createQueryBuilder("orgRevision")
      .where("orgRevision.orgRevisionIsDraft = false")
      .andWhere("orgRevision.orgRevisionIsCurrent = true")
      .getOne();
    if (!orgRevisionPublish) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบแบบร่างโครงสร้าง");
    }

    const permissionProflile = await this.permissionProflileRepository.findOne({
      relations: ["orgRootTree"],
      where: {
        profileId: id,
        orgRootTree: {
          orgRevisionId: orgRevisionPublish.id,
        },
      },
    });
    const posMaster =
      profile.current_holders == null ||
        profile.current_holders.length == 0 ||
        profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) == null
        ? null
        : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id);
    const root =
      profile.current_holders == null ||
        profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgRoot == null
        ? null
        : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgRoot;
    const child1 =
      profile.current_holders == null ||
        profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild1 ==
        null
        ? null
        : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild1;
    const child2 =
      profile.current_holders == null ||
        profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild2 ==
        null
        ? null
        : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild2;
    const child3 =
      profile.current_holders == null ||
        profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild3 ==
        null
        ? null
        : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild3;
    const child4 =
      profile.current_holders == null ||
        profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild4 ==
        null
        ? null
        : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild4;
    const _numPart = posMaster ? [posMaster.posMasterNoPrefix, posMaster.posMasterNo, posMaster.posMasterNoSuffix].filter((p) => p !== null && p !== undefined && p !== '').join(' ') : '';
    const _profile: any = {
      profileId: profile.id,
      prefix: profile.prefix,
      rank: profile.rank,
      isProbation: profile.isProbation,
      firstName: profile.firstName,
      lastName: profile.lastName,
      citizenId: profile.citizenId,
      birthDate: profile.birthDate,
      position: profile.position,
      leaveDate: profile.dateLeave,
      posMasterNo: posMaster == null ? null : posMaster.posMasterNo,
      posLevelName: `${profile?.posType?.posTypeShortName ?? ""} ${profile?.posLevel?.posLevelName ?? ""}`,
      posLevelRank: profile.posLevel == null ? null : profile.posLevel.posLevelRank,
      posLevelId: profile.posLevel == null ? null : profile.posLevel.id,
      posTypeName: profile.posType == null ? null : profile.posType.posTypeName,
      posTypeRank: profile.posType == null ? null : profile.posType.posTypeRank,
      posTypeShortName: profile.posType == null ? null : profile.posType.posTypeShortName,
      posTypeId: profile.posType == null ? null : profile.posType.id,
      rootId: root == null ? null : root.id,
      rootDnaId: root == null ? null : root.ancestorDNA,
      root: root == null ? null : root.orgRootName,
      rootShortName: root == null ? null : root.orgRootShortName,
      child1Id: child1 == null ? null : child1.id,
      child1DnaId: child1 == null ? null : child1.ancestorDNA,
      child1: child1 == null ? null : child1.orgChild1Name,
      child1ShortName: child1 == null ? null : child1.orgChild1ShortName,
      child2Id: child2 == null ? null : child2.id,
      child2DnaId: child2 == null ? null : child2.ancestorDNA,
      child2: child2 == null ? null : child2.orgChild2Name,
      child2ShortName: child2 == null ? null : child2.orgChild2ShortName,
      child3Id: child3 == null ? null : child3.id,
      child3DnaId: child3 == null ? null : child3.ancestorDNA,
      child3: child3 == null ? null : child3.orgChild3Name,
      child3ShortName: child3 == null ? null : child3.orgChild3ShortName,
      child4Id: child4 == null ? null : child4.id,
      child4DnaId: child4 == null ? null : child4.ancestorDNA,
      child4: child4 == null ? null : child4.orgChild4Name,
      child4ShortName: child4 == null ? null : child4.orgChild4ShortName,
      node: null,
      nodeId: null,
      posNo: null,
      salary: profile.amount,
      education:
        profile && profile.profileEducations.length > 0
          ? await getTopDegrees(profile.profileEducations)
          : "-",
      statusCheckEdit: profile.statusCheckEdit,
      isEdit: permissionProflile?.isEdit ?? false,
      isCheck: permissionProflile?.isCheck ?? false,
    };

    if (_profile.child4Id != null) {
      _profile.node = 4;
      _profile.nodeId = _profile.child4Id;
      _profile.nodeShortName = _profile.child4ShortName;
      _profile.posNo = `${_profile.child4ShortName} ${_numPart}`;
    } else if (_profile.child3Id != null) {
      _profile.node = 3;
      _profile.nodeId = _profile.child3Id;
      _profile.nodeShortName = _profile.child3ShortName;
      _profile.posNo = `${_profile.child3ShortName} ${_numPart}`;
    } else if (_profile.child2Id != null) {
      _profile.node = 2;
      _profile.nodeId = _profile.child2Id;
      _profile.nodeShortName = _profile.child2ShortName;
      _profile.posNo = `${_profile.child2ShortName} ${_numPart}`;
    } else if (_profile.child1Id != null) {
      _profile.node = 1;
      _profile.nodeId = _profile.child1Id;
      _profile.nodeShortName = _profile.child1ShortName;
      _profile.posNo = `${_profile.child1ShortName} ${_numPart}`;
    } else if (_profile.rootId != null) {
      _profile.node = 0;
      _profile.nodeId = _profile.rootId;
      _profile.nodeShortName = _profile.rootShortName;
      _profile.posNo = `${_profile.rootShortName} ${_numPart}`;
    }
    return new HttpSuccess(_profile);
  }

  async sendVerifyEmail(
    @Request() req: RequestWithUser,
    @Body()
    body: {
      profileId: string;
      email: string;
      subject: string;
    },
  ) {
    const jwt = require("jsonwebtoken");
    const token = jwt.sign(
      { email_id: body.email, profileId: body.profileId },
      process.env.AUTH_ACCOUNT_SECRET,
      { expiresIn: "15m" },
    );
    const link = process.env.VITE_URL_USER + "/verifyemail?upn=" + token;

    await new CallAPI()
      .PostData(req, "/placement/noti/send-mail", {
        subject: body.subject,
        body: link,
        Email: body.email,
      })
      .catch((error) => {
        console.error("Error calling API:", error);
      });
    return new HttpSuccess();
  }

  /**
   * API แก้ไขเบอร์โทรศัพท์ ลูกจ้างประจำ
   *
   * @summary แก้ไขเบอร์โทรศัพท์ ลูกจ้างประจำ (USER)
   *
   */
  @Put("updatePhoneNumber/user")
  async updatePhoneNumber(
    @Request() request: RequestWithUser,
    @Body()
    body: {
      phone: string;
    },
  ) {
    const profile = await this.profileRepo.findOne({
      relations: {
        posLevel: true,
        posType: true,
      },
      where: { keycloak: request.user.sub },
    });

    if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");

    const history = new ProfileEmployeeHistory();

    Object.assign(profile, body);
    Object.assign(history, { ...profile, id: undefined });

    profile.lastUpdateUserId = request.user.sub;
    profile.lastUpdateFullName = request.user.name;
    profile.lastUpdatedAt = new Date();
    history.lastUpdateUserId = request.user.sub;
    history.lastUpdateFullName = request.user.name;
    history.createdUserId = request.user.sub;
    history.createdFullName = request.user.name;
    history.createdAt = new Date();
    history.lastUpdatedAt = new Date();

    await Promise.all([
      this.profileRepo.save(profile, { data: request }),
      this.profileHistoryRepo.save(history, { data: request }),
    ]);
    return new HttpSuccess();
  }

  /**
   * API แก้ไขอีเมล ลูกจ้างประจำ
   *
   * @summary แก้ไขอีเมล ลูกจ้างประจำ (USER)
   *
   */
  @Put("updateEmail/user")
  async updateEmail(
    @Request() request: RequestWithUser,
    @Body()
    body: {
      email: string;
    },
  ) {
    const profile = await this.profileRepo.findOne({
      relations: {
        posLevel: true,
        posType: true,
      },
      where: { keycloak: request.user.sub },
    });

    if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");

    const history = new ProfileEmployeeHistory();

    Object.assign(profile, body);
    Object.assign(history, { ...profile, id: undefined });

    profile.statusEmail = "NOT_VERIFIED";
    profile.lastUpdateUserId = request.user.sub;
    profile.lastUpdateFullName = request.user.name;
    profile.lastUpdatedAt = new Date();
    history.lastUpdateUserId = request.user.sub;
    history.lastUpdateFullName = request.user.name;
    history.createdUserId = request.user.sub;
    history.createdFullName = request.user.name;
    history.createdAt = new Date();
    history.lastUpdatedAt = new Date();

    await Promise.all([
      this.profileRepo.save(profile, { data: request }),
      this.profileHistoryRepo.save(history, { data: request }),
    ]);
    const verifyemailBody = {
      profileId: profile.id,
      email: body.email,
      subject: "ยืนยันอีเมล",
    };
    this.sendVerifyEmail(request, verifyemailBody);
    return new HttpSuccess();
  }
}
