import { AppDataSource } from "../database/data-source";
import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Route,
  Security,
  Tags,
  Path,
  Body,
  Request,
  Example,
  Response,
} 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 { OrgRevision } from "../entities/OrgRevision";
import { OrgRoot } from "../entities/OrgRoot";
import { CreateOrgChild2, OrgChild2, UpdateOrgChild2 } from "../entities/OrgChild2";
import { OrgChild1 } from "../entities/OrgChild1";
import { OrgChild3 } from "../entities/OrgChild3";
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/child2")
@Tags("OrgChild2")
@Security("bearerAuth")
@Response(
  HttpStatusCode.INTERNAL_SERVER_ERROR,
  "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง",
)
export class OrgChild2Controller extends Controller {
  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 รายละเอียดโครงสร้างระดับ 2
   *
   * @summary ORG_018 - รายละเอียดโครงสร้างระดับ2 (ADMIN) #20
   *
   * @param {string} id Id Child2
   */
  @Get("{id}")
  async GetChild2(@Path() id: string) {
    const orgChild2 = await this.child2Repository.findOne({
      where: { id },
      relations: ["orgRoot", "orgChild1"],
    });
    if (!orgChild2) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงสร้างระดับ 2");
    }
    const getOrgChild2 = {
      orgChild2Id: orgChild2.id,
      responsibility: orgChild2.responsibility,
      orgRootName: orgChild2.orgRoot.orgRootName,
      orgName: `${orgChild2.orgChild2Name}/${orgChild2.orgChild1.orgChild1Name}/${orgChild2.orgRoot.orgRootName}`,
      orgChild2Name: orgChild2.orgChild2Name,
      orgChild2ShortName: orgChild2.orgChild2ShortName,
      orgChild2Code: orgChild2.orgChild2Code,
      orgChild2Rank: orgChild2.orgChild2Rank,
      orgChild2RankSub: orgChild2.orgChild2RankSub,
      orgChild2Order: orgChild2.orgChild2Order,
      orgChild2PhoneEx: orgChild2.orgChild2PhoneEx,
      orgChild2PhoneIn: orgChild2.orgChild2PhoneIn,
      orgChild2Fax: orgChild2.orgChild2Fax,
      orgRevisionId: orgChild2.orgRevisionId,
      misId: orgChild2.misId,
      DEPARTMENT_CODE: orgChild2.DEPARTMENT_CODE,
      DIVISION_CODE: orgChild2.DIVISION_CODE,
      SECTION_CODE: orgChild2.SECTION_CODE,
      JOB_CODE: orgChild2.JOB_CODE,
      orgCode: orgChild2.orgRoot.orgRootCode + orgChild2.orgChild2Code,
    };
    return new HttpSuccess(getOrgChild2);
  }

  /**
   * สร้างโครงสร้างระดับ2 Child2
   *
   * @summary ORG_007 - สร้างโครงสร้างระดับ2 (ADMIN) #7
   *
   */
  @Post()
  @Example([
    {
      orgChild2Name: "string", //ชื่อหน่วยงาน
      orgChild2ShortName: "string", //อักษรย่อ
      orgChild2Code: "string", //รหัสหน่วยงาน
      // orgChild2Order: "number", //ลำดับที่ของหน่วยงาน
      orgChild2PhoneEx: "string", //หมายเลขโทรศัพท์ที่ติดต่อจากภายนอก
      orgChild2PhoneIn: "string", //หมายเลขโทรศัพท์ที่ติดต่อจากภายใน
      orgChild2Fax: "string", //หมายเลขโทรสาร
      //   orgChild2IsNormal: "boolean", //สถานะของหน่วยงาน
      orgChild1Id: "Guid", //id Child1
    },
  ])
  async create(
    @Body()
    requestBody: CreateOrgChild2,
    @Request() request: RequestWithUser,
  ) {
    await new permission().PermissionCreate(request, "SYS_ORG");
    const child1 = await this.child1Repository.findOne({
      where: { id: requestBody.orgChild1Id },
    });
    if (!child1) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "not found. Child1Id");
    }

    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 validOrgChild2Ranks = ["OFFICE", "DIVISION", "SECTION"];
    if (!validOrgChild2Ranks.includes(requestBody.orgChild2Rank.toUpperCase())) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "not found. orgChild2Rank");
    }
    const order: any = await this.child2Repository.findOne({
      where: {
        orgChild1Id: requestBody.orgChild1Id,
      },
      order: { orgChild2Order: "DESC" },
    });
    const before = null;
    const child2 = Object.assign(new OrgChild2(), requestBody) as OrgChild2;
    child2.orgChild2Name = requestBody.orgChild2Name;
    child2.createdUserId = request.user.sub;
    child2.createdFullName = request.user.name;
    child2.lastUpdateUserId = request.user.sub;
    child2.lastUpdateFullName = request.user.name;
    child2.createdAt = new Date();
    child2.lastUpdatedAt = new Date();
    child2.orgRootId = String(child1?.orgRootId);
    child2.orgRevisionId = String(child1?.orgRevisionId);
    child2.orgChild1Id = String(child1?.id);
    child2.orgChild2Order =
      order == null || order.orgChild2Order == null ? 1 : order.orgChild2Order + 1;
    await this.child2Repository.save(child2, { data: request });
    // update ancestorDNA = id row
    child2.ancestorDNA = child2.id;
    await this.child2Repository.save(child2, { data: request });
    setLogDataDiff(request, { before, after: child2 });
    return new HttpSuccess();
  }

  /**
   * แก้ไขโครงสร้างระดับ2 Child2
   *
   * @summary ORG_008 - แก้ไขโครงสร้างระดับ2 (ADMIN) #8
   *
   * @param {string} id  Guid, *Id Child2
   */
  @Put("{id}")
  @Example([
    {
      orgChild2Name: "string", //ชื่อหน่วยงาน
      orgChild2ShortName: "string", //อักษรย่อ
      orgChild2Code: "string", //รหัสหน่วยงาน
      // orgChild2Order: "number", //ลำดับที่ของหน่วยงาน
      orgChild2PhoneEx: "string", //หมายเลขโทรศัพท์ที่ติดต่อจากภายนอก
      orgChild2PhoneIn: "string", //หมายเลขโทรศัพท์ที่ติดต่อจากภายใน
      orgChild2Fax: "string", //หมายเลขโทรสาร
      //   orgChild2IsNormal: "boolean", //สถานะของหน่วยงาน
      orgChild1Id: "Guid", //id Child1
    },
  ])
  async update(
    @Path() id: string,
    @Body()
    requestBody: UpdateOrgChild2,
    @Request() request: RequestWithUser,
  ) {
    await new permission().PermissionUpdate(request, "SYS_ORG");
    const child1IdExits = await this.child1Repository.findOne({
      where: { id: requestBody.orgChild1Id },
    });
    if (!child1IdExits) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "not found. Child1Id");
    }

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

    const child2 = await this.child2Repository.findOne({ where: { id } });
    if (!child2) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "not found.");
    }
    const _null: any = null;
    const before = structuredClone(child2);
    child2.lastUpdateUserId = request.user.sub;
    child2.lastUpdateFullName = request.user.name;
    child2.lastUpdatedAt = new Date();
    child2.orgRootId = String(child1IdExits?.orgRootId);
    child2.orgRevisionId = String(child1IdExits?.orgRevisionId);
    child2.orgChild1Id = String(child1IdExits?.id);
    this.child2Repository.merge(child2, {
      orgChild2Name: requestBody.orgChild2Name,
      orgChild2ShortName: requestBody.orgChild2ShortName,
      orgChild2Code: requestBody.orgChild2Code,
      orgChild2Rank: requestBody.orgChild2Rank != null ? requestBody.orgChild2Rank : _null,
      orgChild2RankSub: requestBody.orgChild2RankSub,
      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,
      orgChild2PhoneEx: requestBody.orgChild2PhoneEx,
      orgChild2PhoneIn: requestBody.orgChild2PhoneIn,
      orgChild2Fax: requestBody.orgChild2Fax,
      responsibility: requestBody.responsibility ?? "",
      misId: requestBody.misId,
    });
    await this.child2Repository.save(child2, { data: request });
    setLogDataDiff(request, { before, after: child2 });
    return new HttpSuccess();
  }

  /**
   * ลบโครงสร้างระดับ Child2
   *
   * @summary ORG_009 - ลบโครงสร้างระดับ2 (ADMIN) #9
   *
   * @param {string} id  Guid, *Id Child2
   */
  @Delete("{id}")
  async delete(@Path() id: string, @Request() request: RequestWithUser) {
    await new permission().PermissionDelete(request, "SYS_ORG");
    const child2 = await this.child2Repository.findOne({ where: { id } });
    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 exitsChild3 = await this.child3Repository.findOne({ where: { orgChild2Id: id } });
    // if (exitsChild3) {
    //   throw new HttpError(
    //     HttpStatusCode.INTERNAL_SERVER_ERROR,
    //     "ไม่สามารถลบได้ เนื่องจาก id ผูกกับโครงสร้างระดับ4",
    //   );
    // }
    const posMasters = await this.posMasterRepository.find({
      where: { orgChild2Id: 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({ orgChild2Id: id });
    await this.child3Repository.delete({ orgChild2Id: id });
    await this.child2Repository.delete({ id });
    return new HttpSuccess();
  }
}
