import {
  Controller,
  Post,
  Delete,
  Route,
  Security,
  Tags,
  Body,
  Path,
  Request,
  Response,
  Get,
  Query,
} from "tsoa";
import { AppDataSource } from "../database/data-source";
import HttpSuccess from "../interfaces/http-success";
import HttpStatusCode from "../interfaces/http-status";
import HttpError from "../interfaces/http-error";
import { OrgRoot } from "../entities/OrgRoot";
import { OrgRevision } from "../entities/OrgRevision";
import { RequestWithUser } from "../middlewares/user";
import { PermissionProfile } from "../entities/PermissionProfile";
import { Profile } from "../entities/Profile";
import HttpStatus from "../interfaces/http-status";
import { PosMaster } from "../entities/PosMaster";
import { setLogDataDiff } from "../interfaces/utils";
import { Brackets, In } from "typeorm";

@Route("api/v1/org/permission-profile")
@Tags("PermissionProfile")
@Security("bearerAuth")
@Response(
  HttpStatusCode.INTERNAL_SERVER_ERROR,
  "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง",
)
export class PermissionProfileController extends Controller {
  private orgRootRepository = AppDataSource.getRepository(OrgRoot);
  private profileRepository = AppDataSource.getRepository(Profile);
  private orgRevisionRepository = AppDataSource.getRepository(OrgRevision);
  private permissionProfileRepository = AppDataSource.getRepository(PermissionProfile);
  private posMasterRepository = AppDataSource.getRepository(PosMaster);
  private profileRepo = AppDataSource.getRepository(Profile);

  /**
   * API หาสำนักทั้งหมดแบบร่าง
   *
   * @summary หาสำนักทั้งหมดแบบร่าง
   *
   */
  @Get()
  async GetActiveRootIdAdmin(@Request() request: RequestWithUser) {
    const orgRevisionActive = await this.orgRevisionRepository.findOne({
      where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false },
      relations: ["posMasters"],
    });
    if (!orgRevisionActive) return new HttpSuccess([]);
    let rootId: any = null;
    if (!request.user.role.includes("SUPER_ADMIN")) {
      const profile = await this.profileRepo.findOne({
        where: {
          keycloak: request.user.sub,
        },
      });
      if (profile == null) return new HttpSuccess([]);

      if (!request.user.role.includes("SUPER_ADMIN")) {
        rootId =
          orgRevisionActive?.posMasters?.filter((x) => x.current_holderId == profile.id)[0]
            ?.orgRootId || null;
        if (!rootId) return new HttpSuccess([]);
      }
    }
    const data = await AppDataSource.getRepository(OrgRoot)
      .createQueryBuilder("orgRoot")
      .where("orgRoot.orgRevisionId = :id", { id: orgRevisionActive.id })
      .andWhere(rootId != null ? `orgRoot.id = :rootId` : "1=1", {
        rootId: rootId,
      })
      .orderBy("orgRoot.orgRootOrder", "ASC")
      .getMany();
    const _data = data.map((x) => ({
      ...x,
      labelName: `${x.orgRootName} ${x.orgRootCode} ${x.orgRootShortName}`,
    }));
    return new HttpSuccess(_data);
  }

  @Get("profile")
  async listProfile(
    @Request() request: RequestWithUser,
    @Query("page") page: number = 1,
    @Query("pageSize") pageSize: number = 10,
    @Query()
    searchField?: "fullName" | "position" | "posNo" | "postype" | "poslevel",
    @Query() searchKeyword: string = "",
  ) {
    // if (!request.user.role.includes("SUPER_ADMIN")) {
    //   throw new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์ใช้งานระบบนี้");
    // }
    let queryLike =
      "CONCAT(profile.prefix, profile.firstName, ' ', profile.lastName) LIKE :keyword";
    if (searchField == "postype") {
      queryLike = "posType.posTypeName LIKE :keyword";
    } else if (searchField == "poslevel") {
      queryLike = "posLevel.posLevelName LIKE :keyword";
    } else if (searchField == "position") {
      queryLike = "profile.position LIKE :keyword";
    } else if (searchField == "posNo") {
      queryLike = `
      CASE 
        WHEN current_holders.orgChild4Id IS NOT NULL THEN CONCAT(orgChild4.orgChild4ShortName, " ", current_holders.posMasterNo)
        WHEN current_holders.orgChild3Id IS NOT NULL THEN CONCAT(orgChild3.orgChild3ShortName, " ", current_holders.posMasterNo)
        WHEN current_holders.orgChild2Id IS NOT NULL THEN CONCAT(orgChild2.orgChild2ShortName, " ", current_holders.posMasterNo)
        WHEN current_holders.orgChild1Id IS NOT NULL THEN CONCAT(orgChild1.orgChild1ShortName, " ", current_holders.posMasterNo)
        ELSE CONCAT(orgRoot.orgRootShortName, " ", current_holders.posMasterNo)
      END LIKE :keyword
    `;
    }
    const findRevision = await this.orgRevisionRepository.findOne({
      where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false },
    });
    const orgRevisionId = findRevision?.id;
    if (!findRevision) {
      throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
    }
    // console.log(findRevision.id);

    const [record, total] = await this.profileRepository
      .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.orgRevision", "orgRevision")
      .leftJoinAndSelect("current_holders.orgRoot", "orgRoot")
      .leftJoinAndSelect("current_holders.orgChild1", "orgChild1")
      .leftJoinAndSelect("current_holders.orgChild2", "orgChild2")
      .leftJoinAndSelect("current_holders.orgChild3", "orgChild3")
      .leftJoinAndSelect("current_holders.orgChild4", "orgChild4")
      .where("current_holders.orgRevisionId = :orgRevisionId", { orgRevisionId })
      .andWhere(
        new Brackets((qb) => {
          // qb.andWhere(`current_holders.orgRevision = :orgRevisionId`, {
          //   orgRevisionId: findRevision.id,
          // })
          qb.andWhere(
            searchKeyword != undefined && searchKeyword != null && searchKeyword != ""
              ? queryLike
              : "1=1",
            {
              keyword: `%${searchKeyword}%`,
            },
          );
        }),
      )
      .orderBy("current_holders.posMasterNo", "ASC")
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getManyAndCount();

    const data = await Promise.all(
      record.map((_data) => {
        const shortName =
          _data.current_holders.length == 0
            ? null
            : _data.current_holders.find((x) => x.orgRevisionId == 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 _root = root?.orgRootName;
        let _child1 = child1?.orgChild1Name;
        let _child2 = child2?.orgChild2Name;
        let _child3 = child3?.orgChild3Name;
        let _child4 = child4?.orgChild4Name;

        return {
          id: _data.id,
          avatar: _data.avatar,
          avatarName: _data.avatarName,
          prefix: _data.prefix,
          rank: _data.rank,
          firstName: _data.firstName,
          lastName: _data.lastName,
          org:
            (_child4 == null ? "" : _child4 + "\n") +
            (_child3 == null ? "" : _child3 + "\n") +
            (_child2 == null ? "" : _child2 + "\n") +
            (_child1 == null ? "" : _child1 + "\n") +
            (_root == null ? "" : _root),
          posNo: shortName,
          position: _data.position,
          posType: _data.posType == null ? null : _data.posType.posTypeName,
          posLevel: _data.posLevel == null ? null : _data.posLevel.posLevelName,
        };
      }),
    );

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

  /**
   * API รายละเอียดรายการสิทธิ์โครงสร้าง
   *
   * @summary - CRUD สิทธิ์โครงสร้าง (ADMIN)
   *
   * @param {string} id  Id โครงสร้าง
   */
  @Post("profile")
  async GetById(
    @Request() request: RequestWithUser,
    @Body()
    requestBody: {
      id: string | null;
      page: number;
      pageSize: number;
      searchField?: "fullName" | "position" | "posNo" | "postype" | "poslevel";
      searchKeyword: string;
    },
  ) {
    // if (!request.user.role.includes("SUPER_ADMIN")) {
    //   throw new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์ใช้งานระบบนี้");
    // }
    let profiles: any = [];
    if (requestBody.id != null) {
      const _permissionProfile = await this.orgRootRepository.findOne({
        where: { id: requestBody.id },
        relations: ["permissionProfileRoots", "permissionProfileRoots.profileTree"],
      });
      if (!_permissionProfile) {
        throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลสิทธิ์โครงสร้างนี้");
      }
      profiles = await _permissionProfile.permissionProfileRoots.map((x) => x.profileId);
    } else {
      const _permissionProfile = await this.permissionProfileRepository.find();
      profiles = await _permissionProfile.map((x) => x.profileId);
    }

    let queryLike =
      "CONCAT(profileTree.prefix, profileTree.firstName, ' ', profileTree.lastName) LIKE :keyword";
    if (requestBody.searchField == "postype") {
      queryLike = "posLevel.posLevelName LIKE :keyword";
    } else if (requestBody.searchField == "poslevel") {
      queryLike = "posType.posTypeName LIKE :keyword";
    } else if (requestBody.searchField == "position") {
      queryLike = "profileTree.position LIKE :keyword";
    } else if (requestBody.searchField == "posNo") {
      queryLike = `CONCAT(
        IFNULL(orgChild4.orgChild4ShortName, ''),
        IFNULL(current_holders.posMasterNo , '')
      ) LIKE :keyword OR CONCAT(
        IFNULL(orgChild3.orgChild3ShortName, ''),
        IFNULL(current_holders.posMasterNo , '')
      ) LIKE :keyword OR CONCAT(
        IFNULL(orgChild2.orgChild2ShortName, ''),
        IFNULL(current_holders.posMasterNo , '')
      ) LIKE :keyword OR CONCAT(
        IFNULL(orgChild1.orgChild1ShortName, ''),
        IFNULL(current_holders.posMasterNo , '')
      ) LIKE :keyword OR CONCAT(
        IFNULL(orgRoot.orgRootShortName, ''),
        IFNULL(current_holders.posMasterNo , '')
      ) LIKE :keyword`;
    }
    const findRevision = await this.orgRevisionRepository.findOne({
      where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false },
    });
    if (!findRevision) {
      throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
    }
    const [record, total] = await this.permissionProfileRepository
      .createQueryBuilder("permissionProfile")
      .leftJoinAndSelect("permissionProfile.orgRootTree", "orgRootTree")
      .leftJoinAndSelect("permissionProfile.profileTree", "profileTree")
      .leftJoinAndSelect("profileTree.posLevel", "posLevel")
      .leftJoinAndSelect("profileTree.posType", "posType")
      .leftJoinAndSelect("profileTree.current_holders", "current_holders")
      .leftJoinAndSelect("current_holders.positions", "positions")
      .leftJoinAndSelect("current_holders.orgRevision", "orgRevision")
      .leftJoinAndSelect("current_holders.orgRoot", "orgRoot")
      .leftJoinAndSelect("current_holders.orgChild1", "orgChild1")
      .leftJoinAndSelect("current_holders.orgChild2", "orgChild2")
      .leftJoinAndSelect("current_holders.orgChild3", "orgChild3")
      .leftJoinAndSelect("current_holders.orgChild4", "orgChild4")
      .where("current_holders.orgRevisionId = :orgRevisionId", { orgRevisionId: findRevision.id })
      .andWhere(requestBody.id == null ? "1=1" : `permissionProfile.orgRootId LIKE :rootId`, {
        rootId: requestBody.id,
      })
      .andWhere(
        requestBody.searchKeyword != undefined &&
          requestBody.searchKeyword != null &&
          requestBody.searchKeyword != ""
          ? queryLike
          : "1=1",
        {
          keyword: `%${requestBody.searchKeyword}%`,
        },
      )
      // .andWhere(`current_holders.orgRevisionId LIKE :orgRevisionId`, {
      //   orgRevisionId: findRevision.id,
      // })
      .orderBy("current_holders.posMasterNo", "ASC")
      .skip((requestBody.page - 1) * requestBody.pageSize)
      .take(requestBody.pageSize)
      .getManyAndCount();

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

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

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

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

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

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

        return {
          id: _data.id,
          profileId: _data.profileId,
          orgRootId: _data.orgRootId,
          isCheck: _data.isCheck,
          isEdit: _data.isEdit,
          orgNew: _data.orgRootTree?.orgRootName,
          avatar: _data.profileTree?.avatar,
          avatarName: _data.profileTree?.avatarName,
          prefix: _data.profileTree?.prefix,
          rank: _data.profileTree?.rank,
          firstName: _data.profileTree?.firstName,
          lastName: _data.profileTree?.lastName,
          org:
            (_child4 == null ? "" : _child4 + "\n") +
            (_child3 == null ? "" : _child3 + "\n") +
            (_child2 == null ? "" : _child2 + "\n") +
            (_child1 == null ? "" : _child1 + "\n") +
            (_root == null ? "" : _root),
          posNo: shortName,
          position: _data.profileTree?.position,
          posType: _data.profileTree?.posType == null ? null : _data.profileTree?.posType.posTypeName,
          posLevel:
            _data.profileTree?.posLevel == null ? null : _data.profileTree?.posLevel.posLevelName,
        };
      }),
    );
    return new HttpSuccess({ data, total });
  }

  /**
   * API สร้างรายการ body สิทธิ์โครงสร้าง
   *
   * @summary - CRUD สิทธิ์โครงสร้าง (ADMIN)
   *
   */
  @Post()
  async Post(
    @Request() request: RequestWithUser,
    @Body() requestBody: { nodeId: string; personId: string[]; isEdit: boolean; isCheck: boolean },
  ) {
    // if (!request.user.role.includes("SUPER_ADMIN")) {
    //   throw new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์ใช้งานระบบนี้");
    // }
    const orgRoot = await this.orgRootRepository.findOne({
      where: { id: requestBody.nodeId },
    });
    if (!orgRoot) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลสำนัก");
    }
    const profile = await this.profileRepository.find({
      where: { id: In(requestBody.personId) },
    });
    if (profile.length == 0) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลทะเบียนประวัติ");
    }

    const checkDup = await this.permissionProfileRepository.findOne({
      where: {
        orgRootTree: { id: requestBody.nodeId },
        profileTree: { id: In(requestBody.personId) },
      },
    });

    if (checkDup) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "มีสิทธิ์นี้อยู่ในระบบแล้ว");
    }
    const before = null;
    // const _permissionProfile = new PermissionProfile();
    // _permissionProfile.orgRootTree = orgRoot;
    // _permissionProfile.profileTree = profile;
    // _permissionProfile.createdUserId = request.user.sub;
    // _permissionProfile.createdFullName = request.user.name;
    // _permissionProfile.lastUpdateUserId = request.user.sub;
    // _permissionProfile.lastUpdateFullName = request.user.name;
    // _permissionProfile.createdAt = new Date();
    // _permissionProfile.lastUpdatedAt = new Date();
    const _permissionProfile = profile.map((profile) => {
      const permission = new PermissionProfile();
      permission.orgRootId = requestBody.nodeId;
      permission.isEdit = requestBody.isEdit;
      permission.isCheck = requestBody.isCheck;
      permission.profileId = profile.id;
      permission.createdUserId = request.user.sub;
      permission.createdFullName = request.user.name;
      permission.lastUpdateUserId = request.user.sub;
      permission.lastUpdateFullName = request.user.name;
      permission.createdAt = new Date();
      permission.lastUpdatedAt = new Date();
      return permission;
    });

    await this.permissionProfileRepository.save(_permissionProfile, { data: request });
    setLogDataDiff(request, { before, after: _permissionProfile });
    return new HttpSuccess();
  }

  /**
   * API ลบรายการสิทธิ์โครงสร้าง
   *
   * @summary - CRUD สิทธิ์โครงสร้าง (ADMIN)
   *
   * @param {string} id  Id สิทธิ์โครงสร้าง
   */
  @Delete("{id}")
  async Delete(@Request() req: RequestWithUser, @Path() id: string) {
    // if (!request.user.role.includes("SUPER_ADMIN")) {
    //   throw new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์ใช้งานระบบนี้");
    // }
    // const orgRoot = await this.orgRootRepository.findOne({
    //   where: { id: nodeId },
    //   relations: ["permissionProfileRoots"],
    // });
    // if (!orgRoot) {
    //   throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลสำนัก");
    // }
    // const profile = await this.profileRepository.findOne({
    //   where: { id: personId },
    //   relations: ["permissionProfileRoots"],
    // });
    // if (!profile) {
    //   throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลทะเบียนประวัติ");
    // }

    const _delPermissionProfile = await this.permissionProfileRepository.findOne({
      where: { id: id },
    });

    if (!_delPermissionProfile) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบสิทธิ์นี้อยู่ในระบบแล้ว");
    }

    await this.permissionProfileRepository.remove(_delPermissionProfile, { data: req });
    return new HttpSuccess();
  }

  public async listAuthSysOrgFuncByRevisionId(
    request: RequestWithUser,
    system: string,
    revisionId: string,
  ) {
    let profile = await this.profileRepo.findOne({
      where: {
        keycloak: request.user.sub,
      },
      relations: ["next_holders", "next_holders.authRole", "next_holders.authRole.authRoles"],
    });
    if (!profile) {
      return [null];
    }

    let attrOwnership =
      profile?.next_holders
        .filter((x) => x.orgRevisionId == revisionId)[0]
        ?.authRole?.authRoles?.filter((x) => x.authSysId == system)[0]?.attrOwnership || null;

    const posMaster = await this.posMasterRepository.findOne({
      where: {
        next_holderId: profile.id,
        orgRevisionId: revisionId,
      },
    });
    if (!posMaster) {
      return [null];
    } else if (attrOwnership == "OWNER") {
      return null;
    } else {
      return [posMaster.orgRootId];
    }
  }
}
