import { AppDataSource } from "../database/data-source";
import { OrgRevision } from "../entities/OrgRevision";
import { OrgRoot } from "../entities/OrgRoot";
import { OrgChild1, CreateOrgChild1, UpdateOrgChild1 } from "../entities/OrgChild1";
import { OrgChild2 } from "../entities/OrgChild2";
import { OrgChild3 } from "../entities/OrgChild3";
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, Not } from "typeorm";
import { OrgChild4 } from "../entities/OrgChild4";
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/child1")
@Tags("OrgChild1")
@Security("bearerAuth")
@Response(
  HttpStatusCode.INTERNAL_SERVER_ERROR,
  "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง",
)
export class OrgChild1Controller {
  private orgRootRepository = AppDataSource.getRepository(OrgRoot);
  private child1Repository = AppDataSource.getRepository(OrgChild1);
  private child2Repository = AppDataSource.getRepository(OrgChild2);
  private child3Repository = AppDataSource.getRepository(OrgChild3);
  private child4Repository = AppDataSource.getRepository(OrgChild4);
  private 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 รายละเอียดโครงสร้างระดับ 1
   *
   * @summary ORG_017 - รายละเอียดโครงสร้างระดับ1 (ADMIN) #17
   *
   * @param {string} id Id Child1
   */
  @Get("{id}")
  async GetChild1(@Path() id: string) {
    const orgChild1 = await this.child1Repository.findOne({
      where: { id },
      relations: ["orgRoot"],
    });
    if (!orgChild1) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงสร้างระดับ 1");
    }
    const getOrgChild1 = {
      orgChild1Id: orgChild1.id,
      responsibility: orgChild1.responsibility,
      orgRootName: orgChild1.orgRoot.orgRootName,
      orgName: `${orgChild1.orgChild1Name}/${orgChild1.orgRoot.orgRootName}`,
      orgChild1Name: orgChild1.orgChild1Name,
      orgChild1ShortName: orgChild1.orgChild1ShortName,
      orgChild1Code: orgChild1.orgChild1Code,
      orgChild1Rank: orgChild1.orgChild1Rank,
      orgChild1RankSub: orgChild1.orgChild1RankSub,
      orgChild1Order: orgChild1.orgChild1Order,
      orgChild1PhoneEx: orgChild1.orgChild1PhoneEx,
      orgChild1PhoneIn: orgChild1.orgChild1PhoneIn,
      orgChild1Fax: orgChild1.orgChild1Fax,
      orgRevisionId: orgChild1.orgRevisionId,
      isOfficer: orgChild1.isOfficer,
      isInformation: orgChild1.isInformation,
      misId: orgChild1.misId,
      DEPARTMENT_CODE: orgChild1.DEPARTMENT_CODE,
      DIVISION_CODE: orgChild1.DIVISION_CODE,
      SECTION_CODE: orgChild1.SECTION_CODE,
      JOB_CODE: orgChild1.JOB_CODE,
      orgCode: orgChild1.orgRoot.orgRootCode + orgChild1.orgChild1Code,
    };
    return new HttpSuccess(getOrgChild1);
  }

  /**
   *   API สร้างโครงสร้างระดับ1
   *
   * @summary ORG_004 - สร้างโครงสร้างระดับ1 (ADMIN) #4
   *
   */
  @Post()
  async save(@Body() requestBody: CreateOrgChild1, @Request() request: RequestWithUser) {
    await new permission().PermissionCreate(request, "SYS_ORG");
    const rootIdExits = await this.orgRootRepository.findOne({
      where: { id: requestBody.orgRootId },
      relations: ["orgChild1s"],
    });
    if (!rootIdExits) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "not found. orgRootId");
    }

    if (requestBody.isOfficer == true) {
      const orgRevision = await this.orgRevisionRepository.findOne({
        where: { id: rootIdExits.orgRevisionId },
        relations: ["orgChild1s"],
      });
      if (orgRevision != null) {
        await Promise.all(
          orgRevision.orgChild1s
            .filter((x: OrgChild1) => x.isOfficer == true)
            .map(async (item: OrgChild1) => {
              item.isOfficer = false;
              await this.child1Repository.save(item);
            }),
        );
      }
    }

    if (requestBody.isInformation == true) {
      const orgRevision = await this.orgRevisionRepository.findOne({
        where: { id: rootIdExits.orgRevisionId },
        relations: ["orgChild1s"],
      });
      if (orgRevision != null) {
        await Promise.all(
          orgRevision.orgChild1s
            .filter((x: OrgChild1) => x.isInformation == true)
            .map(async (item: OrgChild1) => {
              item.isInformation = false;
              await this.child1Repository.save(item);
            }),
        );
      }
    }

    const revisionIdExits = await this.orgRevisionRepository.findOne({
      where: { id: rootIdExits.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 validOrgChild1Ranks = ["OFFICE", "DIVISION", "SECTION"];
    if (!validOrgChild1Ranks.includes(requestBody.orgChild1Rank.toUpperCase())) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "not found. orgChild1Rank");
    }

    if (rootIdExits.orgRootRankSub == "BUREAU") {
      const chkCode = await this.child1Repository.findOne({
        where: {
          orgRevisionId: rootIdExits.orgRevisionId,
          orgRootId: requestBody.orgRootId,
          orgChild1Code: requestBody.orgChild1Code,
        },
      });
      if (chkCode != null) {
        throw new HttpError(
          HttpStatusCode.INTERNAL_SERVER_ERROR,
          "รหัสส่วนราชการนี้มีอยู่ในระบบแล้ว",
        );
      }
      const chkShort = await this.child1Repository.findOne({
        where: {
          orgRevisionId: rootIdExits.orgRevisionId,
          orgRootId: requestBody.orgRootId,
          orgChild1ShortName: requestBody.orgChild1ShortName,
        },
      });
      if (chkShort != null) {
        throw new HttpError(HttpStatusCode.NOT_FOUND, "อักษรย่อนี้มีอยู่ในระบบแล้ว");
      }
    }

    // if (requestBody.orgChild1Code == rootIdExits.orgRootCode) {
    //   throw new HttpError(HttpStatusCode.NOT_FOUND, "รหัสส่วนราชการนี้ซ้ำกับรหัสหน่วยงาน");
    // }
    // if (requestBody.orgChild1ShortName == rootIdExits.orgRootShortName) {
    //   throw new HttpError(HttpStatusCode.NOT_FOUND, "อักษรย่อนี้ซ้ำกับอักษรย่อหน่วยงาน");
    // }

    const order: any = await this.child1Repository.findOne({
      where: {
        orgRootId: requestBody.orgRootId,
      },
      order: { orgChild1Order: "DESC" },
    });
    const before = null;
    const child1 = Object.assign(new OrgChild1(), requestBody) as OrgChild1;
    child1.orgChild1Name = requestBody.orgChild1Name;
    child1.createdUserId = request.user.sub;
    child1.createdFullName = request.user.name;
    child1.lastUpdateUserId = request.user.sub;
    child1.lastUpdateFullName = request.user.name;
    child1.createdAt = new Date();
    child1.lastUpdatedAt = new Date();
    child1.orgRevisionId = String(rootIdExits?.orgRevisionId);
    child1.orgRootId = String(rootIdExits?.id);
    child1.orgChild1Order =
      order == null || order.orgChild1Order == null ? 1 : order.orgChild1Order + 1;
    await this.child1Repository.save(child1, { data: request });
    // update ancestorDNA = id row
    child1.ancestorDNA = child1.id;
    await this.child1Repository.save(child1, { data: request });
    setLogDataDiff(request, { before, after: child1 });
    return new HttpSuccess();
  }

  /**
   * API แก้ไขโครงสร้างระดับ1
   *
   * @summary ORG_005 - แก้ไขโครงสร้างระดับ1 (ADMIN) #5
   *
   * @param {string} id id สร้างโครงสร้างระดับ1
   */
  @Put("{id}")
  async Edit(
    @Path() id: string,
    @Body() requestBody: UpdateOrgChild1,
    @Request() request: RequestWithUser,
  ) {
    await new permission().PermissionUpdate(request, "SYS_ORG");
    const rootIdExits = await this.orgRootRepository.findOne({
      where: { id: requestBody.orgRootId },
      relations: ["orgChild1s"],
    });
    if (!rootIdExits) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "not found. RootId");
    }

    if (requestBody.isOfficer == true) {
      const orgRevision = await this.orgRevisionRepository.findOne({
        where: { id: rootIdExits.orgRevisionId },
        relations: ["orgChild1s"],
      });
      if (orgRevision != null) {
        await Promise.all(
          orgRevision.orgChild1s
            .filter((x: OrgChild1) => x.isOfficer == true)
            .map(async (item: OrgChild1) => {
              item.isOfficer = false;
              await this.child1Repository.save(item);
            }),
        );
      }
    }

    if (requestBody.isInformation == true) {
      const orgRevision = await this.orgRevisionRepository.findOne({
        where: { id: rootIdExits.orgRevisionId },
        relations: ["orgChild1s"],
      });
      if (orgRevision != null) {
        await Promise.all(
          orgRevision.orgChild1s
            .filter((x: OrgChild1) => x.isInformation == true)
            .map(async (item: OrgChild1) => {
              item.isInformation = false;
              await this.child1Repository.save(item);
            }),
        );
      }
    }

    const revisionIdExits = await this.orgRevisionRepository.findOne({
      where: { id: rootIdExits.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 validOrgChild1Ranks = ["OFFICE", "DIVISION", "SECTION"];
    if (
      requestBody.orgChild1Rank == null ||
      !validOrgChild1Ranks.includes(requestBody.orgChild1Rank.toUpperCase())
    ) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "not found. orgChild1Rank");
    }

    const child1 = await this.child1Repository.findOne({ where: { id } });
    if (!child1) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "not found.");
    }

    if (rootIdExits.orgRootRankSub == "BUREAU") {
      const chkCode = await this.child1Repository.findOne({
        where: {
          id: Not(id),
          orgRevisionId: rootIdExits.orgRevisionId,
          orgRootId: requestBody.orgRootId,
          orgChild1Code: requestBody.orgChild1Code,
        },
      });
      if (chkCode != null) {
        throw new HttpError(HttpStatusCode.NOT_FOUND, "รหัสส่วนราชการนี้มีอยู่ในระบบแล้ว");
      }
      const chkShort = await this.child1Repository.findOne({
        where: {
          id: Not(id),
          orgRevisionId: rootIdExits.orgRevisionId,
          orgRootId: requestBody.orgRootId,
          orgChild1ShortName: requestBody.orgChild1ShortName,
        },
      });
      if (chkShort != null) {
        throw new HttpError(HttpStatusCode.NOT_FOUND, "อักษรย่อนี้มีอยู่ในระบบแล้ว");
      }
    }

    // if(requestBody.orgChild1Code == rootIdExits.orgRootCode){
    //   throw new HttpError(HttpStatusCode.NOT_FOUND, "รหัสส่วนราชการนี้ซ้ำกับรหัสหน่วยงาน");
    // }
    // if(requestBody.orgChild1ShortName == rootIdExits.orgRootShortName){
    //   throw new HttpError(HttpStatusCode.NOT_FOUND, "อักษรย่อนี้ซ้ำกับอักษรย่อหน่วยงาน");
    // }
    const _null: any = null;
    const before = structuredClone(child1);

    child1.lastUpdateUserId = request.user.sub;
    child1.lastUpdateFullName = request.user.name;
    child1.lastUpdatedAt = new Date();
    child1.orgRevisionId = String(rootIdExits?.orgRevisionId);
    child1.orgRootId = String(rootIdExits?.id);
    child1.responsibility = child1.responsibility || "";
    this.child1Repository.merge(child1, {
      orgChild1Name: requestBody.orgChild1Name,
      orgChild1ShortName: requestBody.orgChild1ShortName,
      orgChild1Code: requestBody.orgChild1Code,
      orgChild1Rank: requestBody.orgChild1Rank != null ? requestBody.orgChild1Rank : _null,
      orgChild1RankSub: requestBody.orgChild1RankSub,
      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,
      isOfficer: requestBody.isOfficer,
      isInformation: requestBody.isInformation,
      orgChild1PhoneEx: requestBody.orgChild1PhoneEx,
      orgChild1PhoneIn: requestBody.orgChild1PhoneIn,
      orgChild1Fax: requestBody.orgChild1Fax,
      misId: requestBody.misId,
    });
    await this.child1Repository.save(child1, { data: request });
    setLogDataDiff(request, { before, after: child1 });

    const up_Child2 = await this.child2Repository.find({
      where: {
        orgRevisionId: rootIdExits.orgRevisionId,
        orgRootId: requestBody.orgRootId,
        orgChild1Id: child1.id,
      },
    });
    if (up_Child2.length > 0) {
      for (const _child2 of up_Child2) {
        _child2.orgChild2ShortName = String(requestBody.orgChild1ShortName);
        _child2.orgChild2Code = String(requestBody.orgChild1Code);
      }
      await this.child2Repository.save(up_Child2);
    }

    const up_Child3 = await this.child3Repository.find({
      where: {
        orgRevisionId: rootIdExits.orgRevisionId,
        orgRootId: requestBody.orgRootId,
        orgChild1Id: child1.id,
      },
    });
    if (up_Child3.length > 0) {
      for (const _child3 of up_Child3) {
        _child3.orgChild3ShortName = String(requestBody.orgChild1ShortName);
        _child3.orgChild3Code = String(requestBody.orgChild1Code);
      }
      await this.child3Repository.save(up_Child3);
    }

    const up_Child4 = await this.child4Repository.find({
      where: {
        orgRevisionId: rootIdExits.orgRevisionId,
        orgRootId: requestBody.orgRootId,
        orgChild1Id: child1.id,
      },
    });
    if (up_Child4.length > 0) {
      for (const _child4 of up_Child4) {
        _child4.orgChild4ShortName = String(requestBody.orgChild1ShortName);
        _child4.orgChild4Code = String(requestBody.orgChild1Code);
      }
      await this.child4Repository.save(up_Child4);
    }

    return new HttpSuccess();
  }

  /**
   * API ลบโครงสร้างระดับ1
   *
   * @summary ORG_006 - ลบโครงสร้างระดับ1 (ADMIN) #6
   *
   * @param {string} id id สร้างโครงสร้างระดับ1
   */
  @Delete("{id}")
  async delete(@Path() id: string, @Request() request: RequestWithUser) {
    await new permission().PermissionDelete(request, "SYS_ORG");
    const child1 = await this.child1Repository.findOne({ where: { id } });
    if (!child1) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "not found.");
    }
    const revisionIdExits = await this.orgRevisionRepository.findOne({
      where: { id: child1.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 exitsChild2 = await this.child2Repository.findOne({ where: { orgChild1Id: id } });
    // if (exitsChild2) {
    //   throw new HttpError(
    //     HttpStatusCode.INTERNAL_SERVER_ERROR,
    //     "ไม่สามารถลบได้ เนื่องจาก id ผูกกับโครงสร้างระดับ2",
    //   );
    // }
    const posMasters = await this.posMasterRepository.find({
      where: { orgChild1Id: 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({ orgChild1Id: id });
    await this.child3Repository.delete({ orgChild1Id: id });
    await this.child2Repository.delete({ orgChild1Id: id });
    await this.child1Repository.delete({ id });
    return new HttpSuccess();
  }
}
