import {
  Body,
  Controller,
  Delete,
  Get,
  Patch,
  Path,
  Post,
  Request,
  Route,
  Security,
  Tags,
} from "tsoa";
import { AppDataSource } from "../database/data-source";
import {
  CreateProfileInsignia,
  ProfileInsignia,
  UpdateProfileInsignia,
} from "../entities/ProfileInsignia";
import HttpSuccess from "../interfaces/http-success";
import HttpStatus from "../interfaces/http-status";
import HttpError from "../interfaces/http-error";
import { ProfileInsigniaHistory } from "../entities/ProfileInsigniaHistory";
import { RequestWithUser } from "../middlewares/user";
import { Profile } from "../entities/Profile";
import { Insignia } from "../entities/Insignia";
import permission from "../interfaces/permission";
import { setLogDataDiff } from "../interfaces/utils";
import { ProfileSalary } from "../entities/ProfileSalary";
import { In, IsNull } from "typeorm";
@Route("api/v1/org/profile/insignia")
@Tags("ProfileInsignia")
@Security("bearerAuth")
export class ProfileInsigniaController extends Controller {
  private profileRepo = AppDataSource.getRepository(Profile);
  private insigniaRepo = AppDataSource.getRepository(ProfileInsignia);
  private insigniaHistoryRepo = AppDataSource.getRepository(ProfileInsigniaHistory);
  private insigniaMetaRepo = AppDataSource.getRepository(Insignia);
  private profileSalaryRepo = AppDataSource.getRepository(ProfileSalary);

  @Get("user")
  public async getInsigniaUser(@Request() request: { user: Record<string, any> }) {
    const profile = await this.profileRepo.findOneBy({ keycloak: request.user.sub });
    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }
    const record = await this.insigniaRepo.find({
      relations: {
        insignia: {
          insigniaType: true,
        },
      },
      where: { profileId: profile.id, isDeleted: false },
      order: { createdAt: "ASC" },
    });
    return new HttpSuccess(record);
  }

  @Get("{profileId}")
  public async getInsignia(@Path() profileId: string, @Request() req: RequestWithUser) {
    let _workflow = await new permission().Workflow(req, profileId, "SYS_REGISTRY_OFFICER");
    if (_workflow == false)
      await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_OFFICER", profileId);
    const record = await this.insigniaRepo.find({
      relations: {
        insignia: {
          insigniaType: true,
        },
      },
      where: { profileId, isDeleted: false },
      order: { createdAt: "ASC" },
    });
    return new HttpSuccess(record);
  }

  @Get("admin/history/{InsigniaId}")
  public async getInsigniaAdminHistory(
    @Path() InsigniaId: string,
    @Request() req: RequestWithUser,
  ) {
    const _record = await this.insigniaRepo.findOneBy({ id: InsigniaId });
    if (_record) {
      let _workflow = await new permission().Workflow(req, InsigniaId, "SYS_REGISTRY_OFFICER");
      if (_workflow == false)
        await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_OFFICER", _record.profileId);
    }
    const record = await this.insigniaHistoryRepo.find({
      relations: {
        insignia: {
          insigniaType: true,
        },
      },
      where: {
        profileInsigniaId: InsigniaId,
      },
      order: { createdAt: "DESC" },
    });
    return new HttpSuccess(record);
  }

  @Get("history/{InsigniaId}")
  public async getInsigniaHistory(@Path() InsigniaId: string) {
    const record = await this.insigniaHistoryRepo.find({
      relations: {
        insignia: {
          insigniaType: true,
        },
      },
      where: {
        profileInsigniaId: InsigniaId,
      },
      order: { createdAt: "DESC" },
    });
    return new HttpSuccess(record);
  }

  @Post()
  public async newInsignia(@Request() req: RequestWithUser, @Body() body: CreateProfileInsignia) {
    if (!body.profileId) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileId");
    }

    const profile = await this.profileRepo.findOneBy({ id: body.profileId });
    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }
    await new permission().PermissionOrgUserUpdate(req, "SYS_REGISTRY_OFFICER", profile.id);

    const insignia = await this.insigniaMetaRepo.findOne({
      where: { id: body.insigniaId },
    });
    if (!insignia) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลเครื่องราชฯ นี้");
    }
    const before = null;
    const data = new ProfileInsignia();

    const meta = {
      createdUserId: req.user.sub,
      createdFullName: req.user.name,
      lastUpdateUserId: req.user.sub,
      lastUpdateFullName: req.user.name,
      createdAt: new Date(),
      lastUpdatedAt: new Date(),
    };

    Object.assign(data, { ...body, ...meta });
    const history = new ProfileInsigniaHistory();
    Object.assign(history, { ...data, id: undefined });

    await this.insigniaRepo.save(data, { data: req });
    setLogDataDiff(req, { before, after: data });
    history.profileInsigniaId = data.id;
    await this.insigniaHistoryRepo.save(history, { data: req });

    return new HttpSuccess(data.id);
  }

  @Patch("{insigniaId}")
  public async editInsignia(
    @Request() req: RequestWithUser,
    @Body() body: UpdateProfileInsignia,
    @Path() insigniaId: string,
  ) {
    const record = await this.insigniaRepo.findOneBy({ id: insigniaId });
    if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    await new permission().PermissionOrgUserUpdate(req, "SYS_REGISTRY_OFFICER", record.profileId);

    const insignia = await this.insigniaMetaRepo.findOne({
      where: { id: body.insigniaId },
    });
    if (!insignia) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลเครื่องราชฯ นี้");
    }
    const before = structuredClone(record);
    const history = new ProfileInsigniaHistory();

    Object.assign(record, body);
    Object.assign(history, { ...record, id: undefined });

    history.profileInsigniaId = insigniaId;
    record.lastUpdateUserId = req.user.sub;
    record.lastUpdateFullName = req.user.name;
    record.lastUpdatedAt = new Date();
    history.lastUpdateUserId = req.user.sub;
    history.lastUpdateFullName = req.user.name;
    history.createdUserId = req.user.sub;
    history.createdFullName = req.user.name;
    history.createdAt = new Date();
    history.lastUpdatedAt = new Date();

    this.insigniaRepo.save(record, { data: req });
    setLogDataDiff(req, { before, after: record });
    if (!(Object.keys(body).length === 1 && body.isUpload)) {
      this.insigniaHistoryRepo.save(history, { data: req });
      // setLogDataDiff(req, { before, after: history });
    }

    return new HttpSuccess();
  }

  /**
   * API ลบข้อมูลเครื่องราชอิสริยาภรณ์
   * @summary API ลบข้อมูลเครื่องราชอิสริยาภรณ์
   * @param insigniaId คีย์เครื่องราชอิสริยาภรณ์
   */
  @Patch("update-delete/{insigniaId}")
  public async updateIsDeleted(
    @Request() req: RequestWithUser,
    @Path() insigniaId: string,
  ) {
    const record = await this.insigniaRepo.findOneBy({ id: insigniaId });
    if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    if (record.isDeleted === true) {
      return new HttpSuccess();
    }
    await new permission().PermissionOrgUserDelete(req, "SYS_REGISTRY_OFFICER", record.profileId);
    const before = structuredClone(record);
    const history = new ProfileInsigniaHistory();
    const now = new Date();
    record.isDeleted = true;
    record.lastUpdateUserId = req.user.sub;
    record.lastUpdateFullName = req.user.name;
    record.lastUpdatedAt = now;

    Object.assign(history, { ...record, id: undefined });
    history.profileInsigniaId = insigniaId;
    history.createdUserId = req.user.sub;
    history.createdFullName = req.user.name;
    history.createdAt = now;

    await Promise.all([
      this.insigniaRepo.save(record, { data: req }),
      setLogDataDiff(req, { before, after: record }),
      this.insigniaHistoryRepo.save(history, { data: req }),
    ]);

    return new HttpSuccess();
  }

  @Delete("{insigniaId}")
  public async deleteInsignia(@Path() insigniaId: string, @Request() req: RequestWithUser) {
    const _record = await this.insigniaRepo.findOneBy({ id: insigniaId });
    if (_record) {
      await new permission().PermissionOrgUserDelete(
        req,
        "SYS_REGISTRY_OFFICER",
        _record.profileId,
      );
    }
    await this.insigniaHistoryRepo.delete({
      profileInsigniaId: insigniaId,
    });

    const result = await this.insigniaRepo.delete({ id: insigniaId });

    if (result.affected == undefined || result.affected <= 0) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    }

    return new HttpSuccess();
  }

  @Post("dump-db")
  public async newInsigniaDumpDB(
    @Request() req: RequestWithUser,
    @Body() body: CreateProfileInsignia,
  ) {
    if (!body.profileId) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileId");
    }

    const profile = await this.profileRepo.findOneBy({ id: body.profileId });

    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }

    const insignia = await this.insigniaMetaRepo.findOne({
      where: { name: body.insigniaId },
    });
    if (!insignia) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลเครื่องราชฯ นี้");
    }

    const data = new ProfileInsignia();

    const meta = {
      createdUserId: req.user.sub,
      createdFullName: req.user.name,
      lastUpdateUserId: req.user.sub,
      lastUpdateFullName: req.user.name,
      createdAt: new Date(),
      lastUpdatedAt: new Date(),
    };

    Object.assign(data, { ...body, ...meta });
    data.insigniaId = insignia.id;
    await this.insigniaRepo.save(data);

    return new HttpSuccess();
  }

  /**
   * @summary ข้อมูลตำแหน่งและเงินเดือน (ใช้ในรายงานประวัติสำหรับการเสนอขอพระราชทานเหรียญจักรพรรดิมาลา)
   */
  @Post("position")
  public async GetPprofileSalarys(
    @Request() req: RequestWithUser,
    @Body() body: { profileId: string },
  ) {
    const profile = await this.profileRepo.findOneBy({ id: body.profileId });
    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }
    const profileSalarys = await this.profileSalaryRepo.find({
      where: [
        {
          profileId: body.profileId,
          commandCode: In([
            "0",
            "9",
            "1",
            "2",
            "3",
            "4",
            "8",
            "10",
            "11",
            "12",
            "13",
            "14",
            "15",
            "16",
            "20",
          ]),
        },
        { profileId: body.profileId, commandCode: IsNull() },
      ],
      order: { order: "ASC" },
    });
    if (!profileSalarys) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบข้อมูลตำแหน่งและเงินเดือน");
    }
    const birth = new Date(profile.birthDate);
    const mapData = profileSalarys.map((x) => {
      // คำนวณอายุ
      let age = null;
      if (x.commandDateAffect && profile.birthDate) {
        const affect = new Date(x.commandDateAffect);
        age = affect.getFullYear() - birth.getFullYear();
        // เช็คเดือน/วัน ถ้าวันเกิดยังไม่มาถึงในปีนั้น ให้ลบ 1
        const monthDiff = affect.getMonth() - birth.getMonth();
        const dayDiff = affect.getDate() - birth.getDate();
        if (monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)) {
          age--;
        }
      }
      return {
        dateAffect: x.commandDateAffect,
        position: x.positionName,
        root: x.orgRoot,
        child1: x.orgChild1,
        child2: x.orgChild2,
        child3: x.orgChild3,
        child4: x.orgChild4,
        age: age,
        amount: x.amount,
        remark: x.remark,
      };
    });
    return new HttpSuccess(mapData);
  }
}
