import { AppDataSource } from "../database/data-source";
import { OrgRevision } from "../entities/OrgRevision";
import { OrgRoot } from "../entities/OrgRoot";
import { OrgChild2 } from "../entities/OrgChild2";
import { OrgChild3, CreateOrgChild3, UpdateOrgChild3 } from "../entities/OrgChild3";
import { OrgChild4 } from "../entities/OrgChild4";
import { Body, Delete, Get, Path, Post, Put, Response, Route, Tags, Request, Security } from "tsoa";
import HttpStatusCode from "../interfaces/http-status";
import HttpSuccess from "../interfaces/http-success";
import HttpError from "../interfaces/http-error";
import { In } from "typeorm";
import { PosMaster } from "../entities/PosMaster";
import { Position } from "../entities/Position";
import { EmployeePosMaster } from "../entities/EmployeePosMaster";
import { EmployeePosition } from "../entities/EmployeePosition";
import { RequestWithUser } from "../middlewares/user";
import permission from "../interfaces/permission";
import { setLogDataDiff } from "../interfaces/utils";
@Route("api/v1/org/child3")
@Tags("OrgChild3")
@Security("bearerAuth")
@Response(
  HttpStatusCode.INTERNAL_SERVER_ERROR,
  "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง",
)
export class OrgChild3Controller {
  private child2Repository = AppDataSource.getRepository(OrgChild2);
  private child3Repository = AppDataSource.getRepository(OrgChild3);
  private child4Repository = AppDataSource.getRepository(OrgChild4);
  private posMasterRepository = AppDataSource.getRepository(PosMaster);
  private positionRepository = AppDataSource.getRepository(Position);
  private orgRevisionRepository = AppDataSource.getRepository(OrgRevision);
  private empPosMasterRepository = AppDataSource.getRepository(EmployeePosMaster);
  private empPositionRepository = AppDataSource.getRepository(EmployeePosition);

  /**
   * API รายละเอียดโครงสร้างระดับ 3
   *
   * @summary ORG_019 - รายละเอียดโครงสร้างระดับ3 (ADMIN) #18
   *
   * @param {string} id Id Child3
   */
  @Get("{id}")
  async GetChild3(@Path() id: string) {
    const orgChild3 = await this.child3Repository.findOne({
      where: { id },
      relations: ["orgRoot", "orgChild1", "orgChild2"],
    });
    if (!orgChild3) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงสร้างระดับ 3");
    }
    const getOrgChild3 = {
      orgChild3Id: orgChild3.id,
      responsibility: orgChild3.responsibility,
      orgRootName: orgChild3.orgRoot.orgRootName,
      orgName: `${orgChild3.orgChild3Name}/${orgChild3.orgChild2.orgChild2Name}/${orgChild3.orgChild1.orgChild1Name}/${orgChild3.orgRoot.orgRootName}`,
      orgChild3Name: orgChild3.orgChild3Name,
      orgChild3ShortName: orgChild3.orgChild3ShortName,
      orgChild3Code: orgChild3.orgChild3Code,
      orgChild3Rank: orgChild3.orgChild3Rank,
      orgChild3RankSub: orgChild3.orgChild3RankSub,
      orgChild3Order: orgChild3.orgChild3Order,
      orgChild3PhoneEx: orgChild3.orgChild3PhoneEx,
      orgChild3PhoneIn: orgChild3.orgChild3PhoneIn,
      orgChild3Fax: orgChild3.orgChild3Fax,
      orgRevisionId: orgChild3.orgRevisionId,
      misId: orgChild3.misId,
      DEPARTMENT_CODE: orgChild3.DEPARTMENT_CODE,
      DIVISION_CODE: orgChild3.DIVISION_CODE,
      SECTION_CODE: orgChild3.SECTION_CODE,
      JOB_CODE: orgChild3.JOB_CODE,
      orgCode: orgChild3.orgRoot.orgRootCode + orgChild3.orgChild3Code,
    };
    return new HttpSuccess(getOrgChild3);
  }

  /**
   *   API สร้างโครงสร้างระดับ3
   *
   * @summary ORG_010 - สร้างโครงสร้างระดับ3 (ADMIN) #10
   *
   */
  @Post()
  async save(@Body() requestBody: CreateOrgChild3, @Request() request: RequestWithUser) {
    await new permission().PermissionCreate(request, "SYS_ORG");
    const child2 = await this.child2Repository.findOne({
      where: { id: requestBody.orgChild2Id },
    });
    if (!child2) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "not found.");
    }

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

    const validOrgChild3Ranks = ["OFFICE", "DIVISION", "SECTION"];
    if (!validOrgChild3Ranks.includes(requestBody.orgChild3Rank.toUpperCase())) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "not found. orgChild3Rank");
    }
    const order: any = await this.child3Repository.findOne({
      where: {
        orgChild2Id: requestBody.orgChild2Id,
      },
      order: { orgChild3Order: "DESC" },
    });
    const before = null;
    const child3 = Object.assign(new OrgChild3(), requestBody) as OrgChild3;
    child3.orgChild3Name = requestBody.orgChild3Name;
    child3.createdUserId = request.user.sub;
    child3.createdFullName = request.user.name;
    child3.lastUpdateUserId = request.user.sub;
    child3.lastUpdateFullName = request.user.name;
    child3.createdAt = new Date();
    child3.lastUpdatedAt = new Date();
    child3.orgRootId = String(child2?.orgRootId);
    child3.orgChild1Id = String(child2?.orgChild1Id);
    child3.orgRevisionId = String(child2?.orgRevisionId);
    child3.orgChild2Id = String(child2?.id);
    child3.orgChild3Order =
      order == null || order.orgChild3Order == null ? 1 : order.orgChild3Order + 1;
    await this.child3Repository.save(child3, { data: request });
    // update ancestorDNA = id row
    child3.ancestorDNA = child3.id;
    await this.child3Repository.save(child3, { data: request });
    setLogDataDiff(request, { before, after: child3 });
    return new HttpSuccess();
  }

  /**
   * API แก้ไขโครงสร้างระดับ3
   *
   * @summary ORG_011 - แก้ไขโครงสร้างระดับ3 (ADMIN) #11
   *
   * @param {string} id id สร้างโครงสร้างระดับ3
   */
  @Put("{id}")
  async Edit(
    @Path() id: string,
    @Body() requestBody: UpdateOrgChild3,
    @Request() request: RequestWithUser,
  ) {
    await new permission().PermissionUpdate(request, "SYS_ORG");
    const child2IdExits = await this.child2Repository.findOne({
      where: { id: requestBody.orgChild2Id },
    });
    if (!child2IdExits) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "not found. Child2Id");
    }

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

    const validOrgChild3Ranks = ["OFFICE", "DIVISION", "SECTION"];
    if (
      requestBody.orgChild3Rank == null ||
      !validOrgChild3Ranks.includes(requestBody.orgChild3Rank.toUpperCase())
    ) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "not found. orgChild2Rank");
    }

    const child3 = await this.child3Repository.findOne({ where: { id } });
    if (!child3) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "not found.");
    }
    const _null: any = null;
    const before = structuredClone(child3);
    child3.lastUpdateUserId = request.user.sub;
    child3.lastUpdateFullName = request.user.name;
    child3.lastUpdatedAt = new Date();
    child3.orgRootId = String(child2IdExits?.orgRootId);
    child3.orgChild1Id = String(child2IdExits?.orgChild1Id);
    child3.orgRevisionId = String(child2IdExits?.orgRevisionId);
    child3.orgChild2Id = String(child2IdExits?.id);
    this.child3Repository.merge(child3, {
      orgChild3Name: requestBody.orgChild3Name,
      orgChild3ShortName: requestBody.orgChild3ShortName,
      orgChild3Code: requestBody.orgChild3Code,
      orgChild3Rank: requestBody.orgChild3Rank != null ? requestBody.orgChild3Rank : _null,
      orgChild3RankSub: requestBody.orgChild3RankSub,
      DEPARTMENT_CODE: requestBody.DEPARTMENT_CODE != null ? requestBody.DEPARTMENT_CODE : _null,
      DIVISION_CODE: requestBody.DIVISION_CODE != null ? requestBody.DIVISION_CODE : _null,
      SECTION_CODE: requestBody.SECTION_CODE != null ? requestBody.SECTION_CODE : _null,
      JOB_CODE: requestBody.JOB_CODE != null ? requestBody.JOB_CODE : _null,
      orgChild3PhoneEx: requestBody.orgChild3PhoneEx,
      orgChild3PhoneIn: requestBody.orgChild3PhoneIn,
      orgChild3Fax: requestBody.orgChild3Fax,
      responsibility: requestBody.responsibility ?? "",
      misId: requestBody.misId,
    });
    await this.child3Repository.save(child3, { data: request });
    setLogDataDiff(request, { before, after: child3 });
    return new HttpSuccess();
  }

  /**
   * API ลบโครงสร้างระดับ3
   *
   * @summary ORG_012 - ลบโครงสร้างระดับ3 (ADMIN) #12
   *
   * @param {string} id id สร้างโครงสร้างระดับ3
   */
  @Delete("{id}")
  async delete(@Path() id: string, @Request() request: RequestWithUser) {
    await new permission().PermissionDelete(request, "SYS_ORG");
    const child3 = await this.child3Repository.findOne({ where: { id } });
    if (!child3) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "not found.");
    }

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

    // const exitsChild4 = await this.child4Repository.findOne({ where: { orgChild3Id: id } });
    // if (exitsChild4) {
    //   throw new HttpError(
    //     HttpStatusCode.INTERNAL_SERVER_ERROR,
    //     "ไม่สามารถลบได้ เนื่องจาก id ผูกกับโครงสร้างระดับ4",
    //   );
    // }
    const posMasters = await this.posMasterRepository.find({
      where: { orgChild3Id: id },
    });
    const positions = await this.positionRepository.find({
      where: [{ posMasterId: In(posMasters.map((x) => x.id)) }],
    });
    const empPosMasters = await this.empPosMasterRepository.find({
      where: { orgRootId: id },
    });
    const empPositions = await this.empPositionRepository.find({
      where: [{ posMasterId: In(empPosMasters.map((x) => x.id)) }],
    });

    await this.empPositionRepository.remove(empPositions, { data: request });
    await this.empPosMasterRepository.remove(empPosMasters, { data: request });
    await this.positionRepository.remove(positions, { data: request });
    await this.posMasterRepository.remove(posMasters, { data: request });
    await this.child4Repository.delete({ orgChild3Id: id });
    await this.child3Repository.delete(id);
    return new HttpSuccess();
  }
}
