import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Route,
  Security,
  Tags,
  Body,
  Path,
  Request,
  Example,
} from "tsoa";
import { CreateOrgRoot, OrgRoot } from "../entities/OrgRoot";
import { AppDataSource } from "../database/data-source";
import HttpSuccess from "../interfaces/http-success";
import { OrgChild1 } from "../entities/OrgChild1";
import { In, Not } from "typeorm";
import HttpError from "../interfaces/http-error";
import HttpStatusCode from "../interfaces/http-status";
import { OrgRevision } from "../entities/OrgRevision";
import { OrgChild2 } from "../entities/OrgChild2";
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 permission from "../interfaces/permission";
import { RequestWithUser } from "../middlewares/user";
import { setLogDataDiff } from "../interfaces/utils";

@Route("api/v1/org/root")
@Tags("OrgRoot")
@Security("bearerAuth")
export class OrgRootController extends Controller {
  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 orgRevisionRepository = AppDataSource.getRepository(OrgRevision);
  private posMasterRepository = AppDataSource.getRepository(PosMaster);
  private positionRepository = AppDataSource.getRepository(Position);
  private empPosMasterRepository = AppDataSource.getRepository(EmployeePosMaster);
  private empPositionRepository = AppDataSource.getRepository(EmployeePosition);

  /**
   * API รายละเอียดโครงสร้างระดับ Root
   *
   * @summary ORG_016 - รายละเอียดโครงสร้างระดับ Root (ADMIN) #16
   *
   * @param {string} id  Id Root
   */
  @Get("{id}")
  async GetRoot(@Path() id: string) {
    const orgRoot = await this.orgRootRepository.findOne({ where: { id } });
    if (!orgRoot) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงสร้างระดับ Root นี้");
    }
    const getOrgRoot = {
      orgRootId: orgRoot.id,
      orgRootName: orgRoot.orgRootName,
      orgName: "-",
      orgRootShortName: orgRoot.orgRootShortName,
      orgRootCode: orgRoot.orgRootCode,
      orgRootRank: orgRoot.orgRootRank,
      orgRootRankSub: orgRoot.orgRootRankSub,
      orgRootOrder: orgRoot.orgRootOrder,
      orgRootPhoneEx: orgRoot.orgRootPhoneEx,
      orgRootPhoneIn: orgRoot.orgRootPhoneIn,
      orgRootFax: orgRoot.orgRootFax,
      orgRevisionId: orgRoot.orgRevisionId,
      isDeputy: orgRoot.isDeputy,
      orgCode: orgRoot.orgRootCode + "00",
    };
    return new HttpSuccess(getOrgRoot);
  }

  /**
   * สร้างโครงสร้างระดับ Root
   *
   * @summary ORG_001 - สร้างโครงสร้างระดับ Root (ADMIN) #1
   *
   */
  @Post()
  @Example([
    {
      orgRootName: "string", //ชื่อหน่วยงาน
      orgRootShortName: "string", //อักษรย่อ
      orgRootCode: "string", //รหัสหน่วยงาน
      orgRootPhoneEx: "string", //หมายเลขโทรศัพท์ที่ติดต่อจากภายนอก
      orgRootPhoneIn: "string", //หมายเลขโทรศัพท์ที่ติดต่อจากภายใน
      orgRootFax: "string", //หมายเลขโทรสาร
      orgRootIsNormal: "boolean", //สถานะของหน่วยงาน
    },
  ])
  async create(
    // @Path() id: string,
    @Body()
    requestBody: CreateOrgRoot,
    @Request() request: RequestWithUser,
  ) {
    await new permission().PermissionCreate(request, "SYS_ORG");

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

    const validOrgRootRanks = ["DEPARTMENT", "OFFICE", "DIVISION", "SECTION"];
    if (!validOrgRootRanks.includes(requestBody.orgRootRank.toUpperCase())) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "not found. orgRootRank");
    }

    const orgRoot = Object.assign(new OrgRoot(), requestBody);
    if (!orgRoot) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
    }

    const chkCode = await this.orgRootRepository.findOne({
      where: { orgRevisionId: requestBody.orgRevisionId, orgRootCode: requestBody.orgRootCode },
    });
    if (chkCode != null) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "รหัสหน่วยงานนี้มีอยู่ในระบบแล้ว");
    }

    const chkShort = await this.orgRootRepository.findOne({
      where: {
        orgRevisionId: requestBody.orgRevisionId,
        orgRootShortName: requestBody.orgRootShortName,
      },
    });
    if (chkShort != null) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "อักษรย่อนี้มีอยู่ในระบบแล้ว");
    }

    const orgRevision = await this.orgRevisionRepository.findOne({
      where: { id: requestBody.orgRevisionId },
    });
    if (!orgRevision) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "not found. RevisionId");
    }

    if (orgRevision.orgRevisionIsDraft != true && orgRevision.orgRevisionIsCurrent != false) {
      throw new HttpError(
        HttpStatusCode.NOT_FOUND,
        "not found. orgRevisionIsDraft:true, orgRevisionIsCurrent:false",
      );
    }
    const order: any = await this.orgRootRepository.findOne({
      where: {
        orgRevisionId: requestBody.orgRevisionId,
      },
      order: { orgRootOrder: "DESC" },
    });
    const before = null;
    orgRoot.createdUserId = request.user.sub;
    orgRoot.createdFullName = request.user.name;
    orgRoot.lastUpdateUserId = request.user.sub;
    orgRoot.lastUpdateFullName = request.user.name;
    orgRoot.createdAt = new Date();
    orgRoot.lastUpdatedAt = new Date();
    orgRoot.orgRootOrder = order == null || order.orgRootOrder == null ? 1 : order.orgRootOrder + 1;
    await this.orgRootRepository.save(orgRoot, { data: request });
    setLogDataDiff(request, { before, after: orgRoot });

    return new HttpSuccess();
  }

  /**
   * แก้ไขโครงสร้างระดับ Root
   *
   * @summary ORG_002 - แก้ไขโครงสร้างระดับ Root (ADMIN) #2
   *
   * @param {string} id  Guid, *Id root
   */
  @Put("{id}")
  @Example([
    {
      orgRootName: "string", //ชื่อหน่วยงาน
      orgRootShortName: "string", //อักษรย่อ
      orgRootCode: "string", //รหัสหน่วยงาน
      orgRootPhoneEx: "string", //หมายเลขโทรศัพท์ที่ติดต่อจากภายนอก
      orgRootPhoneIn: "string", //หมายเลขโทรศัพท์ที่ติดต่อจากภายใน
      orgRootFax: "string", //หมายเลขโทรสาร
      orgRootIsNormal: "boolean", //สถานะของหน่วยงาน
    },
  ])
  async update(
    @Path() id: string,
    @Body()
    requestBody: CreateOrgRoot,
    @Request() request: RequestWithUser,
  ) {
    await new permission().PermissionUpdate(request, "SYS_ORG");
    const validOrgRootRanks = ["DEPARTMENT", "OFFICE", "DIVISION", "SECTION"];
    if (!validOrgRootRanks.includes(requestBody.orgRootRank.toUpperCase())) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "not found. orgRo otRank");
    }

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

    const revisionIdExits = await this.orgRevisionRepository.findOne({
      where: { id: requestBody.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 chkCode = await this.orgRootRepository.findOne({
      where: {
        orgRevisionId: requestBody.orgRevisionId,
        orgRootCode: requestBody.orgRootCode,
        id: Not(id),
      },
    });
    if (chkCode != null) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "รหัสหน่วยงานนี้มีอยู่ในระบบแล้ว");
    }

    const chkShort = await this.orgRootRepository.findOne({
      where: {
        orgRevisionId: requestBody.orgRevisionId,
        orgRootShortName: requestBody.orgRootShortName,
        id: Not(id),
      },
    });
    if (chkShort != null) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "อักษรย่อนี้มีอยู่ในระบบแล้ว");
    }

    const orgRoot = await this.orgRootRepository.findOne({ where: { id } });
    if (!orgRoot) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงสร้างระดับ Root นี้");
    }

    // const chkCodeChild1 = await this.child1Repository.findOne({
    //   where:{
    //     orgRevisionId : requestBody.orgRevisionId,
    //     orgRootId: id,
    //     orgChild1Code: requestBody.orgRootCode,
    //   }
    // });
    // if(chkCodeChild1 != null){
    //   throw new HttpError(HttpStatusCode.NOT_FOUND, "รหัสหน่วยงานนี้ซ้ำกับรหัสส่วนราชการ");
    // }
    // const chkShortChild1 = await this.child1Repository.findOne({
    //   where:{
    //     orgRevisionId : requestBody.orgRevisionId,
    //     orgRootId: id,
    //     orgChild1ShortName: requestBody.orgRootShortName,
    //   }
    // });
    // if(chkShortChild1 != null){
    //   throw new HttpError(HttpStatusCode.NOT_FOUND, "อักษรย่อนี้ซ้ำกับอักษรย่อส่วนราชการ");
    // }
    const before = structuredClone(orgRoot);
    orgRoot.lastUpdateUserId = request.user.sub;
    orgRoot.lastUpdateFullName = request.user.name;
    orgRoot.lastUpdatedAt = new Date();
    this.orgRootRepository.merge(orgRoot, requestBody);
    await this.orgRootRepository.save(orgRoot, { data: request });
    setLogDataDiff(request, { before, after: orgRoot });

    if (orgRoot.orgRootRankSub == "DISTRICT" || orgRoot.orgRootRankSub == "OFFICE") {
      const up_Child1 = await this.child1Repository.find({
        where: {
          orgRevisionId: orgRoot.orgRevisionId,
          orgRootId: id,
        },
      });
      if (up_Child1.length > 0) {
        for (const _child1 of up_Child1) {
          _child1.orgChild1ShortName = String(requestBody.orgRootShortName);
          _child1.orgChild1Code = String(requestBody.orgRootCode);
        }
        await this.child1Repository.save(up_Child1);
      }
      const up_Child2 = await this.child2Repository.find({
        where: {
          orgRevisionId: orgRoot.orgRevisionId,
          orgRootId: id,
        },
      });
      if (up_Child2.length > 0) {
        for (const _child2 of up_Child2) {
          _child2.orgChild2ShortName = String(requestBody.orgRootShortName);
          _child2.orgChild2Code = String(requestBody.orgRootCode);
        }
        await this.child2Repository.save(up_Child2);
      }

      const up_Child3 = await this.child3Repository.find({
        where: {
          orgRevisionId: orgRoot.orgRevisionId,
          orgRootId: id,
        },
      });
      if (up_Child3.length > 0) {
        for (const _child3 of up_Child3) {
          _child3.orgChild3ShortName = String(requestBody.orgRootShortName);
          _child3.orgChild3Code = String(requestBody.orgRootCode);
        }
        await this.child3Repository.save(up_Child3);
      }

      const up_Child4 = await this.child4Repository.find({
        where: {
          orgRevisionId: orgRoot.orgRevisionId,
          orgRootId: id,
        },
      });
      if (up_Child4.length > 0) {
        for (const _child4 of up_Child4) {
          _child4.orgChild4ShortName = String(requestBody.orgRootShortName);
          _child4.orgChild4Code = String(requestBody.orgRootCode);
        }
        await this.child4Repository.save(up_Child4);
      }
    }
    return new HttpSuccess();
  }

  /**
   * ลบโครงสร้างระดับ Root
   *
   * @summary ORG_003 - ลบโครงสร้างระดับ Root (ADMIN) #3
   *
   * @param {string} id  Guid, *Id root
   */
  @Delete("{id}")
  async delete(@Path() id: string, @Request() request: RequestWithUser) {
    await new permission().PermissionDelete(request, "SYS_ORG");
    const orgRoot = await this.orgRootRepository.findOne({ where: { id } });
    if (!orgRoot) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงสร้างระดับ Root นี้");
    }

    // const orgChild1 = await this.child1Repository.findOne({ where: { orgRootId: id } });
    // if (orgChild1 != null) {
    //   throw new HttpError(
    //     HttpStatusCode.INTERNAL_SERVER_ERROR,
    //     "ไม่สามารถลบข้อมูลได้เมื่อมีข้อมูลโครงสร้างระดับ1",
    //   );
    // }

    const revisionIdExits = await this.orgRevisionRepository.findOne({
      where: { id: orgRoot.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 posMasters = await this.posMasterRepository.find({
      where: { orgRootId: 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({ orgRootId: id });
    await this.child3Repository.delete({ orgRootId: id });
    await this.child2Repository.delete({ orgRootId: id });
    await this.child1Repository.delete({ orgRootId: id });
    await this.orgRootRepository.delete({ id });

    return new HttpSuccess();
  }
}
