import {
  Controller,
  Post,
  Put,
  Delete,
  Route,
  Security,
  Tags,
  Body,
  Path,
  Request,
  SuccessResponse,
  Response,
  Get,
  Query,
  Example,
  Patch,
} 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 {
  Profile,
  CreateProfile,
  UpdateProfile,
  ProfileHistory,
  CreateProfileAllFields,
  UpdateProfileReqEdit,
  UpdateProfileFather,
  UpdateProfileMother,
  UpdateProfileCouple,
} from "../entities/Profile";
import { Brackets, IsNull, Like, Not } from "typeorm";
import { OrgRevision } from "../entities/OrgRevision";
import { PosMaster } from "../entities/PosMaster";
import { PosLevel } from "../entities/PosLevel";
import { PosType } from "../entities/PosType";
import {
  calculateAge,
  calculateRetireDate,
  calculateRetireLaw,
  removeProfileInOrganize,
  setLogDataDiff,
} from "../interfaces/utils";
import { RequestWithUser } from "../middlewares/user";
import { Position } from "../entities/Position";
import { ProfileEmployee } from "../entities/ProfileEmployee";
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 { ProfileInsignia } from "../entities/ProfileInsignia";
import { ProfileLeave } from "../entities/ProfileLeave";
import { updateName } from "../keycloak";
import permission from "../interfaces/permission";
import { PosMasterAct } from "../entities/PosMasterAct";
import axios from "axios";
import { ProfileFamilyFatherHistory } from "../entities/ProfileFamilyFatherHistory";
import { ProfileFamilyMotherHistory } from "../entities/ProfileFamilyMotherHistory";
import { ProfileFamilyCoupleHistory } from "../entities/ProfileFamilyCoupleHistory";
import { viewDirector } from "../entities/view/viewDirector";
import { viewDirectorActing } from "../entities/view/viewDirectorActing";
import CallAPI from "../interfaces/call-api";
@Route("api/v1/org/profile")
@Tags("Profile")
@Security("bearerAuth")
@Response(
  HttpStatus.INTERNAL_SERVER_ERROR,
  "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง",
)
@SuccessResponse(HttpStatus.OK, "สำเร็จ")
export class ProfileController extends Controller {
  private orgRevisionRepo = AppDataSource.getRepository(OrgRevision);
  private posMasterRepo = AppDataSource.getRepository(PosMaster);
  private profileRepo = AppDataSource.getRepository(Profile);
  private profileEmpRepo = AppDataSource.getRepository(ProfileEmployee);
  private profileHistoryRepo = AppDataSource.getRepository(ProfileHistory);
  private posLevelRepo = AppDataSource.getRepository(PosLevel);
  private posTypeRepo = AppDataSource.getRepository(PosType);
  private positionRepository = AppDataSource.getRepository(Position);
  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 profileFamilyCoupleHistoryRepo = AppDataSource.getRepository(ProfileFamilyCoupleHistory);
  private profileFamilyMotherRepository = AppDataSource.getRepository(ProfileFamilyMother);
  private profileFamilyMotherHistoryRepo = AppDataSource.getRepository(ProfileFamilyMotherHistory);
  private profileFamilyFatherRepository = AppDataSource.getRepository(ProfileFamilyFather);
  private profileFamilyFatherHistoryRepo = AppDataSource.getRepository(ProfileFamilyFatherHistory);
  private trainingRepository = AppDataSource.getRepository(ProfileTraining);
  private disciplineRepository = AppDataSource.getRepository(ProfileDiscipline);
  private educationRepository = AppDataSource.getRepository(ProfileEducation);
  private salaryRepository = AppDataSource.getRepository(ProfileSalary);
  private profileEducationRepository = AppDataSource.getRepository(ProfileEducation);
  private provinceRepo = AppDataSource.getRepository(Province);
  private districtRepo = AppDataSource.getRepository(District);
  private subDistrictRepo = AppDataSource.getRepository(SubDistrict);
  private profileInsigniaRepo = AppDataSource.getRepository(ProfileInsignia);
  private profileLeaveRepository = AppDataSource.getRepository(ProfileLeave);
  private posMasterActRepository = AppDataSource.getRepository(PosMasterAct);

  /**
   * 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: {
          date: "DESC",
        },
      },
    });
    if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    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 == null || root == undefined ? "" : `${root.orgRootName}`;
    let _child1 = child1 == null || child1 == undefined ? "" : `${child1.orgChild1Name}/`;
    let _child2 = child2 == null || child2 == undefined ? "" : `${child2.orgChild2Name}/`;
    let _child3 = child3 == null || child3 == undefined ? "" : `${child3.orgChild3Name}/`;
    let _child4 = child4 == null || child4 == undefined ? "" : `${child4.orgChild4Name}/`;

    const educations = await this.educationRepository.find({
      select: ["startDate", "endDate", "educationLevel", "degree", "field", "institute"],
      where: { profileId: id },
      order: { lastUpdatedAt: "DESC" },
    });
    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_monthYear(profile.birthDate))
          : "-",
      dateRetire:
        profile.dateRetire != null
          ? Extension.ToThaiNumber(Extension.ToThaiShortDate_monthYear(profile.dateRetire))
          : "-",
      salaryAmount:
        profile.amount != null ? Extension.ToThaiNumber(profile.amount.toLocaleString()) : "-",
      registrationAddress: Extension.ToThaiNumber(
        `${_regisAddres}${_subDistrict}${_district}${_province}${registrationZipCode}`,
      ),
      salaryDate:
        profile.profileSalary.length > 0 && profile.profileSalary[0].date != null
          ? Extension.ToThaiNumber(
              Extension.ToThaiShortDate_monthYear(profile.profileSalary[0].date),
            )
          : "-",
      positionName: profile.position != null ? profile.position : "-",
      appointText:
        profile.dateAppoint != null
          ? Extension.ToThaiNumber(Extension.ToThaiShortDate_monthYear(profile.dateAppoint))
          : "-",
      ocFullPath: `${_child4}${_child3}${_child2}${_child1}${_root}`,
      educations: Education,
      url: ImgUrl ? ImgUrl : `https://bma-ehr.frappet.synology.me/assets/avatar_user-89f22423.jpg`,
    };

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

  /**
   * รายงาน ก.ก.1 (ข้าราชการ)
   *
   * @summary รายงาน ก.ก.1 (ข้าราชการ)
   *
   * @param {string} id  Id โปรไฟล์
   */
  @Get("kk1/{id}")
  public async getKk1(@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: { profileId: id },
      select: ["couplePrefix", "coupleFirstName", "coupleLastName", "coupleLastNameOld"],
      order: { lastUpdatedAt: "DESC" },
    });

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

    const profileFamilyFather = await this.profileFamilyFatherRepository.findOne({
      where: { profileId: 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
    const _root = root ? `${root.orgRootName}` : "";
    const _child1 = child1 ? `${child1.orgChild1Name}/` : "";
    const _child2 = child2 ? `${child2.orgChild2Name}/` : "";
    const _child3 = child3 ? `${child3.orgChild3Name}/` : "";
    const _child4 = child4 ? `${child4.orgChild4Name}/` : "";

    const cert_raw = await this.certificateRepository.find({
      where: { profileId: id },
      select: ["certificateType", "issuer", "certificateNo", "issueDate"],
      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", "name"],
      where: { profileId: id },
      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"],
      where: { profileId: id },
      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: Extension.ToThaiNumber(item.refCommandNo) ?? null,
          }))
        : [
            {
              disciplineYear: "-",
              disciplineDetail: "-",
              refNo: "-",
            },
          ];

    const education_raw = await this.educationRepository.find({
      select: ["startDate", "endDate", "educationLevel", "degree", "field", "institute"],
      where: { profileId: id },
      // order: { lastUpdatedAt: "DESC" },
      order: { createdAt: "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.salaryRepository.find({
      select: [
        "date",
        "position",
        "posNo",
        "positionType",
        "positionLevel",
        "positionSalaryAmount",
        "refCommandNo",
        "amount",
        "templateDoc",
      ],
      where: { profileId: id },
      order: { order: "ASC" },
    });

    const salarys =
      salary_raw.length > 0
        ? salary_raw.map((item) => ({
            salaryDate: item.date
              ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.date))
              : null,
            position: item.position != null ? Extension.ToThaiNumber(item.position) : 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.templateDoc ? Extension.ToThaiNumber(item.templateDoc) : 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}${_child3}${_child2}${_child1}${_root}`,
          }))
        : [
            {
              salaryDate: "-",
              position: "-",
              posNo: "-",
              salary: "-",
              rank: "-",
              refAll: "-",
              positionLevel: "-",
              positionType: "-",
              positionAmount: "-",
              fullName: "-",
              ocFullPath: "-",
            },
          ];

    const insignia_raw = await this.profileInsigniaRepo.find({
      relations: {
        insignia: {
          insigniaType: true,
        },
      },
      where: { profileId: id },
      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.find({
      relations: { leaveType: true },
      where: { profileId: id },
      order: { dateLeaveStart: "ASC" },
    });
    const leaves =
      leave_raw.length > 0
        ? leave_raw.map((item) => ({
            leaveTypeName: item.leaveType.name,
            dateLeaveStart: item.dateLeaveStart
              ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.dateLeaveStart))
              : "",
            leaveDays: item.leaveDays ? Extension.ToThaiNumber(item.leaveDays.toString()) : "",
          }))
        : [
            {
              leaveTypeName: "-",
              dateLeaveStart: "-",
              leaveDays: "-",
            },
          ];

    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}${_child3}${_child2}${_child1}${_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.telephoneNumber) : "",
      url: ImgUrl ? ImgUrl : `https://bma-ehr.frappet.synology.me/assets/avatar_user-89f22423.jpg`,
      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,
      certs,
      trainings,
      disciplines,
      educations,
      salarys,
    };

    return new HttpSuccess({
      template: "kk1",
      reportName: "docx-report",
      data: data,
    });
  }
  /**
   *
   *
   * @param {string} id  Id ทะเบียนประวัติ
   */
  @Get("placement/{id}")
  async getProfilePlacement(@Path() id: string) {
    const profile = await this.profileRepo.findOne({
      where: { id: id },
    });

    const posMaster = await this.posMasterRepo.findOne({
      where: { current_holderId: profile?.id },
    });
    if (!posMaster) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลการครองตำแหน่ง");
    const orgRoot = posMaster.orgRootId;
    const orgChild1 = posMaster.orgChild1Id;
    const orgChild2 = posMaster.orgChild2Id;
    const orgChild3 = posMaster.orgChild3Id;
    const orgChild4 = posMaster.orgChild4Id;

    const findChild4 = await this.profileRepo
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.current_holders", "current_holders")
      .leftJoinAndSelect("profile.posLevel", "posLevel")
      .leftJoinAndSelect("profile.posType", "posType")
      .andWhere({ keycloak: Not(IsNull()) })
      .where("current_holders.current_holderId IS NOT NULL")
      .andWhere("current_holders.orgRootId = :orgRootId", { orgRootId: orgRoot })
      .andWhere("current_holders.current_holderId <> :current_holderId", {
        current_holderId: posMaster.current_holderId,
      })
      .getMany();
    const findChild3 = await this.profileRepo
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.current_holders", "current_holders")
      .leftJoinAndSelect("profile.posLevel", "posLevel")
      .leftJoinAndSelect("profile.posType", "posType")
      .andWhere({ keycloak: Not(IsNull()) })
      .where("current_holders.current_holderId IS NOT NULL")
      .andWhere("current_holders.orgRootId = :orgRootId", { orgRootId: orgRoot })
      .andWhere("current_holders.current_holderId <> :current_holderId", {
        current_holderId: posMaster.current_holderId,
      })
      .andWhere("current_holders.orgChild3Id = :orgChild3Id", { orgChild3Id: orgChild3 })
      .andWhere("current_holders.orgChild4Id IS NULL")
      .getMany();
    const findChild2 = await this.profileRepo
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.current_holders", "current_holders")
      .leftJoinAndSelect("profile.posLevel", "posLevel")
      .leftJoinAndSelect("profile.posType", "posType")
      .andWhere({ keycloak: Not(IsNull()) })
      .where("current_holders.current_holderId IS NOT NULL")
      .andWhere("current_holders.orgRootId = :orgRootId", { orgRootId: orgRoot })
      .andWhere("current_holders.current_holderId <> :current_holderId", {
        current_holderId: posMaster.current_holderId,
      })
      .andWhere("current_holders.orgChild2Id = :orgChild2Id", { orgChild2Id: orgChild2 })
      .andWhere("current_holders.orgChild3Id IS NULL")
      .getMany();
    const findChild1 = await this.profileRepo
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.current_holders", "current_holders")
      .leftJoinAndSelect("profile.posLevel", "posLevel")
      .leftJoinAndSelect("profile.posType", "posType")
      .andWhere({ keycloak: Not(IsNull()) })
      .where("current_holders.current_holderId IS NOT NULL")
      .andWhere("current_holders.orgRootId = :orgRootId", { orgRootId: orgRoot })
      .andWhere("current_holders.current_holderId <> :current_holderId", {
        current_holderId: posMaster.current_holderId,
      })
      .andWhere("current_holders.orgChild1Id = :orgChild1Id", { orgChild1Id: orgChild1 })
      .andWhere("current_holders.orgChild2Id IS NULL")
      .getMany();
    const findRoot = await this.profileRepo
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.current_holders", "current_holders")
      .leftJoinAndSelect("profile.posLevel", "posLevel")
      .leftJoinAndSelect("profile.posType", "posType")
      .andWhere({ keycloak: Not(IsNull()) })
      .where("current_holders.current_holderId IS NOT NULL")
      .andWhere("current_holders.orgRootId = :orgRootId", { orgRootId: orgRoot })
      .andWhere("current_holders.current_holderId <> :current_holderId", {
        current_holderId: posMaster.current_holderId,
      })
      .andWhere("current_holders.orgChild1Id  IS NULL")
      .getMany();

    let _caregiver: any;
    let caregiver: any;
    let _commander: any;
    let commander: any;
    let _chairman: any;
    let chairman: any;
    if (posMaster) {
      if (orgChild4) {
        if (findChild4) {
          _caregiver = findChild4;
          _commander = findChild3;
          _chairman = findChild2;
        } else if (findChild3) {
          _caregiver = findChild3;
          _commander = findChild2;
          _chairman = findChild1;
        } else if (findChild2) {
          _caregiver = findChild2;
          _commander = findChild1;
          _chairman = findRoot;
        } else if (findChild1) {
          _caregiver = findChild1;
          _commander = findRoot;
          _chairman = findRoot;
        } else if (findRoot) {
          _caregiver = findRoot;
          _commander = findRoot;
          _chairman = findRoot;
        }
      } else if (orgChild3) {
        if (findChild3) {
          _caregiver = findChild3;
          _commander = findChild2;
          _chairman = findChild1;
        } else if (findChild2) {
          _caregiver = findChild2;
          _commander = findChild1;
          _chairman = findRoot;
        } else if (findChild1) {
          _caregiver = findChild1;
          _commander = findRoot;
          _chairman = findRoot;
        } else if (findRoot) {
          _caregiver = findRoot;
          _commander = findRoot;
          _chairman = findRoot;
        }
      } else if (orgChild2) {
        if (findChild2) {
          _caregiver = findChild2;
          _commander = findChild1;
          _chairman = findRoot;
        } else if (findChild1) {
          _caregiver = findChild1;
          _commander = findRoot;
          _chairman = findRoot;
        } else if (findRoot) {
          _caregiver = findRoot;
          _commander = findRoot;
          _chairman = findRoot;
        }
      } else if (orgChild1) {
        if (findChild1) {
          _caregiver = findChild1;
          _commander = findRoot;
          _chairman = findRoot;
        } else if (findRoot) {
          _caregiver = findRoot;
          _commander = findRoot;
          _chairman = findRoot;
        }
      } else if (orgRoot) {
        if (findRoot) {
          _caregiver = findRoot;
          _commander = findRoot;
          _chairman = findRoot;
        }
      }
      caregiver = _caregiver.map((_data: any) => ({
        id: _data.id,
        prefix: _data.prefix,
        firstName: _data.firstName,
        lastName: _data.lastName,
        citizenId: _data.citizenId,
        position: _data.position,
        posLevel: _data.posLevel == null ? null : _data.posLevel.posLevelName,
        posType: _data.posType == null ? null : _data.posType.posTypeName,
        isDirector: true,
      }));
      commander = _commander.map((_data: any) => ({
        id: _data.id,
        prefix: _data.prefix,
        firstName: _data.firstName,
        lastName: _data.lastName,
        citizenId: _data.citizenId,
        position: _data.position,
        posLevel: _data.posLevel == null ? null : _data.posLevel.posLevelName,
        posType: _data.posType == null ? null : _data.posType.posTypeName,
        isDirector: true,
      }));
      chairman = _chairman.map((_data: any) => ({
        id: _data.id,
        prefix: _data.prefix,
        firstName: _data.firstName,
        lastName: _data.lastName,
        citizenId: _data.citizenId,
        position: _data.position,
        posLevel: _data.posLevel == null ? null : _data.posLevel.posLevelName,
        posType: _data.posType == null ? null : _data.posType.posTypeName,
        isDirector: true,
      }));
    }

    return new HttpSuccess({ caregiver, commander, chairman });
  }

  /**
   * API
   *
   * @summary API
   *
   */
  @Get("admin-keycloak")
  async listProfileIdByorg(@Request() request: RequestWithUser) {
    let _data: any = {
      root: null,
      child1: null,
      child2: null,
      child3: null,
      child4: null,
    };
    if (!request.user.role.includes("SUPER_ADMIN")) {
      _data = await new permission().PermissionOrgList(request, "SYS_ORG");
    }
    const profiles = await this.profileRepo
      .createQueryBuilder("profile")
      .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")
      .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 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({ keycloak: Not(IsNull()) })
      .andWhere({ keycloak: Not("") })
      .select("profile.keycloak", "keycloak")
      .getRawMany();
    const keycloakArray = profiles.map((p) => p.keycloak);

    return new HttpSuccess(keycloakArray);
  }
  /**
   *
   *
   */
  @Get("commander")
  async getProfileCommander(@Request() request: RequestWithUser) {
    const profile = await this.profileRepo.findOne({
      where: { keycloak: request.user.sub },
    });

    const posMaster = await this.posMasterRepo.findOne({
      where: { current_holderId: profile?.id },
    });
    if (!posMaster) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลการครองตำแหน่ง");
    const orgRoot = posMaster.orgRootId;
    const orgChild1 = posMaster.orgChild1Id;
    const orgChild2 = posMaster.orgChild2Id;
    const orgChild3 = posMaster.orgChild3Id;
    const orgChild4 = posMaster.orgChild4Id;

    const findChild4 = await this.profileRepo
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.current_holders", "current_holders")
      .leftJoinAndSelect("profile.posLevel", "posLevel")
      .leftJoinAndSelect("profile.posType", "posType")
      .andWhere({ keycloak: Not(IsNull()) })
      .where("current_holders.current_holderId IS NOT NULL")
      .andWhere("current_holders.orgRootId = :orgRootId", { orgRootId: orgRoot })
      .andWhere("current_holders.current_holderId <> :current_holderId", {
        current_holderId: posMaster.current_holderId,
      })
      .getMany();
    const findChild3 = await this.profileRepo
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.current_holders", "current_holders")
      .leftJoinAndSelect("profile.posLevel", "posLevel")
      .leftJoinAndSelect("profile.posType", "posType")
      .andWhere({ keycloak: Not(IsNull()) })
      .where("current_holders.current_holderId IS NOT NULL")
      .andWhere("current_holders.orgRootId = :orgRootId", { orgRootId: orgRoot })
      .andWhere("current_holders.current_holderId <> :current_holderId", {
        current_holderId: posMaster.current_holderId,
      })
      .andWhere("current_holders.orgChild3Id = :orgChild3Id", { orgChild3Id: orgChild3 })
      .andWhere("current_holders.orgChild4Id IS NULL")
      .getMany();
    const findChild2 = await this.profileRepo
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.current_holders", "current_holders")
      .leftJoinAndSelect("profile.posLevel", "posLevel")
      .leftJoinAndSelect("profile.posType", "posType")
      .andWhere({ keycloak: Not(IsNull()) })
      .where("current_holders.current_holderId IS NOT NULL")
      .andWhere("current_holders.orgRootId = :orgRootId", { orgRootId: orgRoot })
      .andWhere("current_holders.current_holderId <> :current_holderId", {
        current_holderId: posMaster.current_holderId,
      })
      .andWhere("current_holders.orgChild2Id = :orgChild2Id", { orgChild2Id: orgChild2 })
      .andWhere("current_holders.orgChild3Id IS NULL")
      .getMany();
    const findChild1 = await this.profileRepo
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.current_holders", "current_holders")
      .leftJoinAndSelect("profile.posLevel", "posLevel")
      .leftJoinAndSelect("profile.posType", "posType")
      .andWhere({ keycloak: Not(IsNull()) })
      .where("current_holders.current_holderId IS NOT NULL")
      .andWhere("current_holders.orgRootId = :orgRootId", { orgRootId: orgRoot })
      .andWhere("current_holders.current_holderId <> :current_holderId", {
        current_holderId: posMaster.current_holderId,
      })
      .andWhere("current_holders.orgChild1Id = :orgChild1Id", { orgChild1Id: orgChild1 })
      .andWhere("current_holders.orgChild2Id IS NULL")
      .getMany();
    const findRoot = await this.profileRepo
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.current_holders", "current_holders")
      .leftJoinAndSelect("profile.posLevel", "posLevel")
      .leftJoinAndSelect("profile.posType", "posType")
      .andWhere({ keycloak: Not(IsNull()) })
      .where("current_holders.current_holderId IS NOT NULL")
      .andWhere("current_holders.orgRootId = :orgRootId", { orgRootId: orgRoot })
      .andWhere("current_holders.current_holderId <> :current_holderId", {
        current_holderId: posMaster.current_holderId,
      })
      .andWhere("current_holders.orgChild1Id  IS NULL")
      .getMany();

    let _caregiver: any;
    let caregiver: any;
    let _commander: any;
    let commander: any;
    let _chairman: any;
    let chairman: any;
    if (posMaster) {
      if (orgChild4) {
        if (findChild4) {
          _caregiver = findChild4;
          _commander = findChild3;
          _chairman = findChild2;
        } else if (findChild3) {
          _caregiver = findChild3;
          _commander = findChild2;
          _chairman = findChild1;
        } else if (findChild2) {
          _caregiver = findChild2;
          _commander = findChild1;
          _chairman = findRoot;
        } else if (findChild1) {
          _caregiver = findChild1;
          _commander = findRoot;
          _chairman = findRoot;
        } else if (findRoot) {
          _caregiver = findRoot;
          _commander = findRoot;
          _chairman = findRoot;
        }
      } else if (orgChild3) {
        if (findChild3) {
          _caregiver = findChild3;
          _commander = findChild2;
          _chairman = findChild1;
        } else if (findChild2) {
          _caregiver = findChild2;
          _commander = findChild1;
          _chairman = findRoot;
        } else if (findChild1) {
          _caregiver = findChild1;
          _commander = findRoot;
          _chairman = findRoot;
        } else if (findRoot) {
          _caregiver = findRoot;
          _commander = findRoot;
          _chairman = findRoot;
        }
      } else if (orgChild2) {
        if (findChild2) {
          _caregiver = findChild2;
          _commander = findChild1;
          _chairman = findRoot;
        } else if (findChild1) {
          _caregiver = findChild1;
          _commander = findRoot;
          _chairman = findRoot;
        } else if (findRoot) {
          _caregiver = findRoot;
          _commander = findRoot;
          _chairman = findRoot;
        }
      } else if (orgChild1) {
        if (findChild1) {
          _caregiver = findChild1;
          _commander = findRoot;
          _chairman = findRoot;
        } else if (findRoot) {
          _caregiver = findRoot;
          _commander = findRoot;
          _chairman = findRoot;
        }
      } else if (orgRoot) {
        if (findRoot) {
          _caregiver = findRoot;
          _commander = findRoot;
          _chairman = findRoot;
        }
      }
      caregiver = _caregiver.map((_data: any) => ({
        id: _data.id,
        prefix: _data.prefix,
        firstName: _data.firstName,
        lastName: _data.lastName,
        citizenId: _data.citizenId,
        position: _data.position,
        posLevel: _data.posLevel == null ? null : _data.posLevel.posLevelName,
        posType: _data.posType == null ? null : _data.posType.posTypeName,
        isDirector: true,
      }));
      commander = _commander.map((_data: any) => ({
        id: _data.id,
        prefix: _data.prefix,
        firstName: _data.firstName,
        lastName: _data.lastName,
        citizenId: _data.citizenId,
        position: _data.position,
        posLevel: _data.posLevel == null ? null : _data.posLevel.posLevelName,
        posType: _data.posType == null ? null : _data.posType.posTypeName,
        isDirector: true,
      }));
      chairman = _chairman.map((_data: any) => ({
        id: _data.id,
        prefix: _data.prefix,
        firstName: _data.firstName,
        lastName: _data.lastName,
        citizenId: _data.citizenId,
        position: _data.position,
        posLevel: _data.posLevel == null ? null : _data.posLevel.posLevelName,
        posType: _data.posType == null ? null : _data.posType.posTypeName,
        isDirector: true,
      }));
    }

    return new HttpSuccess({ caregiver, commander, chairman });
  }
  /**
   *
   *
   */
  @Post("commander-director-act")
  async getProfileCommanderDirectorAct(
    @Request() request: RequestWithUser,
    @Body() body: { isDirector: boolean; keyword: string; page: number; pageSize: number },
  ) {
    const posMaster = await this.posMasterRepo.findOne({
      where: {
        current_holder: { keycloak: request.user.sub },
        orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true },
      },
    });
    if (!posMaster) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลการครองตำแหน่ง");

    let condition: any = {
      orgRootId: posMaster.orgRootId || "",
    };
    if (body.isDirector == true) {
      condition = {
        orgRootId: posMaster.orgRootId || "",
        isDirector: true,
      };
    }
    const [lists, total] = await AppDataSource.getRepository(viewDirectorActing)
      .createQueryBuilder("viewDirectorActing")
      .andWhere(condition)
      .andWhere(
        new Brackets((qb) => {
          qb.orWhere(
            body.keyword != null && body.keyword != ""
              ? "CONCAT(viewDirectorActing.prefix,viewDirectorActing.firstName,' ',viewDirectorActing.lastName) LIKE :keyword"
              : "1=1",
            {
              keyword: `%${body.keyword}%`,
            },
          )
            .orWhere(
              body.keyword != null && body.keyword != ""
                ? "viewDirectorActing.citizenId LIKE :keyword"
                : "1=1",
              {
                keyword: `%${body.keyword}%`,
              },
            )
            .orWhere(
              body.keyword != null && body.keyword != ""
                ? "viewDirectorActing.position LIKE :keyword"
                : "1=1",
              {
                keyword: `%${body.keyword}%`,
              },
            )
            .orWhere(
              body.keyword != null && body.keyword != ""
                ? "viewDirectorActing.posLevel LIKE :keyword"
                : "1=1",
              {
                keyword: `%${body.keyword}%`,
              },
            )
            .orWhere(
              body.keyword != null && body.keyword != ""
                ? "viewDirectorActing.posType LIKE :keyword"
                : "1=1",
              {
                keyword: `%${body.keyword}%`,
              },
            )
            .orWhere(
              body.keyword != null && body.keyword != ""
                ? "viewDirectorActing.actFullName LIKE :keyword"
                : "1=1",
              {
                keyword: `%${body.keyword}%`,
              },
            );
        }),
      )
      .skip((body.page - 1) * body.pageSize)
      .take(body.pageSize)
      .getManyAndCount();
    return new HttpSuccess({ data: lists, total });
  }
  /**
   *
   *
   */
  @Post("commander-director")
  async getProfileCommanderDirector(
    @Request() request: RequestWithUser,
    @Body()
    body: {
      isAct: boolean;
      isDirector: boolean;
      keyword: string;
      page: number;
      pageSize: number;
    },
  ) {
    if (body.isAct == true) {
      const posMaster = await this.posMasterRepo.findOne({
        where: {
          current_holder: { keycloak: request.user.sub },
          orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true },
        },
      });
      if (!posMaster) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลการครองตำแหน่ง");

      let condition: any = {
        orgRootId: posMaster.orgRootId || "",
      };
      //   if (body.isDirector == true) {
      condition = {
        orgRootId: posMaster.orgRootId || "",
        isDirector: true,
      };
      //   }
      const [lists, total] = await AppDataSource.getRepository(viewDirectorActing)
        .createQueryBuilder("viewDirectorActing")
        .andWhere(condition)
        .andWhere(
          new Brackets((qb) => {
            qb.orWhere(
              body.keyword != null && body.keyword != ""
                ? "CONCAT(viewDirectorActing.prefix,viewDirectorActing.firstName,' ',viewDirectorActing.lastName) LIKE :keyword"
                : "1=1",
              {
                keyword: `%${body.keyword}%`,
              },
            )
              .orWhere(
                body.keyword != null && body.keyword != ""
                  ? "viewDirectorActing.citizenId LIKE :keyword"
                  : "1=1",
                {
                  keyword: `%${body.keyword}%`,
                },
              )
              .orWhere(
                body.keyword != null && body.keyword != ""
                  ? "viewDirectorActing.position LIKE :keyword"
                  : "1=1",
                {
                  keyword: `%${body.keyword}%`,
                },
              )
              .orWhere(
                body.keyword != null && body.keyword != ""
                  ? "viewDirectorActing.posLevel LIKE :keyword"
                  : "1=1",
                {
                  keyword: `%${body.keyword}%`,
                },
              )
              .orWhere(
                body.keyword != null && body.keyword != ""
                  ? "viewDirectorActing.posType LIKE :keyword"
                  : "1=1",
                {
                  keyword: `%${body.keyword}%`,
                },
              )
              .orWhere(
                body.keyword != null && body.keyword != ""
                  ? "viewDirectorActing.actFullName LIKE :keyword"
                  : "1=1",
                {
                  keyword: `%${body.keyword}%`,
                },
              );
          }),
        )
        .skip((body.page - 1) * body.pageSize)
        .take(body.pageSize)
        .getManyAndCount();
      return new HttpSuccess({ data: lists, total });
    } else {
      const posMaster = await this.posMasterRepo.findOne({
        where: {
          current_holder: { keycloak: request.user.sub },
          orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true },
        },
      });
      if (!posMaster) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลการครองตำแหน่ง");

      let condition: any = {
        orgRootId: posMaster.orgRootId || "",
      };
      if (body.isDirector == true) {
        condition = {
          orgRootId: posMaster.orgRootId || "",
          isDirector: true,
        };
      }
      const [lists, total] = await AppDataSource.getRepository(viewDirector)
        .createQueryBuilder("viewDirector")
        .andWhere(condition)
        .andWhere(
          new Brackets((qb) => {
            qb.orWhere(
              body.keyword != null && body.keyword != ""
                ? "CONCAT(viewDirector.prefix,viewDirector.firstName,' ',viewDirector.lastName) LIKE :keyword"
                : "1=1",
              {
                keyword: `%${body.keyword}%`,
              },
            )
              .orWhere(
                body.keyword != null && body.keyword != ""
                  ? "viewDirector.citizenId LIKE :keyword"
                  : "1=1",
                {
                  keyword: `%${body.keyword}%`,
                },
              )
              .orWhere(
                body.keyword != null && body.keyword != ""
                  ? "viewDirector.position LIKE :keyword"
                  : "1=1",
                {
                  keyword: `%${body.keyword}%`,
                },
              )
              .orWhere(
                body.keyword != null && body.keyword != ""
                  ? "viewDirector.posLevel LIKE :keyword"
                  : "1=1",
                {
                  keyword: `%${body.keyword}%`,
                },
              )
              .orWhere(
                body.keyword != null && body.keyword != ""
                  ? "viewDirector.posType LIKE :keyword"
                  : "1=1",
                {
                  keyword: `%${body.keyword}%`,
                },
              );
          }),
        )
        .skip((body.page - 1) * body.pageSize)
        .take(body.pageSize)
        .getManyAndCount();
      return new HttpSuccess({ data: lists, total });
    }
  }

  /**
   * API เลือกผู้ประเมินสำหรับ User (ADMIN)
   *
   * @summary เลือกผู้ประเมินสำหรับ User  (ADMIN)
   *
   * @param {string} profileId  Id ทะเบียนประวัติ User
   */
  @Get("commander/{profileId}")
  async getProfileCommanderUser(@Request() request: RequestWithUser, @Path() profileId: string) {
    //await new permission().PermissionOrgUserGet(request, "SYS_REGISTRY_OFFICER", profileId); //ไม่แน่ใจOFFปิดไว้ก่อน
    const profile = await this.profileRepo.findOne({
      where: { id: profileId },
    });

    const posMaster = await this.posMasterRepo.findOne({
      where: { current_holderId: profile?.id },
    });
    if (!posMaster) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลการครองตำแหน่ง");
    const orgRoot = posMaster.orgRootId;
    const orgChild1 = posMaster.orgChild1Id;
    const orgChild2 = posMaster.orgChild2Id;
    const orgChild3 = posMaster.orgChild3Id;
    const orgChild4 = posMaster.orgChild4Id;

    const findChild4 = await this.profileRepo
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.current_holders", "current_holders")
      .leftJoinAndSelect("profile.posLevel", "posLevel")
      .leftJoinAndSelect("profile.posType", "posType")
      .andWhere({ keycloak: Not(IsNull()) })
      .where("current_holders.current_holderId IS NOT NULL")
      .andWhere("current_holders.orgRootId = :orgRootId", { orgRootId: orgRoot })
      .andWhere("current_holders.current_holderId <> :current_holderId", {
        current_holderId: posMaster.current_holderId,
      })
      .getMany();
    const findChild3 = await this.profileRepo
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.current_holders", "current_holders")
      .leftJoinAndSelect("profile.posLevel", "posLevel")
      .leftJoinAndSelect("profile.posType", "posType")
      .andWhere({ keycloak: Not(IsNull()) })
      .where("current_holders.current_holderId IS NOT NULL")
      .andWhere("current_holders.orgRootId = :orgRootId", { orgRootId: orgRoot })
      .andWhere("current_holders.current_holderId <> :current_holderId", {
        current_holderId: posMaster.current_holderId,
      })
      .andWhere("current_holders.orgChild3Id = :orgChild3Id", { orgChild3Id: orgChild3 })
      .andWhere("current_holders.orgChild4Id IS NULL")
      .getMany();
    const findChild2 = await this.profileRepo
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.current_holders", "current_holders")
      .leftJoinAndSelect("profile.posLevel", "posLevel")
      .leftJoinAndSelect("profile.posType", "posType")
      .andWhere({ keycloak: Not(IsNull()) })
      .where("current_holders.current_holderId IS NOT NULL")
      .andWhere("current_holders.orgRootId = :orgRootId", { orgRootId: orgRoot })
      .andWhere("current_holders.current_holderId <> :current_holderId", {
        current_holderId: posMaster.current_holderId,
      })
      .andWhere("current_holders.orgChild2Id = :orgChild2Id", { orgChild2Id: orgChild2 })
      .andWhere("current_holders.orgChild3Id IS NULL")
      .getMany();
    const findChild1 = await this.profileRepo
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.current_holders", "current_holders")
      .leftJoinAndSelect("profile.posLevel", "posLevel")
      .leftJoinAndSelect("profile.posType", "posType")
      .andWhere({ keycloak: Not(IsNull()) })
      .where("current_holders.current_holderId IS NOT NULL")
      .andWhere("current_holders.orgRootId = :orgRootId", { orgRootId: orgRoot })
      .andWhere("current_holders.current_holderId <> :current_holderId", {
        current_holderId: posMaster.current_holderId,
      })
      .andWhere("current_holders.orgChild1Id = :orgChild1Id", { orgChild1Id: orgChild1 })
      .andWhere("current_holders.orgChild2Id IS NULL")
      .getMany();
    const findRoot = await this.profileRepo
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.current_holders", "current_holders")
      .leftJoinAndSelect("profile.posLevel", "posLevel")
      .leftJoinAndSelect("profile.posType", "posType")
      .andWhere({ keycloak: Not(IsNull()) })
      .where("current_holders.current_holderId IS NOT NULL")
      .andWhere("current_holders.orgRootId = :orgRootId", { orgRootId: orgRoot })
      .andWhere("current_holders.current_holderId <> :current_holderId", {
        current_holderId: posMaster.current_holderId,
      })
      .andWhere("current_holders.orgChild1Id  IS NULL")
      .getMany();

    let _caregiver: any;
    let caregiver: any;
    let _commander: any;
    let commander: any;
    let _chairman: any;
    let chairman: any;
    if (posMaster) {
      if (orgChild4) {
        if (findChild4) {
          _caregiver = findChild4;
          _commander = findChild3;
          _chairman = findChild2;
        } else if (findChild3) {
          _caregiver = findChild3;
          _commander = findChild2;
          _chairman = findChild1;
        } else if (findChild2) {
          _caregiver = findChild2;
          _commander = findChild1;
          _chairman = findRoot;
        } else if (findChild1) {
          _caregiver = findChild1;
          _commander = findRoot;
          _chairman = findRoot;
        } else if (findRoot) {
          _caregiver = findRoot;
          _commander = findRoot;
          _chairman = findRoot;
        }
      } else if (orgChild3) {
        if (findChild3) {
          _caregiver = findChild3;
          _commander = findChild2;
          _chairman = findChild1;
        } else if (findChild2) {
          _caregiver = findChild2;
          _commander = findChild1;
          _chairman = findRoot;
        } else if (findChild1) {
          _caregiver = findChild1;
          _commander = findRoot;
          _chairman = findRoot;
        } else if (findRoot) {
          _caregiver = findRoot;
          _commander = findRoot;
          _chairman = findRoot;
        }
      } else if (orgChild2) {
        if (findChild2) {
          _caregiver = findChild2;
          _commander = findChild1;
          _chairman = findRoot;
        } else if (findChild1) {
          _caregiver = findChild1;
          _commander = findRoot;
          _chairman = findRoot;
        } else if (findRoot) {
          _caregiver = findRoot;
          _commander = findRoot;
          _chairman = findRoot;
        }
      } else if (orgChild1) {
        if (findChild1) {
          _caregiver = findChild1;
          _commander = findRoot;
          _chairman = findRoot;
        } else if (findRoot) {
          _caregiver = findRoot;
          _commander = findRoot;
          _chairman = findRoot;
        }
      } else if (orgRoot) {
        if (findRoot) {
          _caregiver = findRoot;
          _commander = findRoot;
          _chairman = findRoot;
        }
      }
      caregiver = _caregiver.map((_data: any) => ({
        id: _data.id,
        prefix: _data.prefix,
        firstName: _data.firstName,
        lastName: _data.lastName,
        citizenId: _data.citizenId,
        position: _data.position,
        posLevel: _data.posLevel == null ? null : _data.posLevel.posLevelName,
        posType: _data.posType == null ? null : _data.posType.posTypeName,
        isDirector: true,
      }));
      commander = _commander.map((_data: any) => ({
        id: _data.id,
        prefix: _data.prefix,
        firstName: _data.firstName,
        lastName: _data.lastName,
        citizenId: _data.citizenId,
        position: _data.position,
        posLevel: _data.posLevel == null ? null : _data.posLevel.posLevelName,
        posType: _data.posType == null ? null : _data.posType.posTypeName,
        isDirector: true,
      }));
      chairman = _chairman.map((_data: any) => ({
        id: _data.id,
        prefix: _data.prefix,
        firstName: _data.firstName,
        lastName: _data.lastName,
        citizenId: _data.citizenId,
        position: _data.position,
        posLevel: _data.posLevel == null ? null : _data.posLevel.posLevelName,
        posType: _data.posType == null ? null : _data.posType.posTypeName,
        isDirector: true,
      }));
    }

    return new HttpSuccess({ caregiver, commander, chairman });
  }

  /**
   * API สร้างทะเบียนประวัติ
   *
   * @summary ORG_065 - สร้างทะเบียนประวัติ (ADMIN) #70
   *
   */
  @Post()
  async createProfile(@Request() request: RequestWithUser, @Body() body: CreateProfile) {
    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.length !== 13) {
      throw new HttpError(
        HttpStatus.NOT_FOUND,
        "กรุณากรอกข้อมูลรหัสบัตรประจำตัวประชาชนให้ครบ 13 หลัก",
      );
    }

    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;
      let chkDigit = 11 - calStp2;
      if (chkDigit === 10) {
        chkDigit = 1;
      } else if (chkDigit === 11) {
        chkDigit = chkDigit % 10;
      }
      // else if(chkDigit === 11){
      //   chkDigit = cal % 10;
      // }

      if (citizenIdDigits[12] !== chkDigit) {
        throw new HttpError(HttpStatus.NOT_FOUND, "ข้อมูลรหัสบัตรประจำตัวประชาชนไม่ถูกต้อง");
      }
    }

    // if (body.citizenId && (await this.profileRepo.findOneBy({ citizenId: body.citizenId }))) {
    //   throw new HttpError(HttpStatus.NOT_FOUND, "ข้อมูลรหัสบัตรประจำตัวประชาชนนี้มีอยู่ในระบบแล้ว");
    // }

    const profile = Object.assign(new Profile(), body);
    profile.isProbation = false;
    profile.isLeave = false;
    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);
    await this.profileRepo.save(profile);

    return new HttpSuccess();
  }

  /**
   * API สร้างทะเบียนประวัติใหม่
   *
   * @summary ORG_065 - สร้างทะเบียนประวัติใหม่ (ADMIN) #XXX
   *
   */
  @Post("all")
  async createProfileAll(
    @Request() request: RequestWithUser,
    @Body() body: CreateProfileAllFields,
  ) {
    const profileExist = await this.profileRepo.findOneBy({ citizenId: body.citizenId });
    if (profileExist) {
      return new HttpSuccess(profileExist.id);
    }

    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 profile: Profile = Object.assign(new Profile(), body);
    const _null: any = null;
    profile.dateRetire = body.birthDate == null ? _null : calculateRetireDate(body.birthDate);
    profile.dateRetireLaw = body.birthDate == null ? _null : calculateRetireLaw(body.birthDate);
    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();
    await this.profileRepo.save(profile);
    return new HttpSuccess(profile.id);
  }

  /**
   * API สร้างทะเบียนประวัติใหม่
   *
   * @summary ORG_065 - สร้างทะเบียนประวัติใหม่ (ADMIN) #XXX
   *
   */
  @Post("allv2")
  async createProfileAllV2(
    @Request() request: RequestWithUser,
    @Body() body: CreateProfileAllFields,
  ) {
    const profileExist = await this.profileRepo.findOneBy({ citizenId: body.citizenId });
    if (profileExist) {
      return new HttpSuccess(profileExist.id);
    }

    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 profile: Profile = Object.assign(new Profile(), body);
    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();
    await this.profileRepo.save(profile);
    return new HttpSuccess(profile.id);
  }

  /**
   * API ออกคำสั่ง คำสั่งให้ข้าราชการที่มีผลการทดลองปฏิบัติหน้าที่ราชการไม่ต่ำกว่ามาตรฐานที่กำหนดรับราชการต่อไป
   *
   * @summary API ออกคำสั่ง คำสั่งให้ข้าราชการที่มีผลการทดลองปฏิบัติหน้าที่ราชการไม่ต่ำกว่ามาตรฐานที่กำหนดรับราชการต่อไป (ADMIN)
   *
   */
  @Post("command11/{profileId}")
  async ExecuteCommand11Async(
    @Request() req: RequestWithUser,
    @Body()
    body: {
      profileId: string;
      date: Date | null;
      refCommandNo: string | null;
      salaryRef: string | null;
    },
  ) {
    const profile = await this.profileRepo.findOne({
      relations: ["profileSalary"],
      where: { id: body.profileId },
      order: {
        profileSalary: {
          order: "DESC",
        },
      },
    });
    if (!profile) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์");
    }
    // const posType = await this.posTypeRepo.findOneBy({ id: String(profile.posTypeId) })
    // const posLevel = await this.posLevelRepo.findOneBy({ id: String(profile.posLevelId) })
    const orgRevision = await this.orgRevisionRepo.findOne({
      where: {
        orgRevisionIsCurrent: true,
        orgRevisionIsDraft: false,
      },
    });
    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)?.posMasterNo}`
          : 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)?.posMasterNo}`
            : 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)?.posMasterNo}`
              : 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)?.posMasterNo}`
                : 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}${profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.posMasterNo}`
                  : null;
    let position =
      profile.current_holders
        .filter((x) => x.orgRevisionId == orgRevision?.id)[0]
        ?.positions?.filter((pos) => pos.positionIsSelected === true)[0] ?? null;
    if (profile.isProbation != false) {
      profile.isProbation = false;
      profile.lastUpdateUserId = req.user.sub;
      profile.lastUpdateFullName = req.user.name;
      profile.lastUpdatedAt = new Date();
      const profileSalary: ProfileSalary = Object.assign(new ProfileSalary(), {
        profileId: body.profileId,
        date: body.date,
        refCommandNo: body.refCommandNo,
        templateDoc: body.salaryRef,
        //profile.position,
        position: profile.position,
        positionType: profile.posType.posTypeName,
        positionLevel: profile.posLevel.posLevelName,
        posNo: shortName ? shortName : "-",
        positionLine: position?.positionField ?? "-",
        positionPathSide: position?.positionArea ?? "-",
        positionExecutive: position?.posExecutive?.posExecutiveName ?? "-",
        amount: profile.amount,
        positionSalaryAmount: profile.positionSalaryAmount,
        mouthSalaryAmount: profile.mouthSalaryAmount,
        order:
          profile.profileSalary.length >= 0
            ? profile.profileSalary.length > 0
              ? profile.profileSalary[0].order + 1
              : 1
            : null,
        createdUserId: req.user.sub,
        createdFullName: req.user.name,
        lastUpdateUserId: req.user.sub,
        lastUpdateFullName: req.user.name,
        createdAt: new Date(),
        lastUpdatedAt: new Date(),
      });
      await Promise.all([this.salaryRepository.save(profileSalary)]);
    }
    return new HttpSuccess();
  }

  /**
   * API ออกคำสั่ง คำสั่งให้ข้าราชการออกจากราชการเพราะผลการทดลองปฏิบัติหน้าที่ราชการต่ำกว่ามาตรฐานที่กำหนด
   *
   * @summary API ออกคำสั่ง คำสั่งให้ข้าราชการออกจากราชการเพราะผลการทดลองปฏิบัติหน้าที่ราชการต่ำกว่ามาตรฐานที่กำหนด (ADMIN)
   *
   */
  @Post("command12/{profileId}")
  async ExecuteCommand12Async(
    @Request() req: RequestWithUser,
    @Body()
    body: {
      profileId: string;
      date: Date | null;
      refCommandNo: string | null;
      salaryRef: string | null;
    },
  ) {
    const profile = await this.profileRepo.findOne({
      relations: ["profileSalary", "posType", "posLevel"],
      where: { id: body.profileId },
      order: {
        profileSalary: {
          order: "DESC",
        },
      },
    });
    if (!profile) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์");
    }
    const _profile = await this.profileRepo.findOne({
      where: { id: body.profileId },
    });
    if (!_profile) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์");
    }
    let dateLeave_: any = body.date;
    _profile.isLeave = true;
    _profile.leaveReason =
      "คำสั่งให้ข้าราชการออกจากราชการเพราะผลการทดลองปฏิบัติหน้าที่ราชการต่ำกว่ามาตรฐานที่กำหนด";
    _profile.dateLeave = dateLeave_;
    _profile.lastUpdateUserId = req.user.sub;
    _profile.lastUpdateFullName = req.user.name;
    _profile.lastUpdatedAt = new Date();

    const orgRevision = await this.orgRevisionRepo.findOne({
      where: {
        orgRevisionIsCurrent: true,
        orgRevisionIsDraft: false,
      },
    });
    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)?.posMasterNo}`
          : 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)?.posMasterNo}`
            : 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)?.posMasterNo}`
              : 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)?.posMasterNo}`
                : 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}${profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.posMasterNo}`
                  : null;
    let position =
      profile.current_holders
        .filter((x) => x.orgRevisionId == orgRevision?.id)[0]
        ?.positions?.filter((pos) => pos.positionIsSelected === true)[0] ?? null;
    const profileSalary: ProfileSalary = Object.assign(new ProfileSalary(), {
      profileId: body.profileId,
      date: body.date,
      refCommandNo: body.refCommandNo,
      templateDoc: body.salaryRef,
      position: profile.position,
      positionType: profile.posType.posTypeName,
      positionLevel: profile.posLevel.posLevelName,
      posNo: shortName ? shortName : "-",
      positionLine: position?.positionField ?? "-",
      positionPathSide: position?.positionArea ?? "-",
      positionExecutive: position?.posExecutive?.posExecutiveName ?? "-",
      amount: profile.amount,
      positionSalaryAmount: profile.positionSalaryAmount,
      mouthSalaryAmount: profile.mouthSalaryAmount,
      order:
        profile.profileSalary.length >= 0
          ? profile.profileSalary.length > 0
            ? profile.profileSalary[0].order + 1
            : 1
          : null,
      createdUserId: req.user.sub,
      createdFullName: req.user.name,
      lastUpdateUserId: req.user.sub,
      lastUpdateFullName: req.user.name,
      createdAt: new Date(),
      lastUpdatedAt: new Date(),
    });
    await removeProfileInOrganize(profile.id, "OFFICER");
    await Promise.all([this.profileRepo.save(_profile), this.salaryRepository.save(profileSalary)]);

    return new HttpSuccess();
  }

  /**
   * API ออกคำสั่ง คำสั่งปลดออกจากราชการ
   *
   * @summary API ออกคำสั่ง คำสั่งปลดออกจากราชการ (ADMIN)
   *
   */
  @Post("command19/{profileId}")
  async ExecuteCommand19Async(
    @Request() req: RequestWithUser,
    @Body()
    body: {
      profileId: string;
      date: Date | null;
      refCommandNo: string | null;
      salaryRef: string | null;
    },
  ) {
    const profile = await this.profileRepo.findOne({
      relations: ["profileSalary", "posType", "posLevel"],
      where: { id: body.profileId },
      order: {
        profileSalary: {
          order: "DESC",
        },
      },
    });
    if (!profile) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์");
    }
    const _profile = await this.profileRepo.findOne({
      where: { id: body.profileId },
    });
    if (!_profile) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์");
    }
    let dateLeave_: any = body.date;
    _profile.isLeave = true;
    _profile.leaveReason = "ได้รับโทษทางวินัย ปลดออกจากราชการ";
    _profile.dateLeave = dateLeave_;
    _profile.lastUpdateUserId = req.user.sub;
    _profile.lastUpdateFullName = req.user.name;
    _profile.lastUpdatedAt = new Date();

    const orgRevision = await this.orgRevisionRepo.findOne({
      where: {
        orgRevisionIsCurrent: true,
        orgRevisionIsDraft: false,
      },
    });
    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)?.posMasterNo}`
          : 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)?.posMasterNo}`
            : 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)?.posMasterNo}`
              : 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)?.posMasterNo}`
                : 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}${profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.posMasterNo}`
                  : null;
    let position =
      profile.current_holders
        .filter((x) => x.orgRevisionId == orgRevision?.id)[0]
        ?.positions?.filter((pos) => pos.positionIsSelected === true)[0] ?? null;
    const profileSalary: ProfileSalary = Object.assign(new ProfileSalary(), {
      profileId: body.profileId,
      date: body.date,
      refCommandNo: body.refCommandNo,
      templateDoc: body.salaryRef,
      position: profile.position,
      positionType: profile.posType.posTypeName,
      positionLevel: profile.posLevel.posLevelName,
      posNo: shortName ? shortName : "-",
      positionLine: position?.positionField ?? "-",
      positionPathSide: position?.positionArea ?? "-",
      positionExecutive: position?.posExecutive?.posExecutiveName ?? "-",
      amount: profile.amount,
      positionSalaryAmount: profile.positionSalaryAmount,
      mouthSalaryAmount: profile.mouthSalaryAmount,
      order:
        profile.profileSalary.length >= 0
          ? profile.profileSalary.length > 0
            ? profile.profileSalary[0].order + 1
            : 1
          : null,
      createdUserId: req.user.sub,
      createdFullName: req.user.name,
      lastUpdateUserId: req.user.sub,
      lastUpdateFullName: req.user.name,
      createdAt: new Date(),
      lastUpdatedAt: new Date(),
    });
    await removeProfileInOrganize(profile.id, "OFFICER");
    await Promise.all([this.profileRepo.save(_profile), this.salaryRepository.save(profileSalary)]);

    return new HttpSuccess();
  }

  /**
   * API ออกคำสั่ง คำสั่งไล่ออกจากราชการ
   *
   * @summary API ออกคำสั่ง คำสั่งไล่ออกจากราชการ (ADMIN)
   *
   */
  @Post("command20/{profileId}")
  async ExecuteCommand20Async(
    @Request() req: RequestWithUser,
    @Body()
    body: {
      profileId: string;
      date: Date | null;
      refCommandNo: string | null;
      salaryRef: string | null;
    },
  ) {
    const profile = await this.profileRepo.findOne({
      relations: ["profileSalary", "posType", "posLevel"],
      where: { id: body.profileId },
      order: {
        profileSalary: {
          order: "DESC",
        },
      },
    });
    if (!profile) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์");
    }
    const _profile = await this.profileRepo.findOne({
      where: { id: body.profileId },
    });
    if (!_profile) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์");
    }
    let dateLeave_: any = body.date;
    _profile.isLeave = true;
    _profile.leaveReason = "ได้รับโทษทางวินัย ไล่ออกจากราชการ";
    _profile.dateLeave = dateLeave_;
    _profile.lastUpdateUserId = req.user.sub;
    _profile.lastUpdateFullName = req.user.name;
    _profile.lastUpdatedAt = new Date();

    const orgRevision = await this.orgRevisionRepo.findOne({
      where: {
        orgRevisionIsCurrent: true,
        orgRevisionIsDraft: false,
      },
    });
    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)?.posMasterNo}`
          : 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)?.posMasterNo}`
            : 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)?.posMasterNo}`
              : 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)?.posMasterNo}`
                : 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}${profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.posMasterNo}`
                  : null;
    let position =
      profile.current_holders
        .filter((x) => x.orgRevisionId == orgRevision?.id)[0]
        ?.positions?.filter((pos) => pos.positionIsSelected === true)[0] ?? null;
    const profileSalary: ProfileSalary = Object.assign(new ProfileSalary(), {
      profileId: body.profileId,
      date: body.date,
      refCommandNo: body.refCommandNo,
      templateDoc: body.salaryRef,
      position: profile.position,
      positionType: profile.posType.posTypeName,
      positionLevel: profile.posLevel.posLevelName,
      posNo: shortName ? shortName : "-",
      positionLine: position?.positionField ?? "-",
      positionPathSide: position?.positionArea ?? "-",
      positionExecutive: position?.posExecutive?.posExecutiveName ?? "-",
      amount: profile.amount,
      positionSalaryAmount: profile.positionSalaryAmount,
      mouthSalaryAmount: profile.mouthSalaryAmount,
      order:
        profile.profileSalary.length >= 0
          ? profile.profileSalary.length > 0
            ? profile.profileSalary[0].order + 1
            : 1
          : null,
      createdUserId: req.user.sub,
      createdFullName: req.user.name,
      lastUpdateUserId: req.user.sub,
      lastUpdateFullName: req.user.name,
      createdAt: new Date(),
      lastUpdatedAt: new Date(),
    });
    // //เพิ่มวินัย
    // const profileDiscipline: ProfileDiscipline = Object.assign(new ProfileDiscipline(), {
    //   date: body.date,
    //   profileId: body.profileId,
    //   refCommandNo: body.refCommandNo,
    //   createdUserId: req.user.sub,
    //   createdFullName: req.user.name,
    //   lastUpdateUserId: req.user.sub,
    //         lastUpdateFullName: req.user.name,
    //   createdAt: new Date(),
    //   lastUpdatedAt: new Date(),
    // });
    await removeProfileInOrganize(profile.id, "OFFICER");
    await Promise.all([
      this.profileRepo.save(_profile),
      this.salaryRepository.save(profileSalary),
      //   this.profileDisciplineRepo.save(profileDiscipline)
    ]);

    return new HttpSuccess();
  }

  /**
   * API ออกคำสั่ง คำสั่งพักจากราชการ
   *
   * @summary API ออกคำสั่ง คำสั่งพักจากราชการ (ADMIN)
   *
   */
  @Post("command25/{profileId}")
  async ExecuteCommand25Async(
    @Request() req: RequestWithUser,
    @Body()
    body: {
      profileId: string;
      date: Date | null;
      refCommandNo: string | null;
      salaryRef: string | null;
    },
  ) {
    const profile = await this.profileRepo.findOne({
      relations: ["profileSalary", "posType", "posLevel"],
      where: { id: body.profileId },
      order: {
        profileSalary: {
          order: "DESC",
        },
      },
    });
    if (!profile) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์");
    }
    const _profile = await this.profileRepo.findOne({
      where: { id: body.profileId },
    });
    if (!_profile) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์");
    }
    let dateLeave_: any = body.date;
    _profile.isLeave = true;
    _profile.leaveReason = "ได้รับโทษทางวินัย พักจากราชการ";
    _profile.dateLeave = dateLeave_;
    _profile.lastUpdateUserId = req.user.sub;
    _profile.lastUpdateFullName = req.user.name;
    _profile.lastUpdatedAt = new Date();

    const orgRevision = await this.orgRevisionRepo.findOne({
      where: {
        orgRevisionIsCurrent: true,
        orgRevisionIsDraft: false,
      },
    });
    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)?.posMasterNo}`
          : 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)?.posMasterNo}`
            : 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)?.posMasterNo}`
              : 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)?.posMasterNo}`
                : 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}${profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.posMasterNo}`
                  : null;
    let position =
      profile.current_holders
        .filter((x) => x.orgRevisionId == orgRevision?.id)[0]
        ?.positions?.filter((pos) => pos.positionIsSelected === true)[0] ?? null;
    const profileSalary: ProfileSalary = Object.assign(new ProfileSalary(), {
      profileId: body.profileId,
      date: body.date,
      refCommandNo: body.refCommandNo,
      templateDoc: body.salaryRef,
      position: profile.position,
      positionType: profile.posType.posTypeName,
      positionLevel: profile.posLevel.posLevelName,
      posNo: shortName ? shortName : "-",
      positionLine: position?.positionField ?? "-",
      positionPathSide: position?.positionArea ?? "-",
      positionExecutive: position?.posExecutive?.posExecutiveName ?? "-",
      amount: profile.amount,
      positionSalaryAmount: profile.positionSalaryAmount,
      mouthSalaryAmount: profile.mouthSalaryAmount,
      order:
        profile.profileSalary.length >= 0
          ? profile.profileSalary.length > 0
            ? profile.profileSalary[0].order + 1
            : 1
          : null,
      createdUserId: req.user.sub,
      createdFullName: req.user.name,
      lastUpdateUserId: req.user.sub,
      lastUpdateFullName: req.user.name,
      createdAt: new Date(),
      lastUpdatedAt: new Date(),
    });
    await removeProfileInOrganize(profile.id, "OFFICER");
    await Promise.all([this.profileRepo.save(_profile), this.salaryRepository.save(profileSalary)]);

    return new HttpSuccess();
  }

  /**
   * API ออกคำสั่ง คำสั่งให้ออกจากราชการไว้ก่อน
   *
   * @summary API ออกคำสั่ง คำสั่งให้ออกจากราชการไว้ก่อน (ADMIN)
   *
   */
  @Post("command26/{profileId}")
  async ExecuteCommand26Async(
    @Request() req: RequestWithUser,
    @Body()
    body: {
      profileId: string;
      date: Date | null;
      refCommandNo: string | null;
      salaryRef: string | null;
    },
  ) {
    const profile = await this.profileRepo.findOne({
      relations: ["profileSalary", "posType", "posLevel"],
      where: { id: body.profileId },
      order: {
        profileSalary: {
          order: "DESC",
        },
      },
    });
    if (!profile) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์");
    }
    const _profile = await this.profileRepo.findOne({
      where: { id: body.profileId },
    });
    if (!_profile) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์");
    }
    let dateLeave_: any = body.date;
    _profile.isLeave = true;
    _profile.leaveReason = "ได้รับโทษทางวินัย ให้ออกจากราชการไว้ก่อน";
    _profile.dateLeave = dateLeave_;
    _profile.lastUpdateUserId = req.user.sub;
    _profile.lastUpdateFullName = req.user.name;

    const orgRevision = await this.orgRevisionRepo.findOne({
      where: {
        orgRevisionIsCurrent: true,
        orgRevisionIsDraft: false,
      },
    });
    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)?.posMasterNo}`
          : 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)?.posMasterNo}`
            : 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)?.posMasterNo}`
              : 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)?.posMasterNo}`
                : 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}${profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.posMasterNo}`
                  : null;
    let position =
      profile.current_holders
        .filter((x) => x.orgRevisionId == orgRevision?.id)[0]
        ?.positions?.filter((pos) => pos.positionIsSelected === true)[0] ?? null;
    const profileSalary: ProfileSalary = Object.assign(new ProfileSalary(), {
      profileId: body.profileId,
      date: body.date,
      refCommandNo: body.refCommandNo,
      templateDoc: body.salaryRef,
      position: profile.position,
      positionType: profile.posType.posTypeName,
      positionLevel: profile.posLevel.posLevelName,
      posNo: shortName ? shortName : "-",
      positionLine: position?.positionField ?? "-",
      positionPathSide: position?.positionArea ?? "-",
      positionExecutive: position?.posExecutive?.posExecutiveName ?? "-",
      amount: profile.amount,
      positionSalaryAmount: profile.positionSalaryAmount,
      mouthSalaryAmount: profile.mouthSalaryAmount,
      order:
        profile.profileSalary.length >= 0
          ? profile.profileSalary.length > 0
            ? profile.profileSalary[0].order + 1
            : 1
          : null,
      createdUserId: req.user.sub,
      createdFullName: req.user.name,
      lastUpdateUserId: req.user.sub,
      lastUpdateFullName: req.user.name,
      createdAt: new Date(),
      lastUpdatedAt: new Date(),
    });
    await removeProfileInOrganize(profile.id, "OFFICER");
    await Promise.all([this.profileRepo.save(_profile), this.salaryRepository.save(profileSalary)]);

    return new HttpSuccess();
  }

  /**
   * API ออกคำสั่ง คำสั่งลงโทษ ภาคทัณฑ์
   *
   * @summary API ออกคำสั่ง คำสั่งลงโทษ ภาคทัณฑ์ (ADMIN)
   *
   */
  @Post("command27/{profileId}")
  async ExecuteCommand27Async(
    @Request() req: RequestWithUser,
    @Body()
    body: {
      profileId: string;
      date: Date | null;
      refCommandNo: string | null;
      salaryRef: string | null;
    },
  ) {
    const profile = await this.profileRepo.findOne({
      relations: ["profileSalary", "posType", "posLevel"],
      where: { id: body.profileId },
      order: {
        profileSalary: {
          order: "DESC",
        },
      },
    });
    if (!profile) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์");
    }
    // let dateLeave_: any = body.date;
    // profile.isLeave = true;
    // profile.leaveReason = "ได้รับโทษทางวินัย ลงโทษ ภาคทัณฑ์";
    // profile.dateLeave = dateLeave_;
    // profile.lastUpdateUserId = req.user.sub;
    // profile.lastUpdateFullName = req.user.name;

    const orgRevision = await this.orgRevisionRepo.findOne({
      where: {
        orgRevisionIsCurrent: true,
        orgRevisionIsDraft: false,
      },
    });
    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)?.posMasterNo}`
          : 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)?.posMasterNo}`
            : 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)?.posMasterNo}`
              : 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)?.posMasterNo}`
                : 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}${profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.posMasterNo}`
                  : null;
    let position =
      profile.current_holders
        .filter((x) => x.orgRevisionId == orgRevision?.id)[0]
        ?.positions?.filter((pos) => pos.positionIsSelected === true)[0] ?? null;
    const profileSalary: ProfileSalary = Object.assign(new ProfileSalary(), {
      profileId: body.profileId,
      date: body.date,
      refCommandNo: body.refCommandNo,
      templateDoc: body.salaryRef,
      position: profile.position,
      positionType: profile.posType.posTypeName,
      positionLevel: profile.posLevel.posLevelName,
      posNo: shortName ? shortName : "-",
      positionLine: position?.positionField ?? "-",
      positionPathSide: position?.positionArea ?? "-",
      positionExecutive: position?.posExecutive?.posExecutiveName ?? "-",
      amount: profile.amount,
      positionSalaryAmount: profile.positionSalaryAmount,
      mouthSalaryAmount: profile.mouthSalaryAmount,
      order:
        profile.profileSalary.length >= 0
          ? profile.profileSalary.length > 0
            ? profile.profileSalary[0].order + 1
            : 1
          : null,
      createdUserId: req.user.sub,
      createdFullName: req.user.name,
      lastUpdateUserId: req.user.sub,
      lastUpdateFullName: req.user.name,
      createdAt: new Date(),
      lastUpdatedAt: new Date(),
    });
    await Promise.all([this.salaryRepository.save(profileSalary)]);

    return new HttpSuccess();
  }

  /**
   * API ออกคำสั่ง คำสั่งลงโทษ ตัดเงินเดือน
   *
   * @summary API ออกคำสั่ง คำสั่งลงโทษ ตัดเงินเดือน (ADMIN)
   *
   */
  @Post("command28/{profileId}")
  async ExecuteCommand28Async(
    @Request() req: RequestWithUser,
    @Body()
    body: {
      profileId: string;
      date: Date | null;
      refCommandNo: string | null;
      salaryRef: string | null;
    },
  ) {
    const profile = await this.profileRepo.findOne({
      relations: ["profileSalary", "posType", "posLevel"],
      where: { id: body.profileId },
      order: {
        profileSalary: {
          order: "DESC",
        },
      },
    });
    if (!profile) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์");
    }
    // let dateLeave_: any = body.date;
    // profile.isLeave = true;
    // profile.leaveReason = "ได้รับโทษทางวินัย ลงโทษ ตัดเงินเดือน";
    // profile.dateLeave = dateLeave_;
    // profile.lastUpdateUserId = req.user.sub;
    // profile.lastUpdateFullName = req.user.name;

    const orgRevision = await this.orgRevisionRepo.findOne({
      where: {
        orgRevisionIsCurrent: true,
        orgRevisionIsDraft: false,
      },
    });
    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)?.posMasterNo}`
          : 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)?.posMasterNo}`
            : 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)?.posMasterNo}`
              : 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)?.posMasterNo}`
                : 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}${profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.posMasterNo}`
                  : null;
    let position =
      profile.current_holders
        .filter((x) => x.orgRevisionId == orgRevision?.id)[0]
        ?.positions?.filter((pos) => pos.positionIsSelected === true)[0] ?? null;
    const profileSalary: ProfileSalary = Object.assign(new ProfileSalary(), {
      profileId: body.profileId,
      date: body.date,
      refCommandNo: body.refCommandNo,
      templateDoc: body.salaryRef,
      position: profile.position,
      positionType: profile.posType.posTypeName,
      positionLevel: profile.posLevel.posLevelName,
      posNo: shortName ? shortName : "-",
      positionLine: position?.positionField ?? "-",
      positionPathSide: position?.positionArea ?? "-",
      positionExecutive: position?.posExecutive?.posExecutiveName ?? "-",
      amount: profile.amount,
      positionSalaryAmount: profile.positionSalaryAmount,
      mouthSalaryAmount: profile.mouthSalaryAmount,
      order:
        profile.profileSalary.length >= 0
          ? profile.profileSalary.length > 0
            ? profile.profileSalary[0].order + 1
            : 1
          : null,
      createdUserId: req.user.sub,
      createdFullName: req.user.name,
      lastUpdateUserId: req.user.sub,
      lastUpdateFullName: req.user.name,
      createdAt: new Date(),
      lastUpdatedAt: new Date(),
    });
    await Promise.all([this.salaryRepository.save(profileSalary)]);

    return new HttpSuccess();
  }

  /**
   * API ออกคำสั่ง คำสั่งลงโทษ ลดขั้นเงินเดือน
   *
   * @summary API ออกคำสั่ง คำสั่งลงโทษ ลดขั้นเงินเดือน (ADMIN)
   *
   */
  @Post("command29/{profileId}")
  async ExecuteCommand29Async(
    @Request() req: RequestWithUser,
    @Body()
    body: {
      profileId: string;
      date: Date | null;
      refCommandNo: string | null;
      salaryRef: string | null;
    },
  ) {
    const profile = await this.profileRepo.findOne({
      relations: ["profileSalary", "posType", "posLevel"],
      where: { id: body.profileId },
      order: {
        profileSalary: {
          order: "DESC",
        },
      },
    });
    if (!profile) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์");
    }
    // let dateLeave_: any = body.date;
    // profile.isLeave = true;
    // profile.leaveReason = "ได้รับโทษทางวินัย ลงโทษ ลดขั้นเงินเดือน";
    // profile.dateLeave = dateLeave_;
    // profile.lastUpdateUserId = req.user.sub;
    // profile.lastUpdateFullName = req.user.name;

    const orgRevision = await this.orgRevisionRepo.findOne({
      where: {
        orgRevisionIsCurrent: true,
        orgRevisionIsDraft: false,
      },
    });
    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)?.posMasterNo}`
          : 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)?.posMasterNo}`
            : 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)?.posMasterNo}`
              : 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)?.posMasterNo}`
                : 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}${profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.posMasterNo}`
                  : null;

    let position =
      profile.current_holders
        .filter((x) => x.orgRevisionId == orgRevision?.id)[0]
        ?.positions?.filter((pos) => pos.positionIsSelected === true)[0] ?? null;
    const profileSalary: ProfileSalary = Object.assign(new ProfileSalary(), {
      profileId: body.profileId,
      date: body.date,
      refCommandNo: body.refCommandNo,
      templateDoc: body.salaryRef,
      position: profile.position,
      positionType: profile.posType.posTypeName,
      positionLevel: profile.posLevel.posLevelName,
      posNo: shortName ? shortName : "-",
      positionLine: position?.positionField ?? "-",
      positionPathSide: position?.positionArea ?? "-",
      positionExecutive: position?.posExecutive?.posExecutiveName ?? "-",
      amount: profile.amount,
      positionSalaryAmount: profile.positionSalaryAmount,
      mouthSalaryAmount: profile.mouthSalaryAmount,
      order:
        profile.profileSalary.length >= 0
          ? profile.profileSalary.length > 0
            ? profile.profileSalary[0].order + 1
            : 1
          : null,
      createdUserId: req.user.sub,
      createdFullName: req.user.name,
      lastUpdateUserId: req.user.sub,
      lastUpdateFullName: req.user.name,
      createdAt: new Date(),
      lastUpdatedAt: new Date(),
    });
    await Promise.all([this.salaryRepository.save(profileSalary)]);

    return new HttpSuccess();
  }

  /**
   * API ออกคำสั่ง คำสั่งเพิ่มโทษ
   *
   * @summary API ออกคำสั่ง คำสั่งเพิ่มโทษ (ADMIN)
   *
   */
  @Post("command30/{profileId}")
  async ExecuteCommand30Async(
    @Request() req: RequestWithUser,
    @Body()
    body: {
      profileId: string;
      date: Date | null;
      refCommandNo: string | null;
      salaryRef: string | null;
    },
  ) {
    const profile = await this.profileRepo.findOne({
      relations: ["profileSalary", "posType", "posLevel"],
      where: { id: body.profileId },
      order: {
        profileSalary: {
          order: "DESC",
        },
      },
    });
    if (!profile) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์");
    }
    // let dateLeave_: any = body.date;
    // profile.isLeave = true;
    // profile.leaveReason = "ได้รับโทษทางวินัย เพิ่มโทษ";
    // profile.dateLeave = dateLeave_;
    // profile.lastUpdateUserId = req.user.sub;
    // profile.lastUpdateFullName = req.user.name;

    const orgRevision = await this.orgRevisionRepo.findOne({
      where: {
        orgRevisionIsCurrent: true,
        orgRevisionIsDraft: false,
      },
    });
    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)?.posMasterNo}`
          : 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)?.posMasterNo}`
            : 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)?.posMasterNo}`
              : 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)?.posMasterNo}`
                : 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}${profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.posMasterNo}`
                  : null;
    let position =
      profile.current_holders
        .filter((x) => x.orgRevisionId == orgRevision?.id)[0]
        ?.positions?.filter((pos) => pos.positionIsSelected === true)[0] ?? null;
    const profileSalary: ProfileSalary = Object.assign(new ProfileSalary(), {
      profileId: body.profileId,
      date: body.date,
      refCommandNo: body.refCommandNo,
      templateDoc: body.salaryRef,
      position: profile.position,
      positionType: profile.posType.posTypeName,
      positionLevel: profile.posLevel.posLevelName,
      posNo: shortName ? shortName : "-",
      positionLine: position?.positionField ?? "-",
      positionPathSide: position?.positionArea ?? "-",
      positionExecutive: position?.posExecutive?.posExecutiveName ?? "-",
      amount: profile.amount,
      positionSalaryAmount: profile.positionSalaryAmount,
      mouthSalaryAmount: profile.mouthSalaryAmount,
      order:
        profile.profileSalary.length >= 0
          ? profile.profileSalary.length > 0
            ? profile.profileSalary[0].order + 1
            : 1
          : null,
      createdUserId: req.user.sub,
      createdFullName: req.user.name,
      lastUpdateUserId: req.user.sub,
      lastUpdateFullName: req.user.name,
      createdAt: new Date(),
      lastUpdatedAt: new Date(),
    });
    await Promise.all([this.salaryRepository.save(profileSalary)]);

    return new HttpSuccess();
  }

  /**
   * API ออกคำสั่ง คำสั่งงดโทษ
   *
   * @summary API ออกคำสั่ง คำสั่งงดโทษ (ADMIN)
   *
   */
  @Post("command31/{profileId}")
  async ExecuteCommand31Async(
    @Request() req: RequestWithUser,
    @Body()
    body: {
      profileId: string;
      date: Date | null;
      refCommandNo: string | null;
      salaryRef: string | null;
    },
  ) {
    const profile = await this.profileRepo.findOne({
      relations: ["profileSalary", "posType", "posLevel"],
      where: { id: body.profileId },
      order: {
        profileSalary: {
          order: "DESC",
        },
      },
    });
    if (!profile) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์");
    }
    // let dateLeave_: any = body.date;
    // profile.isLeave = true;
    // profile.leaveReason = "ได้รับโทษทางวินัย งดโทษ";
    // profile.dateLeave = dateLeave_;
    // profile.lastUpdateUserId = req.user.sub;
    // profile.lastUpdateFullName = req.user.name;

    const orgRevision = await this.orgRevisionRepo.findOne({
      where: {
        orgRevisionIsCurrent: true,
        orgRevisionIsDraft: false,
      },
    });
    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)?.posMasterNo}`
          : 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)?.posMasterNo}`
            : 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)?.posMasterNo}`
              : 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)?.posMasterNo}`
                : 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}${profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.posMasterNo}`
                  : null;

    let position =
      profile.current_holders
        .filter((x) => x.orgRevisionId == orgRevision?.id)[0]
        ?.positions?.filter((pos) => pos.positionIsSelected === true)[0] ?? null;
    const profileSalary: ProfileSalary = Object.assign(new ProfileSalary(), {
      profileId: body.profileId,
      date: body.date,
      refCommandNo: body.refCommandNo,
      templateDoc: body.salaryRef,
      position: profile.position,
      positionType: profile.posType.posTypeName,
      positionLevel: profile.posLevel.posLevelName,
      posNo: shortName ? shortName : "-",
      positionLine: position?.positionField ?? "-",
      positionPathSide: position?.positionArea ?? "-",
      positionExecutive: position?.posExecutive?.posExecutiveName ?? "-",
      amount: profile.amount,
      positionSalaryAmount: profile.positionSalaryAmount,
      mouthSalaryAmount: profile.mouthSalaryAmount,
      order:
        profile.profileSalary.length >= 0
          ? profile.profileSalary.length > 0
            ? profile.profileSalary[0].order + 1
            : 1
          : null,
      createdUserId: req.user.sub,
      createdFullName: req.user.name,
      lastUpdateUserId: req.user.sub,
      lastUpdateFullName: req.user.name,
      createdAt: new Date(),
      lastUpdatedAt: new Date(),
    });
    await Promise.all([this.salaryRepository.save(profileSalary)]);

    return new HttpSuccess();
  }

  /**
   * API ออกคำสั่ง คำสั่งยุติเรื่อง
   *
   * @summary API ออกคำสั่ง คำสั่งยุติเรื่อง (ADMIN)
   *
   */
  @Post("command32/{profileId}")
  async ExecuteCommand32Async(
    @Request() req: RequestWithUser,
    @Body()
    body: {
      profileId: string;
      date: Date | null;
      refCommandNo: string | null;
      salaryRef: string | null;
    },
  ) {
    const profile = await this.profileRepo.findOne({
      relations: ["profileSalary"],
      where: { id: body.profileId },
      order: {
        profileSalary: {
          order: "DESC",
        },
      },
    });
    if (!profile) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์");
    }
    let null_: any = null;
    profile.isLeave = false;
    profile.leaveReason = null_;
    profile.dateLeave = null_;
    profile.lastUpdateUserId = req.user.sub;
    profile.lastUpdateFullName = req.user.name;
    profile.lastUpdatedAt = new Date();

    await Promise.all([this.profileRepo.save(profile)]);

    return new HttpSuccess();
  }

  /**
   * API คำนวนวันเกษียณ
   *
   *
   */
  @Post("cal/retire")
  async calDateRetire(@Body() birthDate: Date) {
    const retireDate = await calculateRetireDate(birthDate);
    const age = calculateAge(birthDate);

    return new HttpSuccess({ retireDate, age });
  }

  /**
   * API แก้ไขประวัติในเมนูร้องขอแก้ไขทะเบียนประวัติ
   *
   * @summary แก้ไขประวัติในเมนูร้องขอแก้ไขทะเบียนประวัติ
   *
   * @param {string} id  Id ทะเบียนประวัติ
   */
  @Patch("request-edit/myprofile/{id}")
  async updateProfileReEdit(
    @Request() request: RequestWithUser,
    @Path() id: string,
    @Body() body: UpdateProfileReqEdit,
  ) {
    const record = await this.profileRepo.findOneBy({ id });

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

    Object.keys(body).forEach((key) => {
      const typedKey = key as keyof UpdateProfileReqEdit; // บอก TypeScript ว่า key เป็นฟิลด์ของ UpdateProfileReqEdit
      if (body[typedKey] === null || body[typedKey] === "") delete body[typedKey];
    });

    Object.assign(record, body);
    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 ProfileHistory(), {
        ...record,
        profileId: id,
        id: undefined,
      }),
    );
    await this.profileRepo.save(record);
    // setLogDataDiff(request, { before, after: record });

    if (record != null && record.keycloak != null) {
      const result = await updateName(record.keycloak, record.firstName, record.lastName);
      if (!result) {
        throw new Error(result.errorMessage);
      }
    }

    return new HttpSuccess();
  }

  /**
   * API แก้ไขประวัติบิดาในเมนูร้องขอแก้ไขทะเบียนประวัติ
   *
   * @summary แก้ไขประวัติบิดาในเมนูร้องขอแก้ไขทะเบียนประวัติ
   *
   * @param {string} id  Id ทะเบียนประวัติ
   */
  @Patch("request-edit/father/{id}")
  public async UpdateFamilyFather(
    @Request() req: RequestWithUser,
    @Path() id: string,
    @Body() body: UpdateProfileFather,
  ) {
    const profile = await this.profileRepo.findOneBy({ id: id });
    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }

    let lastestData: any = await this.profileFamilyFatherRepository.findOne({
      where: { profileId: id },
      order: { createdAt: "DESC" },
    });

    Object.keys(body).forEach((key) => {
      const typedKey = key as keyof UpdateProfileFather; // บอก TypeScript ว่า key เป็นฟิลด์ของ UpdateProfileFather
      if (body[typedKey] === null || body[typedKey] === "") delete body[typedKey];
    });

    if (!lastestData) {
      lastestData = new ProfileFamilyFather();
      Object.assign(lastestData, body);
      lastestData.profileId = id;
    }

    Object.assign(lastestData, body);
    lastestData.createdUserId = req.user.sub;
    lastestData.createdFullName = req.user.name;
    lastestData.lastUpdateUserId = req.user.sub;
    lastestData.lastUpdateFullName = req.user.name;
    lastestData.createdAt = new Date();
    lastestData.lastUpdatedAt = new Date();

    const history = new ProfileFamilyFatherHistory();
    Object.assign(history, { ...lastestData, id: undefined });

    await this.profileFamilyFatherRepository.save(lastestData, { data: req });
    history.profileFamilyFatherId = lastestData.id;
    await this.profileFamilyFatherHistoryRepo.save(history, { data: req });
    return new HttpSuccess(lastestData.id);
  }

  /**
   * API แก้ไขประวัติมารดาในเมนูร้องขอแก้ไขทะเบียนประวัติ
   *
   * @summary แก้ไขประวัติมารดาในเมนูร้องขอแก้ไขทะเบียนประวัติ
   *
   * @param {string} id  Id ทะเบียนประวัติ
   */
  @Patch("request-edit/mother/{id}")
  public async UpdateFamilyMother(
    @Request() req: RequestWithUser,
    @Path() id: string,
    @Body() body: UpdateProfileMother,
  ) {
    const profile = await this.profileRepo.findOneBy({ id: id });
    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }

    let lastestData = await this.profileFamilyMotherRepository.findOne({
      where: { profileId: id },
      order: { createdAt: "DESC" },
    });

    Object.keys(body).forEach((key) => {
      const typedKey = key as keyof UpdateProfileMother; // บอก TypeScript ว่า key เป็นฟิลด์ของ UpdateProfileMother
      if (body[typedKey] === null || body[typedKey] === "") delete body[typedKey];
    });

    if (!lastestData) {
      lastestData = new ProfileFamilyMother();
      Object.assign(lastestData, body);
      lastestData.profileId = id;
    }

    Object.assign(lastestData, body);
    lastestData.createdUserId = req.user.sub;
    lastestData.createdFullName = req.user.name;
    lastestData.lastUpdateUserId = req.user.sub;
    lastestData.lastUpdateFullName = req.user.name;
    lastestData.createdAt = new Date();
    lastestData.lastUpdatedAt = new Date();

    const history = new ProfileFamilyMotherHistory();
    Object.assign(history, { ...lastestData, id: undefined });

    await this.profileFamilyMotherRepository.save(lastestData, { data: req });
    history.profileFamilyMotherId = lastestData.id;
    await this.profileFamilyMotherHistoryRepo.save(history, { data: req });
    return new HttpSuccess(lastestData.id);
  }

  /**
   * API แก้ไขประวัติคู่สมรสในเมนูร้องขอแก้ไขทะเบียนประวัติ
   *
   * @summary แก้ไขประวัติคู่สมรสในเมนูร้องขอแก้ไขทะเบียนประวัติ
   *
   * @param {string} id  Id ทะเบียนประวัติ
   */
  @Patch("request-edit/couple/{id}")
  public async UpdateFamilyCouple(
    @Request() req: RequestWithUser,
    @Path() id: string,
    @Body() body: UpdateProfileCouple,
  ) {
    const profile = await this.profileRepo.findOneBy({ id: id });
    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }

    let lastestData = await this.profileFamilyCoupleRepository.findOne({
      where: { profileId: id },
      order: { createdAt: "DESC" },
    });

    Object.keys(body).forEach((key) => {
      const typedKey = key as keyof UpdateProfileCouple; // บอก TypeScript ว่า key เป็นฟิลด์ของ UpdateProfileCouple
      if (body[typedKey] === null || body[typedKey] === "") delete body[typedKey];
    });

    if (!lastestData) {
      lastestData = new ProfileFamilyCouple();
      Object.assign(lastestData, body);
      lastestData.profileId = id;
    }

    Object.assign(lastestData, body);
    lastestData.createdUserId = req.user.sub;
    lastestData.createdFullName = req.user.name;
    lastestData.lastUpdateUserId = req.user.sub;
    lastestData.lastUpdateFullName = req.user.name;
    lastestData.createdAt = new Date();
    lastestData.lastUpdatedAt = new Date();

    const history = new ProfileFamilyCoupleHistory();
    Object.assign(history, { ...lastestData, id: undefined });

    await this.profileFamilyCoupleRepository.save(lastestData, { data: req });
    history.profileFamilyCoupleId = lastestData.id;
    await this.profileFamilyCoupleHistoryRepo.save(history, { data: req });
    return new HttpSuccess(lastestData.id);
  }

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

    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 && body.citizenId.length !== 13) {
      throw new HttpError(
        HttpStatus.NOT_FOUND,
        "กรุณากรอกข้อมูลรหัสบัตรประจำตัวประชาชนให้ครบ 13 หลัก",
      );
    }

    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;
      let chkDigit = 11 - calStp2;
      if (chkDigit === 10) {
        chkDigit = 1;
      } else if (chkDigit === 11) {
        chkDigit = chkDigit % 10;
      }
      // else if(chkDigit === 11){
      //   chkDigit = cal % 10;
      // }

      //   if (citizenIdDigits[12] !== chkDigit) {
      //     throw new HttpError(HttpStatus.NOT_FOUND, "ข้อมูลรหัสบัตรประจำตัวประชาชนไม่ถูกต้อง");
      //   }
    }
    const record = await this.profileRepo.findOneBy({ id });
    const before = structuredClone(record);

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

    Object.assign(record, body);
    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 ProfileHistory(), {
        ...record,
        profileId: id,
        id: undefined,
      }),
    );
    await this.profileRepo.save(record, { data: request });
    setLogDataDiff(request, { before, after: record });

    if (record != null && record.keycloak != null) {
      const result = await updateName(record.keycloak, record.firstName, record.lastName);
      if (!result) {
        throw new Error(result.errorMessage);
      }
    }

    return new HttpSuccess();
  }

  /**
   * API ลบทะเบียนประวัติ
   *
   * @summary ORG_065 - ลบทะเบียนประวัติ (ADMIN) #70
   *
   * @param {string} id  Id ทะเบียนประวัติ
   */
  @Delete("{id}")
  async deleteProfile(@Path() id: string) {
    const data = await this.profileRepo.findOne({ where: { id: id } });
    if (!data) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    }
    await this.profileRepo.remove(data);

    return new HttpSuccess();
  }

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

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

    return new HttpSuccess(profile);
  }

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

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

    return new HttpSuccess(profile.id);
  }

  @Get("type")
  async checkRole(@Request() request: RequestWithUser) {
    let role: any;
    const checkProfile = await this.profileRepo.findOne({
      where: { keycloak: request.user.sub },
    });
    role = "OFFICER";
    if (!checkProfile) {
      const checkEmployee = await this.profileEmpRepo.findOne({
        where: { keycloak: request.user.sub },
        select: ["employeeClass"],
      });
      if (checkEmployee?.employeeClass === "PERM" || checkEmployee?.employeeClass === "TEMP") {
        role = checkEmployee.employeeClass.toUpperCase();
      } else {
        role = "EMPLOYEE";
      }
      if (!checkProfile && !checkEmployee)
        throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์นี้");
    }
    return new HttpSuccess(role);
  }

  /**
   * API ประวัติการแก้ไขรายการทะเบียนประวัติ
   *
   * @summary ประวัติการแก้ไขรายการทะเบียนประวัติ
   *
   * @param {string} id  Id โปรไฟล์
   */
  @Get("history/user")
  async getHistoryProfileByUser(@Request() request: RequestWithUser) {
    const historyProfile = await this.profileHistoryRepo.find({
      relations: {
        posLevel: true,
        posType: true,
      },
      where: { keycloak: request.user.sub },
      order: {
        createdAt: "ASC",
      },
    });

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

    return new HttpSuccess(historyProfile);
  }

  /**
   * API รายการทะเบียนประวัติในระบบอื่น
   *
   * @summary ORG_065 - รายการทะเบียนประวัติในระบบอื่น
   *
   */
  @Get("otherSystem")
  @Example({
    status: 200,
    message: "สำเร็จ",
    result: {
      data: [
        {
          id: "ecb0b34c-037e-41f2-b95e-7e19f88b42ae",
          createdAt: "2024-03-24T12:39:12.105Z",
          createdUserId: "00000000-0000-0000-0000-000000000000",
          lastUpdatedAt: "2024-03-24T12:41:43.164Z",
          lastUpdateUserId: "00000000-0000-0000-0000-000000000000",
          createdFullName: "string",
          lastUpdateFullName: "string",
          rank: null,
          prefix: null,
          firstName: "Methapon",
          lastName: "Metanipat",
          citizenId: null,
          position: null,
          posLevelId: null,
          posTypeId: null,
          email: null,
          phone: null,
          keycloak: null,
          isProbation: false,
          dateRetire: null,
          birthDate: null,
          ethnicity: null,
          telephoneNumber: null,
          gender: null,
          relationship: null,
          bloodGroup: null,
          posLevel: null,
          posType: null,
          org: null,
        },
      ],
      total: 1,
    },
  })
  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() node?: number,
    @Query() nodeId?: string,
    @Query() isAll?: boolean,
  ) {
    let queryLike =
      "CONCAT(profile.prefix, profile.firstName, ' ', profile.lastName) LIKE :keyword";
    if (searchField == "citizenId") {
      queryLike = "profile.citizenId LIKE :keyword";
    } else if (searchField == "position") {
      queryLike = "profile.position LIKE :keyword";
    } else if (searchField == "posNo") {
      queryLike = `CONCAT(
          IFNULL(orgChild4.orgChild4ShortName, ''),
          IFNULL(orgChild3.orgChild3ShortName, ''),
          IFNULL(orgChild2.orgChild2ShortName, ''),
          IFNULL(orgChild1.orgChild1ShortName, ''),
          IFNULL(orgRoot.orgRootShortName, ''),
          IFNULL(current_holders.posMasterNo , '')
        ) 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 [record, total] = await this.profileRepo
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.posLevel", "posLevel")
      .leftJoinAndSelect("profile.posType", "posType")
      .leftJoinAndSelect("profile.current_holders", "current_holders")
      .leftJoinAndSelect("current_holders.positions", "positions")
      .leftJoinAndSelect("positions.posExecutive", "posExecutive")
      .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(
        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,
      })
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getManyAndCount();

    const findRevision = await this.orgRevisionRepo.findOne({
      where: { orgRevisionIsCurrent: true },
    });
    if (!findRevision) {
      throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
    }
    const data = await Promise.all(
      record.map((_data) => {
        const posExecutive =
          _data.current_holders.length == 0 ||
          _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) == null ||
          _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.positions.length ==
            0 ||
          _data.current_holders
            .find((x) => x.orgRevisionId == findRevision.id)
            ?.positions.find((x: any) => x.positionIsSelected == true) == null ||
          _data.current_holders
            .find((x) => x.orgRevisionId == findRevision.id)
            ?.positions.find((x: any) => x.positionIsSelected == true)?.posExecutive == null
            ? null
            : _data.current_holders
                .find((x) => x.orgRevisionId == findRevision.id)
                ?.positions.find((x: any) => x.positionIsSelected == true)?.posExecutive
                ?.posExecutiveName;

        const shortName =
          _data.current_holders.length == 0
            ? null
            : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
                _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4 !=
                  null
              ? `${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4.orgChild4ShortName}${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
              : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
                  _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)
                    ?.orgChild3 != null
                ? `${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3.orgChild3ShortName}${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
                : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
                    _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)
                      ?.orgChild2 != null
                  ? `${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2.orgChild2ShortName}${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
                  : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
                      _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)
                        ?.orgChild1 != null
                    ? `${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1.orgChild1ShortName}${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
                    : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) !=
                          null &&
                        _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)
                          ?.orgRoot != null
                      ? `${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot.orgRootShortName}${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
                      : null;
        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 _child1 = child1 == null ? "" : `${child1.orgChild1Name}/`;
        let _child2 = child2 == null ? "" : `${child2.orgChild2Name}/`;
        let _child3 = child3 == null ? "" : `${child3.orgChild3Name}/`;
        let _child4 = child4 == null ? "" : `${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,
          posLevelId: _data.posLevel == null ? null : _data.posLevel.id,
          posTypeId: _data.posType == null ? null : _data.posType.id,
          position: _data.position,
          posExecutive: posExecutive,
          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}${_child3}${_child2}${_child1}${root?.orgRootName ?? ""}`,
        };
      }),
    );

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

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

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

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

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

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

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

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

  @Get("history/{id}")
  async getProfileHistory(@Path() id: string, @Request() req: RequestWithUser) {
    //await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_OFFICER", id); //ไม่แน่ใจOFFปิดไว้ก่อน
    const profile = await this.profileHistoryRepo.find({
      relations: {
        posLevel: true,
        posType: true,
      },
      where: { profileId: id },
      order: {
        createdAt: "ASC",
      },
    });

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

    return new HttpSuccess(profile);
  }

  /**
   * API รายการทะเบียนประวัติ
   *
   * @summary ORG_065 - รายการทะเบียนประวัติ (ADMIN) #70
   *
   */
  @Get()
  @Example({
    status: 200,
    message: "สำเร็จ",
    result: {
      data: [
        {
          id: "ecb0b34c-037e-41f2-b95e-7e19f88b42ae",
          createdAt: "2024-03-24T12:39:12.105Z",
          createdUserId: "00000000-0000-0000-0000-000000000000",
          lastUpdatedAt: "2024-03-24T12:41:43.164Z",
          lastUpdateUserId: "00000000-0000-0000-0000-000000000000",
          createdFullName: "string",
          lastUpdateFullName: "string",
          rank: null,
          prefix: null,
          firstName: "Methapon",
          lastName: "Metanipat",
          citizenId: null,
          position: null,
          posLevelId: null,
          posTypeId: null,
          email: null,
          phone: null,
          keycloak: null,
          isProbation: false,
          dateRetire: null,
          birthDate: null,
          ethnicity: null,
          telephoneNumber: null,
          gender: null,
          relationship: null,
          bloodGroup: null,
          posLevel: null,
          posType: null,
          org: null,
        },
      ],
      total: 1,
    },
  })
  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() yearLeave?: number,
    @Query() isProbation?: boolean,
    @Query() isRetire?: boolean,
    @Query() node?: number,
    @Query() nodeId?: string,
    @Query() isAll?: boolean,
  ) {
    let _data = await new permission().PermissionOrgList(request, "SYS_REGISTRY_OFFICER");
    let queryLike =
      "CONCAT(profile.prefix, profile.firstName, ' ', profile.lastName) LIKE :keyword";
    if (searchField == "citizenId") {
      queryLike = "profile.citizenId LIKE :keyword";
    } else if (searchField == "position") {
      queryLike = "profile.position LIKE :keyword";
    } else if (searchField == "posNo") {
      queryLike = `CONCAT(
        IFNULL(orgChild4.orgChild4ShortName, ''),
        IFNULL(orgChild3.orgChild3ShortName, ''),
        IFNULL(orgChild2.orgChild2ShortName, ''),
        IFNULL(orgChild1.orgChild1ShortName, ''),
        IFNULL(orgRoot.orgRootShortName, ''),
        IFNULL(current_holders.posMasterNo , '')
      ) 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 [record, total] = await this.profileRepo
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.posLevel", "posLevel")
      .leftJoinAndSelect("profile.posType", "posType")
      .leftJoinAndSelect("profile.current_holders", "current_holders")
      .leftJoinAndSelect("current_holders.positions", "positions")
      .leftJoinAndSelect("positions.posExecutive", "posExecutive")
      .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(
        _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 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 != ""
          ? "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,
      })
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getManyAndCount();

    const findRevision = await this.orgRevisionRepo.findOne({
      where: { orgRevisionIsCurrent: true },
    });
    if (!findRevision) {
      throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
    }
    const data = await Promise.all(
      record.map((_data) => {
        const posExecutive =
          _data.current_holders.length == 0 ||
          _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) == null ||
          _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.positions.length ==
            0 ||
          _data.current_holders
            .find((x) => x.orgRevisionId == findRevision.id)
            ?.positions.find((x: any) => x.positionIsSelected == true) == null ||
          _data.current_holders
            .find((x) => x.orgRevisionId == findRevision.id)
            ?.positions.find((x: any) => x.positionIsSelected == true)?.posExecutive == null
            ? null
            : _data.current_holders
                .find((x) => x.orgRevisionId == findRevision.id)
                ?.positions.find((x: any) => x.positionIsSelected == true)?.posExecutive
                ?.posExecutiveName;

        const shortName =
          _data.current_holders.length == 0
            ? null
            : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
                _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4 !=
                  null
              ? `${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4.orgChild4ShortName}${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
              : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
                  _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)
                    ?.orgChild3 != null
                ? `${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3.orgChild3ShortName}${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
                : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
                    _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)
                      ?.orgChild2 != null
                  ? `${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2.orgChild2ShortName}${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
                  : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
                      _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)
                        ?.orgChild1 != null
                    ? `${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1.orgChild1ShortName}${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
                    : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) !=
                          null &&
                        _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)
                          ?.orgRoot != null
                      ? `${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot.orgRootShortName}${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
                      : null;
        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 _child1 = child1 == null ? "" : `${child1.orgChild1Name}/`;
        let _child2 = child2 == null ? "" : `${child2.orgChild2Name}/`;
        let _child3 = child3 == null ? "" : `${child3.orgChild3Name}/`;
        let _child4 = child4 == null ? "" : `${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,
          posLevelId: _data.posLevel == null ? null : _data.posLevel.id,
          posTypeId: _data.posType == null ? null : _data.posType.id,
          position: _data.position,
          posExecutive: posExecutive,
          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}${_child3}${_child2}${_child1}${root?.orgRootName ?? ""}`,
        };
      }),
    );

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

  /**
   * API ค้นหารายชื่อไปครองตำแหน่ง
   *
   * @summary ORG_063 - ค้นหารายชื่อไปครองตำแหน่ง (ADMIN) #68
   */
  @Post("search")
  async searchProfileOrg(
    @Body()
    requestBody: {
      position?: string | null;
      posLevelId?: string | null;
      posTypeId?: string | null;
      page: number;
      pageSize: number;
      keyword?: string;
    },
  ) {
    const orgRevision = await this.orgRevisionRepo.findOne({
      where: {
        orgRevisionIsDraft: true,
        orgRevisionIsCurrent: false,
      },
      relations: ["posMasters"],
    });
    if (!orgRevision) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบแบบร่างโครงสร้าง");
    }
    const [profiles, total] = await this.profileRepo
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.next_holders", "next_holders")
      .leftJoinAndSelect("profile.posLevel", "posLevel")
      .leftJoinAndSelect("profile.posType", "posType")
      .where(
        requestBody.position != null && requestBody.position != ""
          ? "profile.position LIKE :position"
          : "1=1",
        {
          position: `%${requestBody.position}%`,
        },
      )
      .andWhere("profile.isLeave IS FALSE")
      .andWhere(
        new Brackets((qb) => {
          qb.where(
            requestBody.keyword != null && requestBody.keyword != ""
              ? "profile.prefix LIKE :keyword"
              : "1=1",
            {
              keyword: `%${requestBody.keyword}%`,
            },
          )
            .orWhere(
              requestBody.keyword != null && requestBody.keyword != ""
                ? "profile.firstName LIKE :keyword"
                : "1=1",
              {
                keyword: `%${requestBody.keyword}%`,
              },
            )
            .orWhere(
              requestBody.keyword != null && requestBody.keyword != ""
                ? "profile.lastName LIKE :keyword"
                : "1=1",
              {
                keyword: `%${requestBody.keyword}%`,
              },
            )
            .orWhere(
              requestBody.keyword != null && requestBody.keyword != ""
                ? "profile.citizenId LIKE :keyword"
                : "1=1",
              {
                keyword: `%${requestBody.keyword}%`,
              },
            );
        }),
      )
      .andWhere(
        requestBody.posTypeId != null && requestBody.posTypeId != ""
          ? "profile.posTypeId LIKE :posTypeId"
          : "1=1",
        {
          posTypeId: `%${requestBody.posTypeId}%`,
        },
      )
      .andWhere(
        requestBody.posLevelId != null && requestBody.posLevelId != ""
          ? "profile.posLevelId LIKE :posLevelId"
          : "1=1",
        {
          posLevelId: `%${requestBody.posLevelId}%`,
        },
      )
      .andWhere(
        new Brackets((qb) => {
          qb.where("profile.id NOT IN (:...ids)", {
            ids:
              orgRevision.posMasters
                .filter((x) => x.next_holderId != null)
                .map((x) => x.next_holderId).length == 0
                ? ["zxc"]
                : orgRevision.posMasters
                    .filter((x) => x.next_holderId != null)
                    .map((x) => x.next_holderId),
          });
        }),
      )
      .skip((requestBody.page - 1) * requestBody.pageSize)
      .take(requestBody.pageSize)
      .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.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("profile")
      .leftJoinAndSelect("profile.profileSalary", "profileSalary")
      .select([
        "profile.id",
        "profile.prefix",
        "profile.firstName",
        "profile.lastName",
        "profile.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
          ? "profileSalary.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,
        // prefix: profile.prefix,
        // firstName: profile.firstName,
        // lastName: profile.lastName,
        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 ข้อมูลทะเบียนประวัติตาม 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) {
      const profile = await this.profileEmpRepo.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) {
        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.positionRepository.findOne({
        relations: ["posExecutive"],
        where: {
          posMasterId: posMaster?.id,
        },
      });

      const _profile: any = {
        profileId: profile.id,
        prefix: profile.prefix,
        rank: profile.rank,
        avatar: profile.avatar,
        isDirector: profile.current_holders[0]?.isDirector ?? null,
        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 ? 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,
        posTypeRank: profile.posType == null ? null : profile.posType.posTypeRank,
        posTypeId: profile.posType == null ? null : profile.posType.id,
        posExecutiveName:
          position == null || position.posExecutive == null
            ? null
            : position.posExecutive.posExecutiveName,
        posExecutivePriority:
          position == null || position.posExecutive == null
            ? null
            : position.posExecutive.posExecutivePriority,
        posExecutiveId:
          position == null || position.posExecutive == null ? null : position.posExecutive.id,
        rootId: root == null ? null : root.id,
        root: root == null ? null : root.orgRootName,
        rootShortName: root == null ? null : root.orgRootShortName,
        child1Id: child1 == null ? null : child1.id,
        child1: child1 == null ? null : child1.orgChild1Name,
        child1ShortName: child1 == null ? null : child1.orgChild1ShortName,
        child2Id: child2 == null ? null : child2.id,
        child2: child2 == null ? null : child2.orgChild2Name,
        child2ShortName: child2 == null ? null : child2.orgChild2ShortName,
        child3Id: child3 == null ? null : child3.id,
        child3: child3 == null ? null : child3.orgChild3Name,
        child3ShortName: child3 == null ? null : child3.orgChild3ShortName,
        child4Id: child4 == null ? null : child4.id,
        child4: child4 == null ? null : child4.orgChild4Name,
        child4ShortName: child4 == null ? null : child4.orgChild4ShortName,
        node: null,
        nodeId: null,
        type: profile.employeeClass,
        salary:
          profile && profile.profileSalary.length > 0 ? profile.profileSalary[0].amount : null,
      };
      if (_profile.child4Id != null) {
        _profile.node = 4;
        _profile.nodeId = _profile.child4Id;
        _profile.nodeShortName = _profile.child4ShortName;
      } else if (_profile.child3Id != null) {
        _profile.node = 3;
        _profile.nodeId = _profile.child3Id;
        _profile.nodeShortName = _profile.child3ShortName;
      } else if (_profile.child2Id != null) {
        _profile.node = 2;
        _profile.nodeId = _profile.child2Id;
        _profile.nodeShortName = _profile.child2ShortName;
      } else if (_profile.child1Id != null) {
        _profile.node = 1;
        _profile.nodeId = _profile.child1Id;
        _profile.nodeShortName = _profile.child1ShortName;
      } else if (_profile.rootId != null) {
        _profile.node = 0;
        _profile.nodeId = _profile.rootId;
        _profile.nodeShortName = _profile.rootShortName;
      }
      return new HttpSuccess(_profile);
    }

    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.positionRepository.findOne({
      relations: ["posExecutive"],
      where: {
        posMasterId: posMaster?.id,
      },
    });

    const _profile: any = {
      profileId: profile.id,
      prefix: profile.prefix,
      rank: profile.rank,
      avatar: profile.avatar,
      isDirector: posMaster?.isDirector || false,
      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 ? 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,
      posTypeRank: profile.posType == null ? null : profile.posType.posTypeRank,
      posTypeId: profile.posType == null ? null : profile.posType.id,
      posExecutiveName:
        position == null || position.posExecutive == null
          ? null
          : position.posExecutive.posExecutiveName,
      posExecutivePriority:
        position == null || position.posExecutive == null
          ? null
          : position.posExecutive.posExecutivePriority,
      posExecutiveId:
        position == null || position.posExecutive == null ? null : position.posExecutive.id,
      rootId: root == null ? null : root.id,
      root: root == null ? null : root.orgRootName,
      rootShortName: root == null ? null : root.orgRootShortName,
      child1Id: child1 == null ? null : child1.id,
      child1: child1 == null ? null : child1.orgChild1Name,
      child1ShortName: child1 == null ? null : child1.orgChild1ShortName,
      child2Id: child2 == null ? null : child2.id,
      child2: child2 == null ? null : child2.orgChild2Name,
      child2ShortName: child2 == null ? null : child2.orgChild2ShortName,
      child3Id: child3 == null ? null : child3.id,
      child3: child3 == null ? null : child3.orgChild3Name,
      child3ShortName: child3 == null ? null : child3.orgChild3ShortName,
      child4Id: child4 == null ? null : child4.id,
      child4: child4 == null ? null : child4.orgChild4Name,
      child4ShortName: child4 == null ? null : child4.orgChild4ShortName,
      node: null,
      nodeId: null,
      salary: profile ? profile.amount : null,
    };

    if (_profile.child4Id != null) {
      _profile.node = 4;
      _profile.nodeId = _profile.child4Id;
      _profile.nodeShortName = _profile.child4ShortName;
    } else if (_profile.child3Id != null) {
      _profile.node = 3;
      _profile.nodeId = _profile.child3Id;
      _profile.nodeShortName = _profile.child3ShortName;
    } else if (_profile.child2Id != null) {
      _profile.node = 2;
      _profile.nodeId = _profile.child2Id;
      _profile.nodeShortName = _profile.child2ShortName;
    } else if (_profile.child1Id != null) {
      _profile.node = 1;
      _profile.nodeId = _profile.child1Id;
      _profile.nodeShortName = _profile.child1ShortName;
    } else if (_profile.rootId != null) {
      _profile.node = 0;
      _profile.nodeId = _profile.rootId;
      _profile.nodeShortName = _profile.rootShortName;
    }
    return new HttpSuccess(_profile);
  }
  /**
   * API ข้อมูลทะเบียนประวัติตาม keycloak
   *
   * @summary ORG_065 - ข้อมูลทะเบียนประวัติตาม keycloak (ADMIN) #70
   *
   */
  @Get("keycloak/position-act")
  async getProfileByKeycloakAct(
    @Request() request: { user: Record<string, any> },
    @Query("revisionId") revisionId?: string,
  ) {
    if (!revisionId) {
      let orgRevisionPublish = await this.orgRevisionRepo
        .createQueryBuilder("orgRevision")
        .where("orgRevision.orgRevisionIsDraft = false")
        .andWhere("orgRevision.orgRevisionIsCurrent = true")
        .getOne();
      if (!orgRevisionPublish) {
        throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบแบบร่างโครงสร้าง");
      }
      revisionId = orgRevisionPublish.id;
    }
    const posMasters = await this.posMasterRepo.findOne({
      where: {
        posMasterAssigns: { assignId: "SYS_PLACEMENT_PASS" },
        current_holder: {
          keycloak: request.user.sub,
        },
        orgRevisionId: revisionId,
      },
      relations: ["orgChild1"],
    });
    if (posMasters == null) {
      return new HttpSuccess({
        isOfficer: null,
        rootId: null,
        child1Id: null,
        child2Id: null,
        child3Id: null,
        child4Id: null,
      });
    }
    return new HttpSuccess({
      isOfficer: posMasters?.orgChild1?.isOfficer || false,
      rootId: posMasters?.orgRootId || null,
      child1Id: posMasters?.orgChild1Id || null,
      child2Id: posMasters?.orgChild2Id || null,
      child3Id: posMasters?.orgChild3Id || null,
      child4Id: posMasters?.orgChild4Id || null,
    });
  }

  /**
   * API เช็ค สกจ
   *
   * @summary เช็ค สกจ
   *
   */
  @Get("keycloak/idofficer")
  async getIsOfficerByKeycloak(@Request() request: RequestWithUser) {
    const posMasters = await this.posMasterRepo.findOne({
      where: {
        current_holder: {
          keycloak: request.user.sub,
        },
        orgRevision: {
          orgRevisionIsCurrent: true,
          orgRevisionIsDraft: false,
        },
      },
      relations: ["orgChild1"],
    });
    if (posMasters == null || posMasters.orgChild1 == null) {
      return new HttpSuccess(false);
    }
    return new HttpSuccess(posMasters.orgChild1.isOfficer);
  }

  /**
   * API ข้อมูลทะเบียนประวัติตาม keycloakid
   *
   * @summary ข้อมูลทะเบียนประวัติตาม keycloak + ผู้บังคับบัญชา
   *
   * @param id keycloak Id
   */
  @Get("keycloak/commander/{id}")
  async getProfileAndCommander(@Request() request: RequestWithUser, @Path() id: string) {
    const profile = await this.profileRepo.findOne({
      where: { keycloak: id },
      relations: ["posLevel", "posType", "current_holders", "current_holders.orgRoot"],
    });
    if (!profile) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลบุคคลนี้ในระบบ");
    }
    const orgRevisionPublish = await this.orgRevisionRepo.findOne({
      where: {
        orgRevisionIsDraft: false,
        orgRevisionIsCurrent: true,
      },
    });
    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.positionRepository.findOne({
      relations: ["posExecutive"],
      where: {
        posMasterId: posMaster?.id,
      },
    });

    //find org(สังกัด)
    const posMaster_ = await this.posMasterRepo.findOne({
      where: {
        orgRevisionId: orgRevisionPublish?.id,
        current_holderId: profile.id,
      },
      order: { createdAt: "DESC" },
      relations: {
        orgRoot: true,
        orgChild1: true,
        orgChild2: true,
        orgChild3: true,
        orgChild4: true,
      },
    });
    const fullNameParts = [
      posMaster_ == null || posMaster_.orgChild4 == null
        ? null
        : posMaster_.orgChild4.orgChild4Name,
      posMaster_ == null || posMaster_.orgChild3 == null
        ? null
        : posMaster_.orgChild3.orgChild3Name,
      posMaster_ == null || posMaster_.orgChild2 == null
        ? null
        : posMaster_.orgChild2.orgChild2Name,
      posMaster_ == null || posMaster_.orgChild1 == null
        ? null
        : posMaster_.orgChild1.orgChild1Name,
      posMaster_ == null || posMaster_.orgRoot == null ? null : posMaster_.orgRoot.orgRootName,
    ];
    const org = fullNameParts.filter((part) => part !== undefined && part !== null).join("/");

    //find commander(ผู้บังคับบัญชา)
    let node = 4;
    let childId = posMaster?.orgChild4Id;
    let condition: any = { orgChild4Id: childId };

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

    const findCmd = await this.posMasterRepo.findOne({
      where: {
        current_holderId: Not(IsNull()) || Not(""),
        orgRevisionId: orgRevisionPublish?.id,
        ...condition,
      },
      relations: ["current_holder"],
      order: { posMasterOrder: "ASC" },
    });

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

    //หาผู้บังคับบัญชาที่เหนือขึ้นไปอีก 2 ขั้น
    if (node !== 0 && node !== 1) {
      findTSAB = await AppDataSource.getRepository(PosMaster)
        .createQueryBuilder("posMaster")
        .leftJoinAndSelect("posMaster.current_holder", "current_holder")
        .where("posMaster.current_holderId IS NOT NULL")
        .andWhere("posMaster.orgRevisionId = :revisionId", { revisionId: orgRevisionPublish?.id })
        .andWhere(
          new Brackets((qb) => {
            if (node === 4) {
              qb.andWhere("posMaster.orgChild3Id IS NULL");
              qb.andWhere("posMaster.orgChild2Id = :childId", {
                childId: posMaster?.orgChild2Id,
              });
            } else if (node === 3) {
              qb.andWhere("posMaster.orgChild2Id IS NULL");
              qb.andWhere("posMaster.orgChild1Id = :childId", {
                childId: posMaster?.orgChild1Id,
              });
            } else if (node === 2) {
              qb.andWhere("posMaster.orgChild1Id IS NULL");
              qb.andWhere("posMaster.orgRootId = :childId", {
                childId: posMaster?.orgRootId,
              });
            }
          }),
        )
        .orderBy("posMaster.posMasterOrder", "ASC")
        .getOne();
    }

    let commandProfileId;
    let commanderFullname_: any = {};
    let commanderPosition_: any = {};
    let commanderRootName_: any = {};
    let commanderOrg_: any;
    let commandAboveProfileId;
    let commanderAboveFullname_: any = {};
    let commanderAbovePosition_: any = {};
    let commanderAboveRootName_: any = {};
    let commanderAboveOrg_: any;
    let dataCommander: any;

    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 == profile?.id) {
      commandProfileId = findOSAB?.current_holderId;
      commanderFullname_ =
        (findOSAB?.current_holder?.prefix ?? "") +
        (findOSAB?.current_holder?.firstName ?? "") +
        (findOSAB?.current_holder?.firstName ? " " : "") +
        (findOSAB?.current_holder?.lastName ?? "");
      commanderPosition_ = findOSAB?.current_holder?.position ?? "";
      commandAboveProfileId = findTSAB?.current_holderId;
      commanderAboveFullname_ =
        (findTSAB?.current_holder?.prefix ?? "") +
        (findTSAB?.current_holder?.firstName ?? "") +
        (findTSAB?.current_holder?.firstName ? " " : "") +
        (findTSAB?.current_holder?.lastName ?? "");
      commanderAbovePosition_ = findTSAB?.current_holder?.position ?? "";
      dataCommander = {
        commanderFullname: commanderFullname_,
        commanderPosition: commanderPosition_,
        commanderAboveFullname: commanderAboveFullname_,
        commanderAbovePosition: commanderAbovePosition_,
      };
    } else {
      commandProfileId = findCmd?.current_holderId;
      commandAboveProfileId = findOSAB?.current_holderId;
      dataCommander = {
        commanderFullname: commanderFullname_,
        commanderPosition: commanderPosition_,
        commanderAboveFullname: commanderAboveFullname_,
        commanderAbovePosition: commanderAbovePosition_,
      };
    }

    const commandProfile = await this.profileRepo.findOne({
      where: { id: String(commandProfileId) },
      relations: ["current_holders", "current_holders.orgRoot"],
    });

    commanderRootName_ =
      commandProfile?.current_holders == null ||
      commandProfile?.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)
        ?.orgRoot == null
        ? null
        : commandProfile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)
            ?.orgRoot;
    //find สังกัดผู้บังคับบัญชา
    const commanderPosMaster_ = await this.posMasterRepo.findOne({
      where: {
        orgRevisionId: orgRevisionPublish?.id,
        current_holderId: String(commandProfileId),
      },
      order: { createdAt: "DESC" },
      relations: {
        orgRoot: true,
        orgChild1: true,
        orgChild2: true,
        orgChild3: true,
        orgChild4: true,
      },
    });
    const commanderFullNameParts = [
      commanderPosMaster_ == null || commanderPosMaster_.orgChild4 == null
        ? null
        : commanderPosMaster_.orgChild4.orgChild4Name,
      commanderPosMaster_ == null || commanderPosMaster_.orgChild3 == null
        ? null
        : commanderPosMaster_.orgChild3.orgChild3Name,
      commanderPosMaster_ == null || commanderPosMaster_.orgChild2 == null
        ? null
        : commanderPosMaster_.orgChild2.orgChild2Name,
      commanderPosMaster_ == null || commanderPosMaster_.orgChild1 == null
        ? null
        : commanderPosMaster_.orgChild1.orgChild1Name,
      commanderPosMaster_ == null || commanderPosMaster_.orgRoot == null
        ? null
        : commanderPosMaster_.orgRoot.orgRootName,
    ];
    commanderOrg_ = commanderFullNameParts
      .filter((part) => part !== undefined && part !== null)
      .join("/");

    const commandAboveProfile = await this.profileRepo.findOne({
      where: { id: String(commandAboveProfileId) },
      relations: ["current_holders", "current_holders.orgRoot"],
    });

    commanderAboveRootName_ =
      commandAboveProfile?.current_holders == null ||
      commandAboveProfile?.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)
        ?.orgRoot == null
        ? null
        : commandAboveProfile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)
            ?.orgRoot;
    //find สังกัดผู้บังคับบัญชาเหนือไป1ขั้น
    const commanderAbovePosMaster_ = await this.posMasterRepo.findOne({
      where: {
        orgRevisionId: orgRevisionPublish?.id,
        current_holderId: String(commandAboveProfileId),
      },
      order: { createdAt: "DESC" },
      relations: {
        orgRoot: true,
        orgChild1: true,
        orgChild2: true,
        orgChild3: true,
        orgChild4: true,
      },
    });
    const commanderAboveFullNameParts = [
      commanderAbovePosMaster_ == null || commanderAbovePosMaster_.orgChild4 == null
        ? null
        : commanderAbovePosMaster_.orgChild4.orgChild4Name,
      commanderAbovePosMaster_ == null || commanderAbovePosMaster_.orgChild3 == null
        ? null
        : commanderAbovePosMaster_.orgChild3.orgChild3Name,
      commanderAbovePosMaster_ == null || commanderAbovePosMaster_.orgChild2 == null
        ? null
        : commanderAbovePosMaster_.orgChild2.orgChild2Name,
      commanderAbovePosMaster_ == null || commanderAbovePosMaster_.orgChild1 == null
        ? null
        : commanderAbovePosMaster_.orgChild1.orgChild1Name,
      commanderAbovePosMaster_ == null || commanderAbovePosMaster_.orgRoot == null
        ? null
        : commanderAbovePosMaster_.orgRoot.orgRootName,
    ];
    commanderAboveOrg_ = commanderAboveFullNameParts
      .filter((part) => part !== undefined && part !== null)
      .join("/");

    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 ? 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,
      posTypeRank: profile.posType == null ? null : profile.posType.posTypeRank,
      posTypeId: profile.posType == null ? null : profile.posType.id,
      posExecutiveName:
        position == null || position.posExecutive == null
          ? null
          : position.posExecutive.posExecutiveName,
      posExecutivePriority:
        position == null || position.posExecutive == null
          ? null
          : position.posExecutive.posExecutivePriority,
      posExecutiveId:
        position == null || position.posExecutive == null ? null : position.posExecutive.id,
      rootId: root == null ? null : root.id,
      root: root == null ? null : root.orgRootName,
      rootShortName: root == null ? null : root.orgRootShortName,
      child1Id: child1 == null ? null : child1.id,
      child1: child1 == null ? null : child1.orgChild1Name,
      child1ShortName: child1 == null ? null : child1.orgChild1ShortName,
      child2Id: child2 == null ? null : child2.id,
      child2: child2 == null ? null : child2.orgChild2Name,
      child2ShortName: child2 == null ? null : child2.orgChild2ShortName,
      child3Id: child3 == null ? null : child3.id,
      child3: child3 == null ? null : child3.orgChild3Name,
      child3ShortName: child3 == null ? null : child3.orgChild3ShortName,
      child4Id: child4 == null ? null : child4.id,
      child4: child4 == null ? null : child4.orgChild4Name,
      child4ShortName: child4 == null ? null : child4.orgChild4ShortName,
      node: null,
      nodeId: null,
      org: org ? org : null,
      // commander: dataCommander,
      commanderFullname:
        dataCommander && dataCommander.commanderFullname ? dataCommander.commanderFullname : null,
      commanderPosition:
        dataCommander && dataCommander.commanderPosition ? dataCommander.commanderPosition : null,
      commanderRootName:
        commanderRootName_ && commanderRootName_.orgRootName
          ? commanderRootName_.orgRootName
          : null,
      commanderOrg: commanderOrg_ ? commanderOrg_ : null,
      commanderAboveFullname:
        dataCommander && dataCommander.commanderAboveFullname
          ? dataCommander.commanderAboveFullname
          : null,
      commanderAbovePosition:
        dataCommander && dataCommander.commanderAbovePosition
          ? dataCommander.commanderAbovePosition
          : null,
      commanderAboveRootName:
        commanderAboveRootName_ && commanderAboveRootName_.orgRootName
          ? commanderAboveRootName_.orgRootName
          : null,
      commanderAboveOrg: commanderAboveOrg_ ? commanderAboveOrg_ : null,
    };

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

  /**
   * API ข้อมูลทะเบียนประวัติตาม profileid
   *
   * @summary ORG_065 - ข้อมูลทะเบียนประวัติตาม profileid (ADMIN) #70
   *
   */
  @Get("profileid/position/{id}")
  async getProfileByProfileid(@Request() request: RequestWithUser, @Path() id: string) {
    //await new permission().PermissionOrgUserGet(request, "SYS_REGISTRY_OFFICER", id); //ไม่แน่ใจOFFปิดไว้ก่อน
    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: {
          createdAt: "DESC",
        },
      },
    });
    if (!profile) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลบุคคลนี้ในระบบ");
    }

    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 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.positionRepository.findOne({
      relations: ["posExecutive"],
      where: {
        posMasterId: posMaster?.id,
      },
    });
    const shortName =
      profile.current_holders.length == 0
        ? null
        : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) != null &&
            profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)
              ?.orgChild4 != null
          ? `${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild4.orgChild4ShortName}${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.posMasterNo}`
          : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) != null &&
              profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)
                ?.orgChild3 != null
            ? `${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild3.orgChild3ShortName}${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.posMasterNo}`
            : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) !=
                  null &&
                profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)
                  ?.orgChild2 != null
              ? `${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild2.orgChild2ShortName}${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.posMasterNo}`
              : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) !=
                    null &&
                  profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)
                    ?.orgChild1 != null
                ? `${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild1.orgChild1ShortName}${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.posMasterNo}`
                : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) !=
                      null &&
                    profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)
                      ?.orgRoot != null
                  ? `${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgRoot.orgRootShortName}${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.posMasterNo}`
                  : null;
    const posMasterActs = await this.posMasterActRepository.find({
      relations: [
        "posMaster",
        "posMaster.orgRoot",
        "posMaster.orgChild1",
        "posMaster.orgChild2",
        "posMaster.orgChild3",
        "posMaster.orgChild4",
        "posMaster.current_holder",
        "posMaster.current_holder.posLevel",
        "posMaster.current_holder.posType",
      ],
      where: {
        posMaster: {
          orgRevisionId: orgRevisionPublish.id,
        },
        posMasterChild: {
          current_holderId: profile.id,
        },
      },
    });
    const data = await Promise.all(
      posMasterActs
        .sort((a, b) => a.posMaster.posMasterOrder - b.posMaster.posMasterOrder)
        .map((item) => {
          const shortName =
            item.posMaster != null && item.posMaster.orgChild4 != null
              ? `${item.posMaster.orgChild4.orgChild4ShortName}${item.posMaster.posMasterNo}`
              : item.posMaster != null && item.posMaster?.orgChild3 != null
                ? `${item.posMaster.orgChild3.orgChild3ShortName}${item.posMaster.posMasterNo}`
                : item.posMaster != null && item.posMaster?.orgChild2 != null
                  ? `${item.posMaster.orgChild2.orgChild2ShortName}${item.posMaster.posMasterNo}`
                  : item.posMaster != null && item.posMaster?.orgChild1 != null
                    ? `${item.posMaster.orgChild1.orgChild1ShortName}${item.posMaster.posMasterNo}`
                    : item.posMaster != null && item.posMaster?.orgRoot != null
                      ? `${item.posMaster.orgRoot.orgRootShortName}${item.posMaster.posMasterNo}`
                      : null;
          return {
            id: item.id,
            posMasterOrder: item.posMasterOrder,
            profileId: item.posMaster?.current_holder?.id ?? null,
            citizenId: item.posMaster?.current_holder?.citizenId ?? null,
            prefix: item.posMaster?.current_holder?.prefix ?? null,
            firstName: item.posMaster?.current_holder?.firstName ?? null,
            lastName: item.posMaster?.current_holder?.lastName ?? null,
            posLevel: item.posMaster?.current_holder?.posLevel?.posLevelName ?? null,
            posType: item.posMaster?.current_holder?.posType?.posTypeName ?? null,
            position: item.posMaster?.current_holder?.position ?? null,
            posNo: shortName,
          };
        }),
    );
    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.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,
      posTypeRank: profile.posType == null ? null : profile.posType.posTypeRank,
      posTypeId: profile.posType == null ? null : profile.posType.id,
      posExecutiveName:
        position == null || position.posExecutive == null
          ? null
          : position.posExecutive.posExecutiveName,
      rootId: root == null ? null : root.id,
      root: root == null ? null : root.orgRootName,
      rootShortName: root == null ? null : root.orgRootShortName,
      child1Id: child1 == null ? null : child1.id,
      child1: child1 == null ? null : child1.orgChild1Name,
      child1ShortName: child1 == null ? null : child1.orgChild1ShortName,
      child2Id: child2 == null ? null : child2.id,
      child2: child2 == null ? null : child2.orgChild2Name,
      child2ShortName: child2 == null ? null : child2.orgChild2ShortName,
      child3Id: child3 == null ? null : child3.id,
      child3: child3 == null ? null : child3.orgChild3Name,
      child3ShortName: child3 == null ? null : child3.orgChild3ShortName,
      child4Id: child4 == null ? null : child4.id,
      child4: child4 == null ? null : child4.orgChild4Name,
      child4ShortName: child4 == null ? null : child4.orgChild4ShortName,
      node: null,
      nodeId: null,
      posNo: shortName,
      isPosmasterAct: data.length > 0,
      posmasterAct: data,
      salary: profile ? profile.amount : null,
      education:
        profile && profile.profileEducations.length > 0
          ? `${profile.profileEducations[0].degree ?? ""}/${profile.profileEducations[0].field ?? ""}`
          : "-",
    };

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

  /**
   * API ข้อมูลทะเบียนประวัติตาม keycloakid
   *
   * @summary ORG_065 - ข้อมูลทะเบียนประวัติตาม keycloakid (ADMIN) #70
   *
   */
  @Get("keycloakid/position/{id}")
  async getProfileByKeycloakid(@Request() request: RequestWithUser, @Path() id: string) {
    const profile = await this.profileRepo.findOne({
      where: { keycloak: id },
      select: ["id"],
    });
    if (!profile) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลบุคคลนี้ในระบบ");
    }
    //await new permission().PermissionOrgUserGet(request, "SYS_REGISTRY_OFFICER", profile.id); //ไม่แน่ใจOFFปิดไว้ก่อน
    return new HttpSuccess(profile);
  }

  /**
   * API ข้อมูลทะเบียนประวัติตาม citizenId
   *
   * @summary ORG_065 - ข้อมูลทะเบียนประวัติตาม citizenId (ADMIN) #70
   *
   * @param id หมายเลขประจำตัวประชาชน (citizenId)
   */
  @Get("citizenid/position/{id}")
  async getProfileByCitizenId(@Request() request: RequestWithUser, @Path() id: string) {
    const profile = await this.profileRepo.findOne({
      where: { citizenId: id },
      relations: [
        "posLevel",
        "posType",
        "current_holders",
        "current_holders.orgRoot",
        "profileSalary",
      ],
      order: {
        profileSalary: {
          order: "DESC",
        },
      },
    });
    if (!profile) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลบุคคลนี้ในระบบ");
    }
    //await new permission().PermissionOrgUserGet(request, "SYS_REGISTRY_OFFICER", profile.id); //ไม่แน่ใจOFFปิดไว้ก่อน

    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 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 _profile: any = {
      profileId: profile.id,
      prefix: profile.prefix,
      rank: profile.rank,
      firstName: profile.firstName,
      lastName: profile.lastName,
      citizenId: profile.citizenId,
      position: profile.position,
      leaveDate: profile.dateLeave,
      posMasterId: posMaster == null ? null : posMaster.id,
      posMasterNo: posMaster == null ? null : posMaster.posMasterNo,
      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,
      posTypeRank: profile.posType == null ? null : profile.posType.posTypeRank,
      posTypeId: profile.posType == null ? null : profile.posType.id,
      orgRevisionId: root == null ? null : root.orgRevisionId,
      rootId: root == null ? null : root.id,
      root: root == null ? null : root.orgRootName,
      rootShortName: root == null ? null : root.orgRootShortName,
      child1Id: child1 == null ? null : child1.id,
      child1: child1 == null ? null : child1.orgChild1Name,
      child1ShortName: child1 == null ? null : child1.orgChild1ShortName,
      child2Id: child2 == null ? null : child2.id,
      child2: child2 == null ? null : child2.orgChild2Name,
      child2ShortName: child2 == null ? null : child2.orgChild2ShortName,
      child3Id: child3 == null ? null : child3.id,
      child3: child3 == null ? null : child3.orgChild3Name,
      child3ShortName: child3 == null ? null : child3.orgChild3ShortName,
      child4Id: child4 == null ? null : child4.id,
      child4: child4 == null ? null : child4.orgChild4Name,
      child4ShortName: child4 == null ? null : child4.orgChild4ShortName,
      node: null,
      nodeId: null,
      amount: profile ? profile.amount : null,
      positionSalaryAmount: profile ? profile.positionSalaryAmount : null,
      mouthSalaryAmount: profile ? profile.mouthSalaryAmount : null,
    };

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

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

    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 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 _profile: any = {
      profileId: profile.id,
      prefix: profile.prefix,
      rank: profile.rank,
      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.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,
      posTypeRank: profile.posType == null ? null : profile.posType.posTypeRank,
      posTypeId: profile.posType == null ? null : profile.posType.id,
      rootId: root == null ? null : root.id,
      root: root == null ? null : root.orgRootName,
      rootShortName: root == null ? null : root.orgRootShortName,
      child1Id: child1 == null ? null : child1.id,
      child1: child1 == null ? null : child1.orgChild1Name,
      child1ShortName: child1 == null ? null : child1.orgChild1ShortName,
      child2Id: child2 == null ? null : child2.id,
      child2: child2 == null ? null : child2.orgChild2Name,
      child2ShortName: child2 == null ? null : child2.orgChild2ShortName,
      child3Id: child3 == null ? null : child3.id,
      child3: child3 == null ? null : child3.orgChild3Name,
      child3ShortName: child3 == null ? null : child3.orgChild3ShortName,
      child4Id: child4 == null ? null : child4.id,
      child4: child4 == null ? null : child4.orgChild4Name,
      child4ShortName: child4 == null ? null : child4.orgChild4ShortName,
      node: null,
      nodeId: null,
      education:
        profile && profile.profileEducations.length > 0
          ? `${profile.profileEducations[0].degree ?? ""}/${profile.profileEducations[0].field ?? ""}`
          : "-",
    };

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

  /**
   * API ค้นหาข้อมูลทะเบียนประวัติ
   *
   * @summary ORG_065 - ค้นหาข้อมูลทะเบียนประวัติ (ADMIN) #70
   *
   */
  @Post("search-personal")
  async getProfileBySearchKeyword(
    @Query("page") page: number = 1,
    @Query("pageSize") pageSize: number = 10,
    @Body()
    body: {
      fieldName: string;
      keyword?: string;
    },
  ) {
    let findProfile: any;
    let total: any;
    const skip = (page - 1) * pageSize;
    const take = pageSize;
    switch (body.fieldName) {
      case "citizenId":
        [findProfile, total] = await this.profileRepo.findAndCount({
          where: { citizenId: Like(`%${body.keyword}%`) },
          relations: [
            "posType",
            "posLevel",
            "current_holders",
            "profileSalary",
            "current_holders.orgRoot",
            "current_holders.orgChild1",
            "current_holders.orgChild2",
            "current_holders.orgChild3",
            "current_holders.orgChild4",
          ],
          skip,
          take,
        });
        break;

      case "firstname":
        [findProfile, total] = await this.profileRepo.findAndCount({
          where: { firstName: Like(`%${body.keyword}%`) },
          relations: [
            "posType",
            "posLevel",
            "current_holders",
            "profileSalary",
            "current_holders.orgRoot",
            "current_holders.orgChild1",
            "current_holders.orgChild2",
            "current_holders.orgChild3",
            "current_holders.orgChild4",
          ],
          skip,
          take,
        });
        break;

      case "lastname":
        [findProfile, total] = await this.profileRepo.findAndCount({
          where: { lastName: Like(`%${body.keyword}%`) },
          relations: [
            "posType",
            "posLevel",
            "current_holders",
            "profileSalary",
            "current_holders.orgRoot",
            "current_holders.orgChild1",
            "current_holders.orgChild2",
            "current_holders.orgChild3",
            "current_holders.orgChild4",
          ],
          skip,
          take,
        });
        break;

      default:
        [findProfile, total] = await this.profileRepo.findAndCount({
          relations: [
            "posType",
            "posLevel",
            "current_holders",
            "profileSalary",
            "current_holders.orgRoot",
            "current_holders.orgChild1",
            "current_holders.orgChild2",
            "current_holders.orgChild3",
            "current_holders.orgChild4",
          ],
          skip,
          take,
        });
        break;
    }

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

    const mapDataProfile = await Promise.all(
      findProfile.map(async (item: Profile) => {
        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;

        let salary: any = "";
        if (item != null && item.profileSalary != null && item.profileSalary.length > 0) {
          let _salary: any = item.profileSalary.sort(
            (a, b) =>
              (b.date == null ? 0 : b.date.getTime()) - (a.date == null ? 0 : a.date.getTime()),
          );
          if (_salary.length > 0) {
            salary = _salary[0];
          }
        }

        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.profileEducationRepository.findOne({
          where: { profileId: item.id },
          order: { endDate: "DESC" },
        });

        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.orgRootShortName,
          salary: salary == "" ? "" : salary.amount,
          root: rootHolder?.orgRootName ?? null,
          rootId: rootHolder?.id ?? null,
          rootShortName: rootHolder?.orgRootShortName ?? null,
          child1: child1Holder?.orgChild1Name ?? null,
          child1Id: child1Holder?.id ?? null,
          child1ShortName: child1Holder?.orgChild1ShortName ?? null,
          child2: child2Holder?.orgChild2Name ?? null,
          child2Id: child2Holder?.id ?? null,
          child2ShortName: child2Holder?.orgChild2ShortName ?? null,
          child3: child3Holder?.orgChild3Name ?? null,
          child3Id: child3Holder?.id ?? null,
          child3ShortName: child3Holder?.orgChild3ShortName ?? null,
          child4: child4Holder?.orgChild4Name ?? null,
          child4Id: child4Holder?.id ?? null,
          child4ShortName: child4Holder?.orgChild4ShortName ?? null,
          posMasterNo: posMasterNo ?? null,
          posTypeId: item.posTypeId,
          posTypeName: item.posType?.posTypeName,
          posLevelId: item.posLevelId,
          posLevelName: item.posLevel?.posLevelName,
          educationDegree:
            latestProfileEducation != null && latestProfileEducation.educationLevel != null
              ? latestProfileEducation.educationLevel
              : null,
          // ? {
          //     id: latestProfileEducation.id,
          //     degree: latestProfileEducation.degree,
          //     country: latestProfileEducation.country,
          //     duration: latestProfileEducation.duration,
          //     durationYear: latestProfileEducation.durationYear,
          //     field: latestProfileEducation.field,
          //     finishDate: latestProfileEducation.finishDate,
          //     fundName: latestProfileEducation.fundName,
          //     gpa: latestProfileEducation.gpa,
          //     institute: latestProfileEducation.institute,
          //     other: latestProfileEducation.other,
          //     startDate: latestProfileEducation.startDate,
          //     endDate: latestProfileEducation.endDate,
          //     educationLevel: latestProfileEducation.educationLevel,
          //     positionPath: latestProfileEducation.positionPath,
          //     positionPathId: latestProfileEducation.positionPathId,
          //     isDate: latestProfileEducation.isDate,
          //     isEducation: latestProfileEducation.isEducation,
          //     note: latestProfileEducation.note,
          //   }
          // : 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: PosMaster | null = null;
    let findTSAB: PosMaster | null = null;
    //หาผู้บังคับบัญชาที่เหนือขึ้นไปอีก 1 ขั้น
    if (node !== 0) {
      findOSAB = await AppDataSource.getRepository(PosMaster)
        .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(PosMaster)
        .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("citizenId/{id}")
  async checkCitizenIdProfile(
    @Path() id: string,
    @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,
    };
    const isProbation: boolean = true;
    if (!request.user.role.includes("SUPER_ADMIN")) {
      _data = await new permission().PermissionOrgCreate(request, "SYS_PROBATION");
    }
    const [findProfile, total] = await AppDataSource.getRepository(Profile)
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.profileSalary", "profileSalary")
      .leftJoinAndSelect("profile.posLevel", "posLevel")
      .leftJoinAndSelect("profile.posType", "posType")
      .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")
      .leftJoinAndSelect("current_holders.positions", "positions")
      .leftJoinAndSelect("positions.posExecutive", "posExecutive")
      .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 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(`profile.prefix LIKE :keyword and profile.isProbation = ${isProbation}`, {
            keyword: `%${body.keyword}%`,
          })
            .orWhere(`profile.firstName LIKE :keyword and profile.isProbation = ${isProbation}`, {
              keyword: `%${body.keyword}%`,
            })
            .orWhere(`profile.lastName LIKE :keyword and profile.isProbation = ${isProbation}`, {
              keyword: `%${body.keyword}%`,
            })
            .orWhere(`profile.position LIKE :keyword and profile.isProbation = ${isProbation}`, {
              keyword: `%${body.keyword}%`,
            })
            .orWhere(
              `posLevel.posLevelName LIKE :keyword and profile.isProbation = ${isProbation}`,
              {
                keyword: `%${body.keyword}%`,
              },
            )
            .orWhere(`posType.posTypeName LIKE :keyword and profile.isProbation = ${isProbation}`, {
              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 findRevision = await this.orgRevisionRepo.findOne({
      where: { orgRevisionIsCurrent: true },
    });
    if (!findRevision) {
      throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
    }

    const mapDataProfile = await Promise.all(
      findProfile.map(async (item: Profile) => {
        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 position =
          posMaster == null ||
          item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.positions == null ||
          item.current_holders?.find((x) => x.orgRevisionId == findRevision.id)?.positions.length ==
            0 ||
          item.current_holders
            .find((x) => x.orgRevisionId == findRevision.id)
            ?.positions?.find((position) => position.positionIsSelected == true) == null
            ? null
            : item.current_holders
                .find((x) => x.orgRevisionId == findRevision.id)
                ?.positions?.find((position) => position.positionIsSelected == true);
        const posExecutive =
          position == null ||
          item.current_holders
            .find((x) => x.orgRevisionId == findRevision.id)
            ?.positions?.find((position) => position.positionIsSelected == true)?.posExecutive ==
            null ||
          item.current_holders
            .find((x) => x.orgRevisionId == findRevision.id)
            ?.positions?.find((position) => position.positionIsSelected == true)?.posExecutive
            ?.posExecutiveName == null
            ? null
            : item.current_holders
                .find((x) => x.orgRevisionId == findRevision.id)
                ?.positions?.find((position) => position.positionIsSelected == true)?.posExecutive
                .posExecutiveName;

        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;

        return {
          id: item.id,
          prefix: item.prefix,
          rank: item.rank,
          firstName: item.firstName,
          lastName: item.lastName,
          position: item.position,
          idcard: item.citizenId,
          refCommandNo:
            item.profileSalary.sort((a, b) => b.order - a.order).length == 0
              ? null
              : item.profileSalary.sort((a, b) => b.order - a.order)[0].refCommandNo,
          posLevelName: item.posLevel == null ? null : item.posLevel.posLevelName,
          posTypeName: item.posType == null ? null : item.posType.posTypeName,
          posNo: posMaster == null ? null : `${posMaster.posMasterNo}${shortName}`,
          positionField: position == null ? null : position.positionField,
          positionArea: position == null ? null : position.positionArea,
          posExecutiveName: posExecutive,
          positionExecutiveField: position == null ? null : position.positionExecutiveField,
          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,
          root:
            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
                  ?.id,
          orgChild1:
            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?.id,
          orgChild2:
            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?.id,
          orgChild3:
            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?.id,
          orgChild4:
            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?.id,
        };
      }),
    );

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

  /**
   * API ค้นหาข้อมูลทะเบียนประวัติ เกษียณข้าราชการ
   *
   * @summary ค้นหาข้อมูลทะเบียนประวัติ เกษียณข้าราชการ (ADMIN)
   *
   */
  @Post("retire")
  async getProfileBySearchKeywordRetire(
    @Body()
    body: {
      page: number;
      pageSize: number;
      keyword?: string;
    },
  ) {
    let conditionFullName =
      "CONCAT(profile.prefix, profile.firstName, ' ', profile.lastName) LIKE :keyword";
    const [findProfile, total] = await AppDataSource.getRepository(Profile)
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.posLevel", "posLevel")
      .leftJoinAndSelect("profile.posType", "posType")
      .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")
      .leftJoinAndSelect("current_holders.positions", "positions")
      .leftJoinAndSelect("positions.posExecutive", "posExecutive")
      .where(`profile.position LIKE :keyword`, {
        keyword: `%${body.keyword}%`,
      })
      .orWhere(`profile.prefix LIKE :keyword`, {
        keyword: `%${body.keyword}%`,
      })
      .orWhere(`profile.firstName LIKE :keyword`, {
        keyword: `%${body.keyword}%`,
      })
      .orWhere(`profile.lastName LIKE :keyword`, {
        keyword: `%${body.keyword}%`,
      })
      .orWhere(`posLevel.posLevelName LIKE :keyword`, {
        keyword: `%${body.keyword}%`,
      })
      .orWhere(`posType.posTypeName LIKE :keyword`, {
        keyword: `%${body.keyword}%`,
      })
      .orWhere(conditionFullName, {
        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 findRevision = await this.orgRevisionRepo.findOne({
      where: { orgRevisionIsCurrent: true },
    });
    if (!findRevision) {
      throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
    }

    const mapDataProfile = await Promise.all(
      findProfile.map(async (item: Profile) => {
        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 position =
          posMaster == null ||
          item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.positions == null ||
          item.current_holders?.find((x) => x.orgRevisionId == findRevision.id)?.positions.length ==
            0 ||
          item.current_holders
            .find((x) => x.orgRevisionId == findRevision.id)
            ?.positions?.find((position) => position.positionIsSelected == true) == null
            ? null
            : item.current_holders
                .find((x) => x.orgRevisionId == findRevision.id)
                ?.positions?.find((position) => position.positionIsSelected == true);
        const posExecutive =
          position == null ||
          item.current_holders
            .find((x) => x.orgRevisionId == findRevision.id)
            ?.positions?.find((position) => position.positionIsSelected == true)?.posExecutive ==
            null ||
          item.current_holders
            .find((x) => x.orgRevisionId == findRevision.id)
            ?.positions?.find((position) => position.positionIsSelected == true)?.posExecutive
            ?.posExecutiveName == null
            ? null
            : item.current_holders
                .find((x) => x.orgRevisionId == findRevision.id)
                ?.positions?.find((position) => position.positionIsSelected == true)?.posExecutive
                .posExecutiveName;

        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;

        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: `${posMaster == null ? null : posMaster.posMasterNo}${shortName}`,
          positionField: position == null ? null : position.positionField,
          positionArea: position == null ? null : position.positionArea,
          posExecutiveName: posExecutive,
          positionExecutiveField: position == null ? null : position.positionExecutiveField,
          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;
    },
  ) {
    const findRevision = await this.orgRevisionRepo.findOne({
      where: { orgRevisionIsCurrent: true },
    });
    if (!findRevision) {
      throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
    }

    const [findPosMaster, total] = await AppDataSource.getRepository(PosMaster)
      .createQueryBuilder("posMaster")
      .leftJoinAndSelect("posMaster.current_holder", "current_holder")
      .leftJoinAndSelect("posMaster.orgRoot", "orgRoot")
      .leftJoinAndSelect("posMaster.orgChild1", "orgChild1")
      .leftJoinAndSelect("posMaster.orgChild2", "orgChild2")
      .leftJoinAndSelect("posMaster.orgChild3", "orgChild3")
      .leftJoinAndSelect("posMaster.orgChild4", "orgChild4")
      .leftJoinAndSelect("posMaster.positions", "positions")
      .leftJoinAndSelect("positions.posExecutive", "posExecutive")
      .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("posMaster.orgRootId = :rootId", { rootId: body.rootId });
        }
        qb.andWhere("posMaster.current_holderId IS NOT NULL");
        qb.andWhere("posMaster.orgRevisionId = :orgRevisionId", {
          orgRevisionId: findRevision?.id,
        });
      })
      .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 != ""
                ? "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 != ""
                ? "posLevel.posLevelName LIKE :keyword"
                : "1=1",
              {
                keyword: `%${body.keyword}%`,
              },
            );
        }),
      )
      .orderBy("current_holder.citizenId", "ASC")
      .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 posExecutive =
        item.positions == null ||
        item.positions?.find((position) => position.positionIsSelected == true) == null ||
        item.positions?.find((position) => position.positionIsSelected == true)?.posExecutive ==
          null ||
        item.positions?.find((position) => position.positionIsSelected == true)?.posExecutive
          ?.posExecutiveName == null
          ? null
          : item.positions?.find((position) => position.positionIsSelected == true)?.posExecutive
              .posExecutiveName;

      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;
      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,
        prefix: item.current_holder.prefix,
        rank: item.current_holder.rank,
        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,
        posLevel:
          item.current_holder.posLevel == null ? null : item.current_holder.posLevel.posLevelName,
        posExecutive: posExecutive,
        amount: amount ? amount : null,
        // revisionId: item.orgRevisionId,
        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: isSpecial,
      };
    });

    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: RequestWithUser,
  ) {
    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 posMaster = await this.posMasterRepo.findOne({
      where: {
        current_holderId: profile.id,
        orgRevisionId: revisionId,
      },
    });
    const position = await this.positionRepository.findOne({
      relations: ["posExecutive"],
      where: {
        posMasterId: posMaster?.id,
      },
    });

    const _profile = {
      profileId: profile.id,
      prefix: profile.prefix,
      rank: profile.rank,
      firstName: profile.firstName,
      lastName: profile.lastName,
      citizenId: profile.citizenId,
      position: profile.position,
      isDirector: posMaster?.isDirector ?? null,
      isProbation: profile.isProbation,
      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,
      posTypeRank: profile.posType == null ? null : profile.posType.posTypeRank,
      posTypeId: profile.posType == null ? null : profile.posType.id,
      posExecutiveName:
        position == null || position.posExecutive == null
          ? null
          : position.posExecutive.posExecutiveName,
      posExecutivePriority:
        position == null || position.posExecutive == null
          ? null
          : position.posExecutive.posExecutivePriority,
      posExecutiveId:
        position == null || position.posExecutive == null ? null : position.posExecutive.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,
      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,
      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,
      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,
      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,
      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().PermissionOrgUserGet(req, "SYS_REGISTRY_OFFICER", id); //ไม่แน่ใจOFFปิดไว้ก่อน
    const profiles = await this.profileRepo
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.posLevel", "posLevel")
      .leftJoinAndSelect("profile.posType", "posType")
      .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")
      .leftJoinAndSelect("current_holders.positions", "positions")
      .leftJoinAndSelect("positions.posExecutive", "posExecutive")
      .where("YEAR(profile.dateRetire) = :year", { year })
      .getMany();

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

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

    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 position =
        posMaster == null ||
        item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.positions == null ||
        item.current_holders?.find((x) => x.orgRevisionId == findRevision.id)?.positions.length ==
          0 ||
        item.current_holders
          .find((x) => x.orgRevisionId == findRevision.id)
          ?.positions?.find((position) => position.positionIsSelected == true) == null
          ? null
          : item.current_holders
              .find((x) => x.orgRevisionId == findRevision.id)
              ?.positions?.find((position) => position.positionIsSelected == true);
      const posExecutive =
        position == null ||
        item.current_holders
          .find((x) => x.orgRevisionId == findRevision.id)
          ?.positions?.find((position) => position.positionIsSelected == true)?.posExecutive ==
          null ||
        item.current_holders
          .find((x) => x.orgRevisionId == findRevision.id)
          ?.positions?.find((position) => position.positionIsSelected == true)?.posExecutive
          ?.posExecutiveName == null
          ? null
          : item.current_holders
              .find((x) => x.orgRevisionId == findRevision.id)
              ?.positions?.find((position) => position.positionIsSelected == true)?.posExecutive
              .posExecutiveName;
      const posExecutiveId =
        position == null || position.posExecutive == null ? null : position.posExecutive.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,
        posExecutiveId: posExecutiveId,
        posExecutiveName: posExecutive,
        node: node,
        nodeId: nodeId,
        nodeShortName: nodeShortName,
      };
    });
    return new HttpSuccess(formattedData);
  }

  /**
   * API อัพเดทเกษียณ
   *
   * @summary อัพเดทเกษียณ  (ADMIN)
   *
   * @param {string} id  Id ทะเบียนประวัติ
   */
  @Post("leave/{id}")
  async updateLeaveUser(
    @Path() id: string,
    @Body()
    requestBody: { isLeave: boolean; leaveReason?: any; dateLeave?: any },
    @Request() request: RequestWithUser,
  ) {
    const profile = await this.profileRepo.findOne({
      where: { id: id },
    });
    if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    const before = structuredClone(profile);
    profile.isLeave = requestBody.isLeave;
    profile.leaveReason = requestBody.leaveReason;
    profile.dateLeave = requestBody.dateLeave;
    if (requestBody.isLeave == true) {
      await removeProfileInOrganize(profile.id, "OFFICER");
    }
    await this.profileRepo.save(profile, { data: request });
    setLogDataDiff(request, { before, after: profile });

    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;
    },
  ) {
    let findProfile: any;
    let total: any;
    const skip = (page - 1) * pageSize;
    const take = pageSize;
    switch (body.fieldName) {
      case "citizenId":
        [findProfile, total] = await this.profileRepo.findAndCount({
          where: {
            keycloak: IsNull(),
            citizenId: Like(`%${body.keyword}%`),
          },
          relations: ["posType", "posLevel", "current_holders", "profileSalary"],
          skip,
          take,
        });
        break;

      case "firstname":
        [findProfile, total] = await this.profileRepo.findAndCount({
          where: {
            keycloak: IsNull(),
            firstName: Like(`%${body.keyword}%`),
          },
          relations: ["posType", "posLevel", "current_holders", "profileSalary"],
          skip,
          take,
        });
        break;

      case "lastname":
        [findProfile, total] = await this.profileRepo.findAndCount({
          where: {
            keycloak: IsNull(),
            lastName: Like(`%${body.keyword}%`),
          },
          relations: ["posType", "posLevel", "current_holders", "profileSalary"],
          skip,
          take,
        });
        break;

      default:
        [findProfile, total] = await this.profileRepo.findAndCount({
          where: {
            keycloak: IsNull(),
          },
          relations: ["posType", "posLevel", "current_holders", "profileSalary"],
          skip,
          take,
        });
        break;
    }

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

    const mapDataProfile = await Promise.all(
      findProfile.map(async (item: Profile) => {
        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;

        let salary: any = "";
        if (item != null && item.profileSalary != null && item.profileSalary.length > 0) {
          let _salary: any = item.profileSalary.sort(
            (a, b) =>
              (b.date == null ? 0 : b.date.getTime()) - (a.date == null ? 0 : a.date.getTime()),
          );
          if (_salary.length > 0) {
            salary = _salary[0];
          }
        }

        const posMasterNo = item.current_holders?.find(
          (x) => x.orgRevisionId == findRevision.id,
        )?.posMasterNo;

        const latestProfileEducation = await this.profileEducationRepository.findOne({
          where: { profileId: item.id },
          order: { endDate: "DESC" },
        });

        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.orgRootShortName,
          salary: salary == "" ? "" : salary.amount,
          posMasterNo: posMasterNo ?? null,
          posTypeId: item.posTypeId,
          posTypeName: item.posType?.posTypeName,
          posLevelId: item.posLevelId,
          posLevelName: item.posLevel?.posLevelName,
          educationDegree:
            latestProfileEducation != null && latestProfileEducation.educationLevel != null
              ? latestProfileEducation.educationLevel
              : null,
        };
      }),
    );

    return new HttpSuccess({ data: mapDataProfile, total });
  }
  /**
   * API ค้นหาข้อมูลทะเบียนประวัติที่เกี่ยวข้องคำสั่ง
   *
   * @summary  ค้นหาข้อมูลทะเบียนประวัติที่เกี่ยวข้องคำสั่ง
   *
   */
  @Post("search/profile/command")
  async searchProfileBycommand(
    @Query("page") page: number = 1,
    @Query("pageSize") pageSize: number = 10,
    @Body()
    body: {
      commandType: string;
      posno: string;
      year: number;
    },
  ) {
    const [profiles, total] = await this.profileRepo
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.profileSalary", "profileSalary")
      .where("YEAR(profileSalary.date) = :year", { year: body.year })
      .where("profileSalary.refCommandNo LIKE :refCommandNo", {
        refCommandNo: `%${body.posno}%`,
      })
      //   .andWhere("profileSalary.commandType LIKE :commandType", {
      //     commandType: `${body.commandType}`,
      //   })
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .distinct(true) // Ensure unique profiles
      .getManyAndCount();
    const _profiles = profiles.map((_data) => ({
      id: _data.id,
      fullName: `${_data.prefix}${_data.firstName} ${_data.lastName}`,
      citizenId: _data.citizenId,
      posNo: _data.profileSalary.filter((x) => x.id != null)[0].refCommandNo,
      position: _data.profileSalary.filter((x) => x.id != null)[0].position,
    }));

    return new HttpSuccess({ data: _profiles, total });
  }
  /**
   *
   * @summary ปรับคนเป็นทดลองงาน  (ADMIN)
   *
   */
  @Get("probation/{id}")
  async getProbationProfile(@Path() id: string) {
    const profile = await this.profileRepo.findOne({
      where: { id },
    });

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

    profile.isProbation = true;
    await this.profileRepo.save(profile);
    return new HttpSuccess(profile);
  }

  /**
   * API สร้างทะเบียนประวัติใหม่
   *
   * @summary ORG_065 - สร้างทะเบียนประวัติใหม่ (ADMIN) #XXX
   *
   */
  @Post("all/dump-db")
  async createProfileAllDump(
    @Request() request: RequestWithUser,
    @Body() body: CreateProfileAllFields,
  ) {
    const citizen = await this.profileRepo.findOne({
      where: { citizenId: body.citizenId },
      select: ["id"],
    });
    if (citizen) return new HttpSuccess(citizen.id);
    const _null: any = null;
    const profile: Profile = Object.assign(new Profile(), body);
    if (body && body.posLevelId) {
      const findPosLevel = await this.posLevelRepo.findOne({
        where: { posLevelName: body.posLevelId },
        select: ["id", "posLevelName"],
      });
      if (findPosLevel) {
        profile.posLevelId = findPosLevel.id;
      } else {
        profile.posLevelId = _null;
      }
    } else {
      profile.posLevelId = _null;
    }
    if (body && body.posTypeId) {
      const findPosType = await this.posTypeRepo.findOne({
        where: { posTypeName: body.posTypeId },
        select: ["id", "posTypeName"],
      });
      if (findPosType) {
        profile.posTypeId = findPosType.id;
      } else {
        profile.posTypeId = _null;
      }
    } else {
      profile.posTypeId = _null;
    }
    // if (body && body.prefix) {
    //   const findPrefix = await this.prefixRepo.findOne({
    //     where: { name: body.prefix },
    //     select: ["id", "name"],
    //   });
    //   if (findPrefix) {
    //     profile.prefix = findPrefix.id;
    //   } else {
    //     profile.prefix = _null;
    //   }
    // } else {
    //   profile.prefix = _null;
    // }
    //current
    if (body && body.currentProvinceId) {
      const findProvince = await this.provinceRepo.findOne({
        where: { name: body.currentProvinceId },
        select: ["id", "name"],
      });
      if (findProvince) {
        profile.currentProvinceId = findProvince.id;
      } else {
        profile.currentProvinceId = _null;
      }
    } else {
      profile.currentProvinceId = _null;
    }
    if (body && body.currentDistrictId) {
      const findDistrict = await this.districtRepo.findOne({
        where: { name: body.currentDistrictId },
        select: ["id", "name"],
      });
      if (findDistrict) {
        profile.currentDistrictId = findDistrict.id;
      } else {
        profile.currentDistrictId = _null;
      }
    } else {
      profile.currentDistrictId = _null;
    }
    if (body && body.currentSubDistrictId) {
      const findSubDistrict = await this.subDistrictRepo.findOne({
        where: { name: body.currentSubDistrictId },
        select: ["id", "name"],
      });
      if (findSubDistrict) {
        profile.currentSubDistrictId = findSubDistrict.id;
      } else {
        profile.currentSubDistrictId = _null;
      }
    } else {
      profile.currentSubDistrictId = _null;
    }
    //register
    if (body && body.registrationProvinceId) {
      const findProvince_regis = await this.provinceRepo.findOne({
        where: { name: body.registrationProvinceId },
        select: ["id", "name"],
      });
      if (findProvince_regis) {
        profile.registrationProvinceId = findProvince_regis.id;
      } else {
        profile.registrationProvinceId = _null;
      }
    } else {
      profile.registrationProvinceId = _null;
    }
    if (body && body.registrationDistrictId) {
      const findDistrict_regis = await this.districtRepo.findOne({
        where: { name: body.registrationDistrictId },
        select: ["id", "name"],
      });
      if (findDistrict_regis) {
        profile.registrationDistrictId = findDistrict_regis.id;
      } else {
        profile.registrationDistrictId = _null;
      }
    } else {
      profile.registrationDistrictId = _null;
    }
    if (body && body.registrationSubDistrictId) {
      const findSubDistrict_regis = await this.subDistrictRepo.findOne({
        where: { name: body.registrationSubDistrictId },
        select: ["id", "name"],
      });
      if (findSubDistrict_regis) {
        profile.registrationSubDistrictId = findSubDistrict_regis.id;
      } else {
        profile.registrationSubDistrictId = _null;
      }
    } else {
      profile.registrationSubDistrictId = _null;
    }

    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();
    // return new HttpSuccess(profile);
    await this.profileRepo.save(profile);
    return new HttpSuccess(profile.id);
  }
  /**
   *
   * @summary  (ADMIN)
   *
   */
  @Get("retireDate/mock")
  async calRetireDate() {
    const profile = await this.profileRepo.find({ relations: ["profileSalary"] });
    const _null: any = null;
    const profiles = profile.map((_data) => ({
      ..._data,
      dateRetire: _data.birthDate == null ? _null : calculateRetireDate(_data.birthDate),
      dateRetireLaw: _data.birthDate == null ? _null : calculateRetireLaw(_data.birthDate),
    }));
    await this.profileRepo.save(profiles);
    return new HttpSuccess();
  }
  /**
   *
   * @summary  (ADMIN)
   *
   */
  @Get("gensalary/latest")
  async calSalaryDate() {
    const profile = await this.profileRepo.find();
    const _null: any = null;
    const profiles = await Promise.all(
      profile.map(async (_data) => {
        const salary = await this.salaryRepository.findOne({
          where: {
            profileId: _data.id,
          },
          order: { order: "DESC" },
        });
        const type = await this.posTypeRepo.findOne({
          where: {
            posTypeName: salary?.positionType ?? "",
          },
        });
        const level = await this.posLevelRepo.findOne({
          where: {
            posLevelName: salary?.positionLevel ?? "",
          },
        });
        return {
          ..._data,
          position: salary?.position ?? _null,
          posLevelId: level?.id ?? _null,
          posTypeId: type?.id ?? _null,
        };
      }),
    );
    await this.profileRepo.save(profiles);
    return new HttpSuccess();
  }
  /**
   *
   * @summary  (ADMIN)
   *
   */
  @Get("deleteprofile/all")
  async deleteHistoryLatest() {
    const [profile, total] = await this.profileRepo
      .createQueryBuilder("profile")
      .leftJoinAndSelect("profile.current_holders", "current_holders")
      .leftJoinAndSelect("profile.next_holders", "next_holders")
      .skip(1)
      .take(50)
      .getManyAndCount();

    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 ProfileHistory();

    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 ProfileHistory();

    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 }),
    ]);
    return new HttpSuccess();
  }

  @Post("noti-admin")
  public async notiAllAdmin(
    @Request() req: RequestWithUser,
    @Body()
    body: {
      subject: string;
      body: string;
    },
  ) {
    if (!req.user.role.includes("SUPER_ADMIN"))
      throw new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์ส่งข้อความ");
    const profileNoti = await this.profileRepo.find({
      where: {
        roleKeycloaks: {
          name: "ADMIN",
        },
      },
    });
    let _profileNoti = profileNoti.map((x) => ({
      receiverUserId: x.id,
      notiLink: "",
    }));
    console.log(profileNoti);
    await new CallAPI()
      .PostData(req, "/placement/noti/profiles", {
        subject: body.subject,
        body: body.body,
        receiverUserIds: _profileNoti,
        payload: "", //แนบไฟล์
        isSendMail: true,
        isSendInbox: true,
        isSendNotification: true,
      })
      .catch((error) => {
        console.error("Error calling API:", error);
      });

    return new HttpSuccess();
  }
}
