import {
  Body,
  Controller,
  Delete,
  Get,
  Patch,
  Path,
  Post,
  Request,
  Route,
  Security,
  Tags,
} from "tsoa";
import { AppDataSource } from "../database/data-source";
import { CreateProfileSalary, ProfileSalary, UpdateProfileSalary } from "../entities/ProfileSalary";
import HttpSuccess from "../interfaces/http-success";
import HttpStatus from "../interfaces/http-status";
import HttpError from "../interfaces/http-error";
import { ProfileSalaryHistory } from "../entities/ProfileSalaryHistory";
import { RequestWithUser } from "../middlewares/user";
import { Profile } from "../entities/Profile";
import { ProfileEmployee } from "../entities/ProfileEmployee";
import { In, IsNull, LessThan, MoreThan, Not } from "typeorm";
import permission from "../interfaces/permission";
import { setLogDataDiff } from "../interfaces/utils";
import { normalizeDurationSumSimple } from "../utils/tenure";
import {
  TenurePositionOfficer,
  CreateTenurePositionOfficer,
} from "../entities/TenurePositionOfficer";
import { TenureLevelOfficer, CreateTenureLevelOfficer } from "../entities/TenureLevelOfficer";
import {
  TenurePositionEmployee,
  CreateTenurePositionEmployee,
} from "../entities/TenurePositionEmployee";
import { TenureLevelEmployee, CreateTenureLevelEmployee } from "../entities/TenureLevelEmployee";
import {
  TenurePositionExecutiveOfficer,
  CreateTenurePositionExecutiveOfficer,
} from "../entities/TenurePositionExecutiveOfficer";
import { Command } from "../entities/Command";
import { OrgRoot } from "../entities/OrgRoot";
import { OrgRevision } from "../entities/OrgRevision";
import { Position } from "../entities/Position";
import Extension from "../interfaces/extension";
import { viewRegistryOfficer } from "../entities/view/viewRegistryOfficer";
import { viewRegistryEmployee } from "../entities/view/viewRegistryEmployee";
import { Registry } from "../entities/Registry";
import { RegistryEmployee } from "../entities/RegistryEmployee";
@Route("api/v1/org/profile/salary")
@Tags("ProfileSalary")
@Security("bearerAuth")
export class ProfileSalaryController extends Controller {
  private profileRepo = AppDataSource.getRepository(Profile);
  private profileEmployeeRepo = AppDataSource.getRepository(ProfileEmployee);
  private salaryRepo = AppDataSource.getRepository(ProfileSalary);
  private salaryHistoryRepo = AppDataSource.getRepository(ProfileSalaryHistory);
  private commandRepository = AppDataSource.getRepository(Command);
  private orgRootRepository = AppDataSource.getRepository(OrgRoot);
  private registryRepo = AppDataSource.getRepository(Registry);
  private registryEmployeeRepo = AppDataSource.getRepository(RegistryEmployee);

  @Get("TenurePositionOfficer")
  public async cronjobTenurePositionOfficer() {
    const CURRENT_DATE = await AppDataSource.query("SELECT CURRENT_DATE() as today");
    const baseCurrentDate = CURRENT_DATE[0].today;

    const profiles = await this.profileRepo.find({
      select: ["id", "position", "isLeave", "leaveDate"],
      where: { position: Not(IsNull()) },
    });

    const BATCH_SIZE = 50;
    let successCount = 0;
    let failCount = 0;
    const allData: CreateTenurePositionOfficer[] = [];

    for (let i = 0; i < profiles.length; i += BATCH_SIZE) {
      const batch = profiles.slice(i, Math.min(i + BATCH_SIZE, profiles.length));
      const results = await Promise.allSettled(
        batch.map((profile) =>
          this.processSingleProfileForTenurePositionOfficer(profile, baseCurrentDate),
        ),
      );

      results.forEach((result) => {
        if (result.status === "fulfilled" && result.value) {
          allData.push(result.value);
          successCount++;
        } else {
          failCount++;
        }
      });
    }

    await AppDataSource.transaction(async (transactionalEntityManager) => {
      await transactionalEntityManager.delete(TenurePositionOfficer, {});
      if (allData.length > 0) {
        const entities = allData.map((data) => {
          const entity = new TenurePositionOfficer();
          Object.assign(entity, data);
          return entity;
        });
        await transactionalEntityManager.save(TenurePositionOfficer, entities);
      }
    });

    return new HttpSuccess({
      message: `อัปเดต tenure position officer สำเร็จ`,
      total: profiles.length,
      success: successCount,
      failed: failCount,
    });
  }

  private async processSingleProfileForTenurePositionOfficer(
    profile: Pick<Profile, "id" | "position" | "isLeave" | "leaveDate">,
    baseCurrentDate: string,
  ): Promise<CreateTenurePositionOfficer | null> {
    try {
      let _currentDate = baseCurrentDate;
      if (profile.isLeave && profile.leaveDate) {
        _currentDate = Extension.toDateOnlyString(profile.leaveDate);
      }

      const position = await AppDataSource.query("CALL GetProfileSalaryPosition(?, ?)", [
        profile.id,
        _currentDate,
      ]);
      const _position = position.length > 0 ? position[0] : [];

      const mapPosition =
        _position.length > 1
          ? _position.slice(1).map((curr: any, index: number) => ({
              positionName: _position[index]?.positionName,
              year:
                curr.Years !== null && curr.Years !== undefined
                  ? Math.floor(Number(curr.Years))
                  : 0,
              month:
                curr.Months !== null && curr.Months !== undefined
                  ? Math.floor(Number(curr.Months))
                  : 0,
              day:
                curr.Days !== null && curr.Days !== undefined ? Math.floor(Number(curr.Days)) : 0,
            }))
          : [];

      const currentTenure = mapPosition.find((curr: any) => curr.positionName === profile.position);

      if (currentTenure) {
        const normalized = normalizeDurationSumSimple(
          currentTenure.year,
          currentTenure.month,
          currentTenure.day,
        );
        return {
          profileId: profile.id,
          positionName: currentTenure.positionName,
          days_diff: null,
          Years: normalized.years,
          Months: normalized.months,
          Days: normalized.days,
        };
      }
      return null;
    } catch (error) {
      return null;
    }
  }
  @Get("TenurePositionEmployee")
  public async cronjobTenurePositionEmployee() {
    const CURRENT_DATE = await AppDataSource.query("SELECT CURRENT_DATE() as today");
    const baseCurrentDate = CURRENT_DATE[0].today;

    const profiles = await this.profileEmployeeRepo.find({
      select: ["id", "position", "isLeave", "leaveDate"],
      where: { position: Not(IsNull()) },
    });

    const BATCH_SIZE = 50;
    let successCount = 0;
    let failCount = 0;
    const allData: CreateTenurePositionEmployee[] = [];

    for (let i = 0; i < profiles.length; i += BATCH_SIZE) {
      const batch = profiles.slice(i, Math.min(i + BATCH_SIZE, profiles.length));
      const results = await Promise.allSettled(
        batch.map((profile) =>
          this.processSingleProfileForTenurePositionEmployee(profile, baseCurrentDate),
        ),
      );

      results.forEach((result) => {
        if (result.status === "fulfilled" && result.value) {
          allData.push(result.value);
          successCount++;
        } else {
          failCount++;
        }
      });
    }

    await AppDataSource.transaction(async (transactionalEntityManager) => {
      await transactionalEntityManager.delete(TenurePositionEmployee, {});
      if (allData.length > 0) {
        const entities = allData.map((data) => {
          const entity = new TenurePositionEmployee();
          Object.assign(entity, data);
          return entity;
        });
        await transactionalEntityManager.save(TenurePositionEmployee, entities);
      }
    });

    return new HttpSuccess({
      message: `อัปเดต tenure position employee สำเร็จ`,
      total: profiles.length,
      success: successCount,
      failed: failCount,
    });
  }

  private async processSingleProfileForTenurePositionEmployee(
    profile: Pick<ProfileEmployee, "id" | "position" | "isLeave" | "leaveDate">,
    baseCurrentDate: string,
  ): Promise<CreateTenurePositionEmployee | null> {
    try {
      let _currentDate = baseCurrentDate;
      if (profile.isLeave && profile.leaveDate) {
        _currentDate = Extension.toDateOnlyString(profile.leaveDate);
      }

      const position = await AppDataSource.query("CALL GetProfileEmployeeSalaryPosition(?, ?)", [
        profile.id,
        _currentDate,
      ]);
      const _position = position.length > 0 ? position[0] : [];

      const mapPosition =
        _position.length > 1
          ? _position.slice(1).map((curr: any, index: number) => ({
              positionName: _position[index]?.positionName,
              year:
                curr.Years !== null && curr.Years !== undefined
                  ? Math.floor(Number(curr.Years))
                  : 0,
              month:
                curr.Months !== null && curr.Months !== undefined
                  ? Math.floor(Number(curr.Months))
                  : 0,
              day:
                curr.Days !== null && curr.Days !== undefined ? Math.floor(Number(curr.Days)) : 0,
            }))
          : [];

      const currentTenure = mapPosition.find((curr: any) => curr.positionName === profile.position);

      if (currentTenure) {
        const normalized = normalizeDurationSumSimple(
          currentTenure.year,
          currentTenure.month,
          currentTenure.day,
        );
        return {
          profileEmployeeId: profile.id,
          positionName: currentTenure.positionName,
          days_diff: null,
          Years: normalized.years,
          Months: normalized.months,
          Days: normalized.days,
        };
      }
      return null;
    } catch (error) {
      return null;
    }
  }
  @Get("TenureLevelOfficer")
  public async cronjobTenureLevelOfficer() {
    const CURRENT_DATE = await AppDataSource.query("SELECT CURRENT_DATE() as today");
    const baseCurrentDate = CURRENT_DATE[0].today;

    const profiles = await this.profileRepo.find({
      relations: ["posLevel", "posType"],
      select: ["id", "isLeave", "leaveDate", "posLevel", "posType"],
      where: {
        posLevel: Not(IsNull()),
        posType: Not(IsNull()),
      },
    });

    const BATCH_SIZE = 50;
    let successCount = 0;
    let failCount = 0;
    const allData: CreateTenureLevelOfficer[] = [];

    for (let i = 0; i < profiles.length; i += BATCH_SIZE) {
      const batch = profiles.slice(i, Math.min(i + BATCH_SIZE, profiles.length));
      const results = await Promise.allSettled(
        batch.map((profile) =>
          this.processSingleProfileForTenureLevelOfficer(profile, baseCurrentDate),
        ),
      );

      results.forEach((result) => {
        if (result.status === "fulfilled" && result.value) {
          allData.push(result.value);
          successCount++;
        } else {
          failCount++;
        }
      });
    }

    await AppDataSource.transaction(async (transactionalEntityManager) => {
      await transactionalEntityManager.delete(TenureLevelOfficer, {});
      if (allData.length > 0) {
        const entities = allData.map((data) => {
          const entity = new TenureLevelOfficer();
          Object.assign(entity, data);
          return entity;
        });
        await transactionalEntityManager.save(TenureLevelOfficer, entities);
      }
    });

    return new HttpSuccess({
      message: `อัปเดต tenure level officer สำเร็จ`,
      total: profiles.length,
      success: successCount,
      failed: failCount,
    });
  }

  private async processSingleProfileForTenureLevelOfficer(
    profile: Pick<Profile, "id" | "isLeave" | "leaveDate" | "posLevel" | "posType"> & {
      posLevel?: { posLevelName?: string } | null;
      posType?: { posTypeName?: string } | null;
    },
    baseCurrentDate: string,
  ): Promise<CreateTenureLevelOfficer | null> {
    try {
      let _currentDate = baseCurrentDate;
      if (profile.isLeave && profile.leaveDate) {
        _currentDate = Extension.toDateOnlyString(profile.leaveDate);
      }

      const positionLevel = await AppDataSource.query("CALL GetProfileSalaryLevel(?, ?)", [
        profile.id,
        _currentDate,
      ]);
      const _positionLevel = positionLevel.length > 0 ? positionLevel[0] : [];

      const mapPositionLevel =
        _positionLevel.length > 1
          ? _positionLevel.slice(1).map((curr: any, index: number) => ({
              days_diff: curr.days_diff,
              positionType: _positionLevel[index]?.positionType,
              positionLevel: _positionLevel[index]?.positionLevel,
              positionCee: _positionLevel[index]?.positionCee,
              year:
                curr.Years !== null && curr.Years !== undefined
                  ? Math.floor(Number(curr.Years))
                  : 0,
              month:
                curr.Months !== null && curr.Months !== undefined
                  ? Math.floor(Number(curr.Months))
                  : 0,
              day:
                curr.Days !== null && curr.Days !== undefined ? Math.floor(Number(curr.Days)) : 0,
            }))
          : [];

      const calDayDiff = mapPositionLevel
        .filter(
          (curr: any) =>
            curr.positionLevel === (profile.posLevel?.posLevelName ?? null) &&
            curr.positionType === (profile.posType?.posTypeName ?? null),
        )
        .reduce(
          (acc: any, curr: any) => {
            acc.days_diff += Number(curr.days_diff) || 0;
            acc.positionType = curr.positionType;
            acc.positionLevel = curr.positionLevel;
            acc.positionCee = curr.positionCee;
            acc.year += curr.year;
            acc.month += curr.month;
            acc.day += curr.day;
            return acc;
          },
          {
            days_diff: 0,
            positionType: null,
            positionLevel: null,
            positionCee: null,
            year: 0,
            month: 0,
            day: 0,
          },
        );

      const normalized = normalizeDurationSumSimple(
        calDayDiff.year,
        calDayDiff.month,
        calDayDiff.day,
      );

      return {
        profileId: profile.id,
        positionType: calDayDiff.positionType,
        positionLevel: calDayDiff.positionLevel,
        positionCee: calDayDiff.positionCee,
        days_diff: calDayDiff.days_diff,
        Years: profile.posLevel == null ? 0 : normalized.years,
        Months: profile.posLevel == null ? 0 : normalized.months,
        Days: profile.posLevel == null ? 0 : normalized.days,
      };
    } catch (error) {
      return null;
    }
  }
  @Get("TenureLevelEmployee")
  public async cronjobTenureLevelEmployee() {
    const CURRENT_DATE = await AppDataSource.query("SELECT CURRENT_DATE() as today");
    const baseCurrentDate = CURRENT_DATE[0].today;

    const profiles = await this.profileEmployeeRepo.find({
      relations: ["posLevel", "posType"],
      select: ["id", "isLeave", "leaveDate", "posLevel", "posType"],
      where: {
        posLevel: Not(IsNull()),
        posType: Not(IsNull()),
      },
    });

    const BATCH_SIZE = 50;
    let successCount = 0;
    let failCount = 0;
    const allData: CreateTenureLevelEmployee[] = [];

    for (let i = 0; i < profiles.length; i += BATCH_SIZE) {
      const batch = profiles.slice(i, Math.min(i + BATCH_SIZE, profiles.length));
      const results = await Promise.allSettled(
        batch.map((profile) =>
          this.processSingleProfileForTenureLevelEmployee(profile, baseCurrentDate),
        ),
      );

      results.forEach((result) => {
        if (result.status === "fulfilled" && result.value) {
          allData.push(result.value);
          successCount++;
        } else {
          failCount++;
        }
      });
    }

    await AppDataSource.transaction(async (transactionalEntityManager) => {
      await transactionalEntityManager.delete(TenureLevelEmployee, {});
      if (allData.length > 0) {
        const entities = allData.map((data) => {
          const entity = new TenureLevelEmployee();
          Object.assign(entity, data);
          return entity;
        });
        await transactionalEntityManager.save(TenureLevelEmployee, entities);
      }
    });

    return new HttpSuccess({
      message: `อัปเดต tenure level employee สำเร็จ`,
      total: profiles.length,
      success: successCount,
      failed: failCount,
    });
  }

  private async processSingleProfileForTenureLevelEmployee(
    profile: Pick<ProfileEmployee, "id" | "isLeave" | "leaveDate" | "posLevel" | "posType"> & {
      posLevel?: { posLevelName?: string } | null;
      posType?: { posTypeName?: string } | null;
    },
    baseCurrentDate: string,
  ): Promise<CreateTenureLevelEmployee | null> {
    try {
      let _currentDate = baseCurrentDate;
      if (profile.isLeave && profile.leaveDate) {
        _currentDate = Extension.toDateOnlyString(profile.leaveDate);
      }

      const positionLevel = await AppDataSource.query("CALL GetProfileEmployeeSalaryLevel(?, ?)", [
        profile.id,
        _currentDate,
      ]);
      const _positionLevel = positionLevel.length > 0 ? positionLevel[0] : [];

      const mapPositionLevel =
        _positionLevel.length > 1
          ? _positionLevel.slice(1).map((curr: any, index: number) => ({
              days_diff: curr.days_diff,
              positionType: _positionLevel[index]?.positionType,
              positionLevel: _positionLevel[index]?.positionLevel,
              positionCee: _positionLevel[index]?.positionCee,
              year:
                curr.Years !== null && curr.Years !== undefined
                  ? Math.floor(Number(curr.Years))
                  : 0,
              month:
                curr.Months !== null && curr.Months !== undefined
                  ? Math.floor(Number(curr.Months))
                  : 0,
              day:
                curr.Days !== null && curr.Days !== undefined ? Math.floor(Number(curr.Days)) : 0,
            }))
          : [];

      const calDayDiff = mapPositionLevel
        .filter(
          (curr: any) =>
            curr.positionLevel === (profile.posLevel?.posLevelName ?? null) &&
            curr.positionType === (profile.posType?.posTypeName ?? null),
        )
        .reduce(
          (acc: any, curr: any) => {
            acc.days_diff += Number(curr.days_diff) || 0;
            acc.positionType = curr.positionType;
            acc.positionLevel = curr.positionLevel;
            acc.positionCee = curr.positionCee;
            acc.year += curr.year;
            acc.month += curr.month;
            acc.day += curr.day;
            return acc;
          },
          {
            days_diff: 0,
            positionType: null,
            positionLevel: null,
            positionCee: null,
            year: 0,
            month: 0,
            day: 0,
          },
        );

      const normalized = normalizeDurationSumSimple(
        calDayDiff.year,
        calDayDiff.month,
        calDayDiff.day,
      );

      return {
        profileEmployeeId: profile.id,
        positionType: calDayDiff.positionType,
        positionLevel: calDayDiff.positionLevel,
        positionCee: calDayDiff.positionCee,
        days_diff: calDayDiff.days_diff,
        Years: profile.posLevel == null ? 0 : normalized.years,
        Months: profile.posLevel == null ? 0 : normalized.months,
        Days: profile.posLevel == null ? 0 : normalized.days,
      };
    } catch (error) {
      return null;
    }
  }

  @Get("TenurePositionExecutiveOfficer")
  public async cronjobTenureExecutivePositionOfficer() {
    const CURRENT_DATE = await AppDataSource.query("SELECT CURRENT_DATE() as today");
    const baseCurrentDate = CURRENT_DATE[0].today;

    const profiles = await this.profileRepo.find({
      select: ["id", "posExecutive", "isLeave", "leaveDate"],
      where: { posExecutive: Not(IsNull()) },
    });

    const BATCH_SIZE = 50;
    let successCount = 0;
    let failCount = 0;
    const allData: CreateTenurePositionExecutiveOfficer[] = [];

    for (let i = 0; i < profiles.length; i += BATCH_SIZE) {
      const batch = profiles.slice(i, Math.min(i + BATCH_SIZE, profiles.length));
      const results = await Promise.allSettled(
        batch.map((profile) =>
          this.processSingleProfileForTenureExecutivePositionOfficer(profile, baseCurrentDate),
        ),
      );

      results.forEach((result) => {
        if (result.status === "fulfilled" && result.value) {
          allData.push(result.value);
          successCount++;
        } else {
          failCount++;
        }
      });
    }

    await AppDataSource.transaction(async (transactionalEntityManager) => {
      await transactionalEntityManager.delete(TenurePositionExecutiveOfficer, {});
      if (allData.length > 0) {
        const entities = allData.map((data) => {
          const entity = new TenurePositionExecutiveOfficer();
          Object.assign(entity, data);
          return entity;
        });
        await transactionalEntityManager.save(TenurePositionExecutiveOfficer, entities);
      }
    });

    return new HttpSuccess({
      message: `อัปเดต tenure executive position officer สำเร็จ`,
      total: profiles.length,
      success: successCount,
      failed: failCount,
    });
  }

  private async processSingleProfileForTenureExecutivePositionOfficer(
    profile: Pick<Profile, "id" | "isLeave" | "leaveDate" | "posExecutive">,
    baseCurrentDate: string,
  ): Promise<CreateTenurePositionExecutiveOfficer | null> {
    try {
      let _currentDate = baseCurrentDate;
      if (profile.isLeave && profile.leaveDate) {
        _currentDate = Extension.toDateOnlyString(profile.leaveDate);
      }

      const positionExecutive = await AppDataSource.query("CALL GetProfileSalaryExecutive(?, ?)", [
        profile.id,
        _currentDate,
      ]);
      const _position = positionExecutive.length > 0 ? positionExecutive[0] : [];

      const mapPosition =
        _position.length > 1
          ? _position.slice(1).map((curr: any, index: number) => ({
              days_diff: curr.days_diff,
              positionExecutive: _position[index]?.positionExecutive,
              year:
                curr.Years !== null && curr.Years !== undefined
                  ? Math.floor(Number(curr.Years))
                  : 0,
              month:
                curr.Months !== null && curr.Months !== undefined
                  ? Math.floor(Number(curr.Months))
                  : 0,
              day:
                curr.Days !== null && curr.Days !== undefined ? Math.floor(Number(curr.Days)) : 0,
            }))
          : [];

      const calDayDiff = mapPosition
        .filter((curr: any) => curr.positionExecutive === profile.posExecutive)
        .reduce(
          (acc: any, curr: any) => {
            acc.days_diff += Number(curr.days_diff) || 0;
            acc.positionExecutive = curr.positionExecutive;
            acc.year += curr.year;
            acc.month += curr.month;
            acc.day += curr.day;
            return acc;
          },
          { days_diff: 0, positionExecutive: null, year: 0, month: 0, day: 0 },
        );

      const normalized = normalizeDurationSumSimple(
        calDayDiff.year,
        calDayDiff.month,
        calDayDiff.day,
      );

      return {
        profileId: profile.id,
        positionExecutiveName: calDayDiff.positionExecutive,
        days_diff: calDayDiff.days_diff,
        Years: normalized.years,
        Months: normalized.months,
        Days: normalized.days,
      };
    } catch (error) {
      return null;
    }
  }

  @Get("Registry")
  public async Registry() {
    await this.registryRepo.clear();
    const allRegis = await AppDataSource.getRepository(viewRegistryOfficer)
      .createQueryBuilder("registryOfficer")
      .getMany();
    const profileIds = new Set((await this.profileRepo.find()).map((p) => p.id));
    const mapData = allRegis
      .filter((x) => profileIds.has(x.profileId))
      .map((x) => ({
        ...x,
        isProbation: Boolean(x.isProbation),
        isLeave: Boolean(x.isLeave),
        isRetirement: Boolean(x.isRetirement),
        Educations: x.Educations ? JSON.stringify(x.Educations) : "",
      }));
    if (mapData.length > 0) {
      await this.registryRepo.save(mapData);
    }
    return new HttpSuccess();
  }

  @Get("RegistryEmployee")
  public async RegistryEmployee() {
    await this.registryEmployeeRepo.clear();
    const allRegis = await AppDataSource.getRepository(viewRegistryEmployee)
      .createQueryBuilder("registryEmployee")
      .getMany();
    const profileEmpIds = new Set((await this.profileEmployeeRepo.find()).map((p) => p.id));
    const mapData = allRegis
      .filter((x) => profileEmpIds.has(x.profileEmployeeId))
      .map((x) => ({
        ...x,
        isProbation: Boolean(x.isProbation),
        isLeave: Boolean(x.isLeave),
        isRetirement: Boolean(x.isRetirement),
        Educations: x.Educations ? JSON.stringify(x.Educations) : "",
      }));
    if (mapData.length > 0) {
      await this.registryEmployeeRepo.save(mapData);
    }
    return new HttpSuccess();
  }

  @Get("user")
  public async getSalaryUser(@Request() request: { user: Record<string, any> }) {
    const profile = await this.profileRepo.findOneBy({ keycloak: request.user.sub });
    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }
    const record = await this.salaryRepo.find({
      where: {
        profileId: profile.id,
        commandCode: In(["5", "6", "7", "19"]),
      },
      order: { order: "ASC" },
    });
    const result = await Promise.all(
      record.map(async (r) => {
        let _command = null;
        if (r.commandId) {
          _command = await this.commandRepository.findOne({
            where: { id: r.commandId },
            relations: ["commandType"],
          });
        }
        return {
          ...r,
          commandType: _command && _command?.commandType ? _command?.commandType.code : null,
        };
      }),
    );
    return new HttpSuccess(result);
  }

  @Get("position/user")
  public async getSalaryPositionUser(@Request() request: { user: Record<string, any> }) {
    const profile = await this.profileRepo.findOneBy({ keycloak: request.user.sub });
    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }
    const record = await this.salaryRepo.find({
      where: [
        {
          profileId: profile.id,
          commandCode: In([
            "0",
            "9",
            "1",
            "2",
            "3",
            "4",
            "8",
            "10",
            "11",
            "12",
            "13",
            "14",
            "15",
            "16",
            "20",
          ]),
        },
        { profileId: profile.id, commandCode: IsNull() },
      ],
      order: { order: "ASC" },
      //   order: { commandDateAffect: "ASC" },
    });
    const result = await Promise.all(
      record.map(async (r) => {
        let _command = null;
        if (r.commandId) {
          _command = await this.commandRepository.findOne({
            where: { id: r.commandId },
            relations: ["commandType"],
          });
        }
        return {
          ...r,
          commandType: _command && _command?.commandType ? _command?.commandType.code : null,
        };
      }),
    );
    return new HttpSuccess(result);
  }

  @Get("{profileId}")
  public async getSalary(@Path() profileId: string, @Request() req: RequestWithUser) {
    let _workflow = await new permission().Workflow(req, profileId, "SYS_REGISTRY_OFFICER");
    if (_workflow == false)
      await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_OFFICER", profileId);
    const record = await this.salaryRepo.find({
      where: { profileId: profileId, commandCode: In(["5", "6", "7", "19"]) },
      order: { order: "ASC" },
    });
    // const result = record.map((r) => ({
    //   ...r,
    //   positionExecutive:
    //     r.positionExecutiveField
    //       ? `${r.positionExecutive}(${r.positionExecutiveField})`
    //       : r.positionExecutive ?? null,
    // }));
    const result = await Promise.all(
      record.map(async (r) => {
        let _command = null;
        if (r.commandId) {
          _command = await this.commandRepository.findOne({
            where: { id: r.commandId },
            relations: ["commandType"],
          });
        }
        return {
          ...r,
          commandType: _command && _command?.commandType ? _command?.commandType.code : null,
        };
      }),
    );
    return new HttpSuccess(result);
  }

  @Get("position/{profileId}")
  public async getPositionSalary(@Path() profileId: string, @Request() req: RequestWithUser) {
    let _workflow = await new permission().Workflow(req, profileId, "SYS_REGISTRY_OFFICER");
    if (_workflow == false)
      await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_OFFICER", profileId);
    const record = await this.salaryRepo.find({
      where: [
        {
          profileId: profileId,
          commandCode: In([
            "0",
            "9",
            "1",
            "2",
            "3",
            "4",
            "8",
            "10",
            "11",
            "12",
            "13",
            "14",
            "15",
            "16",
            "20",
          ]),
        },
        { profileId: profileId, commandCode: IsNull() },
      ],
      order: { order: "ASC" },
      //   order: { commandDateAffect: "ASC" },
    });

    // const result = record.map((r) => ({
    //   ...r,
    //   positionExecutive:
    //     r.positionExecutiveField
    //       ? `${r.positionExecutive}(${r.positionExecutiveField})`
    //       : r.positionExecutive ?? null,
    // }));
    const result = await Promise.all(
      record.map(async (r) => {
        let _command = null;
        if (r.commandId) {
          _command = await this.commandRepository.findOne({
            where: { id: r.commandId },
            relations: ["commandType"],
          });
        }
        return {
          ...r,
          commandType: _command && _command?.commandType ? _command?.commandType.code : null,
        };
      }),
    );
    return new HttpSuccess(result);
  }

  @Get("tenure/user")
  public async getPositionTenureUser(@Request() request: { user: Record<string, any> }) {
    // const sql_mode = await AppDataSource.query(
    //   "SET SESSION sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));",
    // );
    const profile = await this.profileRepo.findOneBy({ keycloak: request.user.sub });
    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }
    const CURRENT_DATE = await AppDataSource.query("SELECT CURRENT_DATE() as today");
    let _currentDate = CURRENT_DATE[0].today;
    if (profile && profile?.isLeave) {
      _currentDate =
        profile && profile.leaveDate ? Extension.toDateOnlyString(profile.leaveDate) : _currentDate;
    }
    const position = await AppDataSource.query("CALL GetProfileSalaryPosition(?, ?)", [
      profile.id,
      _currentDate,
    ]);
    const _position = position.length > 0 ? position[0] : [];

    const mapPosition =
      _position.length > 1
        ? _position.slice(1).map((curr: any, index: number) => ({
            days: curr.days_diff ? Number(curr.days_diff) : 0,
            // Use stored procedure's calculated values (calendar arithmetic)
            year:
              curr.Years !== null && curr.Years !== undefined ? Math.floor(Number(curr.Years)) : 0,
            month:
              curr.Months !== null && curr.Months !== undefined
                ? Math.floor(Number(curr.Months))
                : 0,
            day: curr.Days !== null && curr.Days !== undefined ? Math.floor(Number(curr.Days)) : 0,
            name: _position[index]?.positionName,
          }))
        : [];

    const groupMapPosition = mapPosition.reduce(
      (acc: any, curr: any) => {
        let existing = acc.find((item: any) => item.name === curr.name);

        if (existing) {
          existing.days += curr.days;
          existing.year += curr.year;
          existing.month += curr.month;
          existing.day += curr.day;
        } else {
          existing = {
            name: curr.name,
            days: curr.days,
            year: curr.year,
            month: curr.month,
            day: curr.day,
          };
          acc.push(existing);
        }

        // Normalize the summed values using calendar arithmetic
        const normalized = normalizeDurationSumSimple(existing.year, existing.month, existing.day);
        existing.year = normalized.years;
        existing.month = normalized.months;
        existing.day = normalized.days;

        return acc;
      },
      [] as { name: string; days: number; year: number; month: number; day: number }[],
    );
    const posLevel = await AppDataSource.query("CALL GetProfileSalaryLevel(?, ?)", [
      profile.id,
      _currentDate,
    ]);
    const _posLevel = posLevel.length > 0 ? posLevel[0] : [];
    const mapPosLevel =
      _posLevel.length > 1
        ? _posLevel.slice(1).map((curr: any, index: number) => ({
            days: curr.days_diff ? Number(curr.days_diff) : 0,
            // Use stored procedure's calculated values (calendar arithmetic)
            year:
              curr.Years !== null && curr.Years !== undefined ? Math.floor(Number(curr.Years)) : 0,
            month:
              curr.Months !== null && curr.Months !== undefined
                ? Math.floor(Number(curr.Months))
                : 0,
            day: curr.Days !== null && curr.Days !== undefined ? Math.floor(Number(curr.Days)) : 0,
            name:
              !_posLevel[index]?.positionType && _posLevel[index]?.positionCee
                ? `ระดับ ${_posLevel[index]?.positionCee.trim()}`
                : _posLevel[index]?.positionType == "บริหาร" ||
                    _posLevel[index]?.positionType == "อำนวยการ"
                  ? `${_posLevel[index]?.positionType}${_posLevel[index]?.positionLevel}`
                  : _posLevel[index]?.positionLevel,
          }))
        : [];

    const groupMapPosLevel = mapPosLevel.reduce(
      (acc: any, curr: any) => {
        let existing = acc.find((item: any) => item.name === curr.name);

        if (existing) {
          existing.days += curr.days;
          existing.year += curr.year;
          existing.month += curr.month;
          existing.day += curr.day;
        } else {
          existing = {
            name: curr.name,
            days: curr.days,
            year: curr.year,
            month: curr.month,
            day: curr.day,
          };
          acc.push(existing);
        }

        // Normalize the summed values using calendar arithmetic
        const normalized = normalizeDurationSumSimple(existing.year, existing.month, existing.day);
        existing.year = normalized.years;
        existing.month = normalized.months;
        existing.day = normalized.days;

        return acc;
      },
      [] as { name: string; days: number; year: number; month: number; day: number }[],
    );

    const posExecutive = await AppDataSource.query("CALL GetProfileSalaryExecutive(?, ?)", [
      profile.id,
      _currentDate,
    ]);
    const _posExecutive = posExecutive.length > 0 ? posExecutive[0] : [];
    const mapPosExecutive =
      _posExecutive.length > 1
        ? _posExecutive.slice(1).map((curr: any, index: number) => ({
            days: curr.days_diff ? Number(curr.days_diff) : 0,
            // Use stored procedure's calculated values (calendar arithmetic)
            year:
              curr.Years !== null && curr.Years !== undefined ? Math.floor(Number(curr.Years)) : 0,
            month:
              curr.Months !== null && curr.Months !== undefined
                ? Math.floor(Number(curr.Months))
                : 0,
            day: curr.Days !== null && curr.Days !== undefined ? Math.floor(Number(curr.Days)) : 0,
            name: _posExecutive[index]?.positionExecutive,
          }))
        : [];

    const groupMapPosExecutive = mapPosExecutive.reduce(
      (acc: any, curr: any) => {
        let existing = acc.find((item: any) => item.name === curr.name);

        if (existing) {
          existing.days += curr.days;
          existing.year += curr.year;
          existing.month += curr.month;
          existing.day += curr.day;
        } else {
          existing = {
            name: curr.name,
            days: curr.days,
            year: curr.year,
            month: curr.month,
            day: curr.day,
          };
          acc.push(existing);
        }

        // Normalize the summed values using calendar arithmetic
        const normalized = normalizeDurationSumSimple(existing.year, existing.month, existing.day);
        existing.year = normalized.years;
        existing.month = normalized.months;
        existing.day = normalized.days;

        return acc;
      },
      [] as { name: string; days: number; year: number; month: number; day: number }[],
    );

    return new HttpSuccess({
      position: groupMapPosition,
      posLevel: groupMapPosLevel,
      posExecutive: groupMapPosExecutive,
    });
  }

  @Get("tenure/{profileId}")
  public async getPositionTenure(@Path() profileId: string, @Request() req: RequestWithUser) {
    // const sql_mode = await AppDataSource.query(
    //   "SET SESSION sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));",
    // );
    const _profile = await this.profileRepo.findOne({
      where: { id: profileId },
    });
    if (!_profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }
    const CURRENT_DATE = await AppDataSource.query("SELECT CURRENT_DATE() as today");
    let _currentDate = CURRENT_DATE[0].today;
    if (_profile && _profile?.isLeave) {
      _currentDate =
        _profile && _profile.leaveDate
          ? Extension.toDateOnlyString(_profile.leaveDate)
          : _currentDate;
    }
    const position = await AppDataSource.query("CALL GetProfileSalaryPosition(?, ?)", [
      profileId,
      _currentDate,
    ]);
    const _position = position.length > 0 ? position[0] : [];

    const mapPosition =
      _position.length > 1
        ? _position.slice(1).map((curr: any, index: number) => ({
            days: curr.days_diff ? Number(curr.days_diff) : 0,
            // Use stored procedure's calculated values (calendar arithmetic)
            year:
              curr.Years !== null && curr.Years !== undefined ? Math.floor(Number(curr.Years)) : 0,
            month:
              curr.Months !== null && curr.Months !== undefined
                ? Math.floor(Number(curr.Months))
                : 0,
            day: curr.Days !== null && curr.Days !== undefined ? Math.floor(Number(curr.Days)) : 0,
            name: _position[index]?.positionName,
          }))
        : [];

    const groupMapPosition = mapPosition.reduce(
      (acc: any, curr: any) => {
        let existing = acc.find((item: any) => item.name === curr.name);

        if (existing) {
          existing.days += curr.days;
          existing.year += curr.year;
          existing.month += curr.month;
          existing.day += curr.day;
        } else {
          existing = {
            name: curr.name,
            days: curr.days,
            year: curr.year,
            month: curr.month,
            day: curr.day,
          };
          acc.push(existing);
        }

        // Normalize the summed values using calendar arithmetic
        const normalized = normalizeDurationSumSimple(existing.year, existing.month, existing.day);
        existing.year = normalized.years;
        existing.month = normalized.months;
        existing.day = normalized.days;

        return acc;
      },
      [] as { name: string; days: number; year: number; month: number; day: number }[],
    );

    const posLevel = await AppDataSource.query("CALL GetProfileSalaryLevel(?, ?)", [
      profileId,
      _currentDate,
    ]);
    const _posLevel = posLevel.length > 0 ? posLevel[0] : [];
    const mapPosLevel =
      _posLevel.length > 1
        ? _posLevel.slice(1).map((curr: any, index: number) => ({
            days: curr.days_diff ? Number(curr.days_diff) : 0,
            // Use stored procedure's calculated values (calendar arithmetic)
            year:
              curr.Years !== null && curr.Years !== undefined ? Math.floor(Number(curr.Years)) : 0,
            month:
              curr.Months !== null && curr.Months !== undefined
                ? Math.floor(Number(curr.Months))
                : 0,
            day: curr.Days !== null && curr.Days !== undefined ? Math.floor(Number(curr.Days)) : 0,
            name:
              !_posLevel[index]?.positionType && _posLevel[index]?.positionCee
                ? `ระดับ ${_posLevel[index]?.positionCee.trim()}`
                : _posLevel[index]?.positionType == "บริหาร" ||
                    _posLevel[index]?.positionType == "อำนวยการ"
                  ? `${_posLevel[index]?.positionType}${_posLevel[index]?.positionLevel}`
                  : _posLevel[index]?.positionLevel,
          }))
        : [];

    const groupMapPosLevel = mapPosLevel.reduce(
      (acc: any, curr: any) => {
        let existing = acc.find((item: any) => item.name === curr.name);

        if (existing) {
          existing.days += curr.days;
          existing.year += curr.year;
          existing.month += curr.month;
          existing.day += curr.day;
        } else {
          existing = {
            name: curr.name,
            days: curr.days,
            year: curr.year,
            month: curr.month,
            day: curr.day,
          };
          acc.push(existing);
        }

        // Normalize the summed values using calendar arithmetic
        const normalized = normalizeDurationSumSimple(existing.year, existing.month, existing.day);
        existing.year = normalized.years;
        existing.month = normalized.months;
        existing.day = normalized.days;

        return acc;
      },
      [] as { name: string; days: number; year: number; month: number; day: number }[],
    );

    const posExecutive = await AppDataSource.query("CALL GetProfileSalaryExecutive(?, ?)", [
      profileId,
      _currentDate,
    ]);
    const _posExecutive = posExecutive.length > 0 ? posExecutive[0] : [];
    const mapPosExecutive =
      _posExecutive.length > 1
        ? _posExecutive.slice(1).map((curr: any, index: number) => ({
            days: curr.days_diff ? Number(curr.days_diff) : 0,
            // Use stored procedure's calculated values (calendar arithmetic)
            year:
              curr.Years !== null && curr.Years !== undefined ? Math.floor(Number(curr.Years)) : 0,
            month:
              curr.Months !== null && curr.Months !== undefined
                ? Math.floor(Number(curr.Months))
                : 0,
            day: curr.Days !== null && curr.Days !== undefined ? Math.floor(Number(curr.Days)) : 0,
            name: _posExecutive[index]?.positionExecutive,
          }))
        : [];

    const groupMapPosExecutive = mapPosExecutive.reduce(
      (acc: any, curr: any) => {
        let existing = acc.find((item: any) => item.name === curr.name);

        if (existing) {
          existing.days += curr.days;
          existing.year += curr.year;
          existing.month += curr.month;
          existing.day += curr.day;
        } else {
          existing = {
            name: curr.name,
            days: curr.days,
            year: curr.year,
            month: curr.month,
            day: curr.day,
          };
          acc.push(existing);
        }

        // Normalize the summed values using calendar arithmetic
        const normalized = normalizeDurationSumSimple(existing.year, existing.month, existing.day);
        existing.year = normalized.years;
        existing.month = normalized.months;
        existing.day = normalized.days;

        return acc;
      },
      [] as { name: string; days: number; year: number; month: number; day: number }[],
    );

    return new HttpSuccess({
      position: groupMapPosition,
      posLevel: groupMapPosLevel,
      posExecutive: groupMapPosExecutive,
    });
  }

  @Get("admin/{profileId}")
  public async getSalaryAdmin(@Path() profileId: string, @Request() req: RequestWithUser) {
    let _workflow = await new permission().Workflow(req, profileId, "SYS_SALARY_OFFICER");
    if (_workflow == false) await new permission().PermissionGet(req, "SYS_SALARY_OFFICER");
    const record = await this.salaryRepo.find({
      where: { profileId: profileId, commandCode: In(["5", "6", "7", "19"]) },
      order: { order: "ASC" },
    });
    return new HttpSuccess(record);
  }

  @Get("admin/history/{salaryId}")
  public async salaryAdminHistory(@Path() salaryId: string, @Request() req: RequestWithUser) {
    const _record = await this.salaryRepo.findOneBy({ id: salaryId });
    if (_record) {
      let _workflow = await new permission().Workflow(req, salaryId, "SYS_REGISTRY_OFFICER");
      if (_workflow == false)
        await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_OFFICER", _record.profileId);
    }
    const record = await this.salaryHistoryRepo.find({
      where: {
        profileSalaryId: salaryId,
      },
      order: { createdAt: "DESC" },
    });
    return new HttpSuccess(record);
  }

  @Get("history/{salaryId}")
  public async salaryHistory(@Path() salaryId: string) {
    const record = await this.salaryHistoryRepo.find({
      where: {
        profileSalaryId: salaryId,
      },
      order: { createdAt: "DESC" },
    });
    return new HttpSuccess(record);
  }

  @Post()
  public async newSalary(@Request() req: RequestWithUser, @Body() body: CreateProfileSalary) {
    if (!body.profileId) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileId");
    }

    const profile = await this.profileRepo.findOneBy({ id: body.profileId });
    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }
    await new permission().PermissionOrgUserUpdate(req, "SYS_REGISTRY_OFFICER", profile.id);

    const dest_item = await this.salaryRepo.findOne({
      where: { profileId: body.profileId },
      order: { order: "DESC" },
    });
    const before = null;
    const data = new ProfileSalary();

    const meta = {
      order: dest_item == null ? 1 : dest_item.order + 1,
      createdUserId: req.user.sub,
      createdFullName: req.user.name,
      lastUpdateUserId: req.user.sub,
      lastUpdateFullName: req.user.name,
      createdAt: new Date(),
      lastUpdatedAt: new Date(),
    };
    const _null: any = null;
    if (body.commandCode && !body.commandName) {
      if (body.commandCode == "7") body.commandName = "เงินพิเศษอื่น ๆ";
      else if (body.commandCode == "6") body.commandName = "เลื่อนเงินเดือนกรณีอื่น ๆ";
      else if (body.commandCode == "5") body.commandName = "เลื่อนเงินเดือนตามปกติ";
      else if (body.commandCode == "19") body.commandName = "ไม่ได้เลื่อนเงินเดือน/ค่าจ้าง";
    }
    Object.assign(data, { ...body, ...meta });
    // 12,15,16 isGovernment = false & dateGovernment = commandDateAffect
    if (["12", "15", "16"].includes(body.commandCode ?? "")) {
      data.isGovernment = false;
      if (body.commandDateAffect) data.dateGovernment = body.commandDateAffect;
    }
    // 1,2,3,4,10,11,20 isGovernment = true & dateGovernment = commandDateAffect
    else if (["1", "2", "3", "4", "10", "11", "20"].includes(body.commandCode ?? "")) {
      data.isGovernment = true;
      if (body.commandDateAffect) data.dateGovernment = body.commandDateAffect;
    }

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

    profile.amount = body?.amount ?? _null;
    profile.amountSpecial = body.amountSpecial ?? _null;
    profile.positionSalaryAmount = body?.positionSalaryAmount ?? _null;
    profile.mouthSalaryAmount = body.mouthSalaryAmount ?? _null;
    await this.profileRepo.save(profile, { data: req });

    return new HttpSuccess();
  }

  @Post("update")
  public async updateSalary(@Request() req: RequestWithUser, @Body() body: CreateProfileSalary) {
    if (!body.profileId) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileId");
    }

    const profile = await this.profileRepo.findOneBy({ id: body.profileId });
    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }
    await new permission().PermissionOrgUserUpdate(req, "SYS_REGISTRY_OFFICER", profile.id);

    const dest_item = await this.salaryRepo.findOne({
      where: { profileId: body.profileId },
      order: { order: "DESC" },
    });
    const before = null;
    let _posNumCodeSit: string = "";
    let _posNumCodeSitAbb: string = "";
    const _command = await this.commandRepository.findOne({
      where: { id: body.commandId ?? "" },
    });
    if (_command) {
      if (_command?.isBangkok?.toLocaleUpperCase() == "OFFICE") {
        const orgRootDeputy = await this.orgRootRepository.findOne({
          where: {
            isDeputy: true,
            orgRevision: {
              orgRevisionIsCurrent: true,
              orgRevisionIsDraft: false,
            },
          },
          relations: ["orgRevision"],
        });
        _posNumCodeSit = orgRootDeputy ? orgRootDeputy?.orgRootName : "สำนักปลัดกรุงเทพมหานคร";
        _posNumCodeSitAbb = orgRootDeputy ? orgRootDeputy?.orgRootShortName : "สนป.";
      } else if (_command?.isBangkok?.toLocaleUpperCase() == "BANGKOK") {
        _posNumCodeSit = "กรุงเทพมหานคร";
        _posNumCodeSitAbb = "กทม.";
      } else {
        let _profileAdmin = await this.profileRepo.findOne({
          where: {
            keycloak: _command?.createdUserId.toString(),
            current_holders: {
              orgRevision: {
                orgRevisionIsCurrent: true,
                orgRevisionIsDraft: false,
              },
            },
          },
          relations: ["current_holders", "current_holders.orgRevision", "current_holders.orgRoot"],
        });
        _posNumCodeSit =
          _profileAdmin?.current_holders.find((x) => x.orgRoot.orgRootName)?.orgRoot.orgRootName ??
          "";
        _posNumCodeSitAbb =
          _profileAdmin?.current_holders.find((x) => x.orgRoot.orgRootShortName)?.orgRoot
            .orgRootShortName ?? "";
      }
    }
    const data = new ProfileSalary();
    data.posNumCodeSit = _posNumCodeSit;
    data.posNumCodeSitAbb = _posNumCodeSitAbb;
    const meta = {
      order: dest_item == null ? 1 : dest_item.order + 1,
      createdUserId: req.user.sub,
      createdFullName: req.user.name,
      lastUpdateUserId: req.user.sub,
      lastUpdateFullName: req.user.name,
      createdAt: new Date(),
      lastUpdatedAt: new Date(),
    };

    Object.assign(data, { ...body, ...meta });
    const history = new ProfileSalaryHistory();
    Object.assign(history, { ...data, id: undefined });
    await this.salaryRepo.save(data, { data: req });
    setLogDataDiff(req, { before, after: data });
    history.profileSalaryId = data.id;
    await this.salaryHistoryRepo.save(history, { data: req });

    let _null: any = null;
    profile.amount = body.amount ?? _null;
    profile.amountSpecial = body.amountSpecial ?? _null;
    profile.positionSalaryAmount = body.positionSalaryAmount ?? _null;
    profile.mouthSalaryAmount = body.mouthSalaryAmount ?? _null;
    await this.profileRepo.save(profile);
    return new HttpSuccess();
  }

  @Patch("{salaryId}")
  public async editSalary(
    @Request() req: RequestWithUser,
    @Body() body: UpdateProfileSalary,
    @Path() salaryId: string,
  ) {
    const record = await this.salaryRepo.findOneBy({ id: salaryId });
    if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    await new permission().PermissionOrgUserUpdate(req, "SYS_REGISTRY_OFFICER", record.profileId);
    const before = structuredClone(record);
    const history = new ProfileSalaryHistory();
    if (body.commandCode && !body.commandName) {
      if (body.commandCode == "7") body.commandName = "เงินพิเศษอื่น ๆ";
      else if (body.commandCode == "6") body.commandName = "เลื่อนเงินเดือนกรณีอื่น ๆ";
      else if (body.commandCode == "5") body.commandName = "เลื่อนเงินเดือนตามปกติ";
      else if (body.commandCode == "19") body.commandName = "ไม่ได้เลื่อนเงินเดือน/ค่าจ้าง";
    }
    Object.assign(record, body);
    // 12,15,16 isGovernment = false & dateGovernment = commandDateAffect
    if (["12", "15", "16"].includes(body.commandCode ?? "")) {
      record.isGovernment = false;
      if (body.commandDateAffect) record.dateGovernment = body.commandDateAffect;
    }
    // 1,2,3,4,10,11,20 isGovernment = true & dateGovernment = commandDateAffect
    else if (["1", "2", "3", "4", "10", "11", "20"].includes(body.commandCode ?? "")) {
      record.isGovernment = true;
      if (body.commandDateAffect) record.dateGovernment = body.commandDateAffect;
    }

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

    history.profileSalaryId = salaryId;
    record.lastUpdateUserId = req.user.sub;
    record.lastUpdateFullName = req.user.name;
    record.lastUpdatedAt = new Date();
    history.lastUpdateUserId = req.user.sub;
    history.lastUpdateFullName = req.user.name;
    history.createdUserId = req.user.sub;
    history.createdFullName = req.user.name;
    history.createdAt = new Date();
    history.lastUpdatedAt = new Date();

    await Promise.all([
      this.salaryRepo.save(record, { data: req }),
      setLogDataDiff(req, { before, after: record }),
      this.salaryHistoryRepo.save(history, { data: req }),
    ]);

    return new HttpSuccess();
  }

  @Delete("{salaryId}")
  public async deleteSalary(@Path() salaryId: string, @Request() req: RequestWithUser) {
    const _record = await this.salaryRepo.findOneBy({ id: salaryId });
    if (_record) {
      await new permission().PermissionOrgUserDelete(
        req,
        "SYS_REGISTRY_OFFICER",
        _record.profileId,
      );
    }
    const data = await this.salaryRepo.findOneBy({ id: salaryId });
    if (!data) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    if (data == null) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    const profileId = data.profileId;
    await this.salaryHistoryRepo.delete({
      profileSalaryId: salaryId,
    });

    const result = await this.salaryRepo.delete({ id: salaryId });

    const salaryList = await this.salaryRepo.find({
      where: {
        profileId: profileId,
      },
    });
    salaryList.forEach(async (p, i) => {
      p.order = i + 1;
      await this.salaryRepo.save(p);
    });
    if (result.affected == undefined || result.affected <= 0) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    }

    return new HttpSuccess();
  }

  @Get("swap/{direction}/{salaryId}")
  public async swapSalary(
    @Path() direction: string,
    salaryId: string,
    @Request() req: RequestWithUser,
  ) {
    const source_item = await this.salaryRepo.findOne({ where: { id: salaryId } });
    // if (source_item) {
    //await new permission().PermissionOrgUserGet(req,"SYS_REGISTRY_OFFICER",source_item.profileId,); //ไม่แน่ใจOFFปิดไว้ก่อน
    // }
    if (source_item == null) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    const sourceOrder = source_item.order;
    if (direction.trim().toUpperCase() == "UP") {
      const dest_item = await this.salaryRepo.findOne({
        where: { profileId: source_item.profileId, order: LessThan(sourceOrder) },
        order: { order: "DESC" },
      });
      if (dest_item == null) return new HttpSuccess();
      var destOrder = dest_item.order;
      dest_item.order = sourceOrder;
      source_item.order = destOrder;
      await Promise.all([this.salaryRepo.save(source_item), this.salaryRepo.save(dest_item)]);
    } else {
      const dest_item = await this.salaryRepo.findOne({
        where: { profileId: source_item.profileId, order: MoreThan(sourceOrder) },
        order: { order: "ASC" },
      });
      if (dest_item == null) return new HttpSuccess();
      var destOrder = dest_item.order;
      dest_item.order = sourceOrder;
      source_item.order = destOrder;
      await Promise.all([this.salaryRepo.save(source_item), this.salaryRepo.save(dest_item)]);
    }
    return new HttpSuccess();
  }
}
