import {
  Controller,
  Post,
  Put,
  Delete,
  Route,
  Security,
  Tags,
  Body,
  Path,
  Request,
  Response,
  Get,
  Query,
} from "tsoa";
import { AppDataSource } from "../database/data-source";
import HttpSuccess from "../interfaces/http-success";
import HttpStatusCode from "../interfaces/http-status";
import HttpError from "../interfaces/http-error";
import { CommandSalary, CreateCommandSalary, UpdateCommandSalary } from "../entities/CommandSalary";
import { CommandSys } from "../entities/CommandSys";
import { Brackets } from "typeorm";

@Route("api/v1/org/commandSalary")
@Tags("CommandSalary")
@Security("bearerAuth")
@Response(
  HttpStatusCode.INTERNAL_SERVER_ERROR,
  "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง",
)
export class CommandSalaryController extends Controller {
  private commandSalaryRepository = AppDataSource.getRepository(CommandSalary);
  private commandSysRepository = AppDataSource.getRepository(CommandSys);

  /**
   * API  list รายการประเภทคำสั่ง
   *
   * @summary ORG_056 - CRUD ประเภทคำสั่ง (ADMIN) #61
   *
   */
  @Get("list")
  async Get(@Query() commandSysId: string) {
    const _commandSalary = await this.commandSalaryRepository.find({
      where: { isActive: true, commandSysId: commandSysId },
      select: [
        "id",
        "name",
        "commandSysId",
        "createdAt",
        "lastUpdatedAt",
        "createdFullName",
        "lastUpdateFullName",
      ],
      order: { createdAt: "ASC" },
    });
    return new HttpSuccess(_commandSalary);
  }

  /**
   * API  list รายการประเภทคำสั่ง
   *
   * @summary ORG_056 - CRUD ประเภทคำสั่ง (ADMIN) #61
   *
   */
  @Get("admin")
  async GetAdmin(
    @Query("page") page: number = 1,
    @Query("pageSize") pageSize: number = 10,
    @Query() commandSysId?: string | null,
    @Query() isActive?: boolean | null,
    @Query() searchKeyword?: string | null,
  ) {
    const [commandSalarys, total] = await this.commandSalaryRepository
      .createQueryBuilder("commandSalary")
      .andWhere(
        isActive != null && isActive != undefined ? "commandSalary.isActive = :isActive" : "1=1",
        {
          isActive:
            isActive == null || isActive == undefined ? null : `${isActive == true ? 1 : 0}`,
        },
      )
      .andWhere(
        commandSysId != null && commandSysId != undefined && commandSysId != ""
          ? "commandSalary.commandSysId = :commandSysId"
          : "1=1",
        {
          commandSysId:
            commandSysId == null || commandSysId == undefined || commandSysId == ""
              ? null
              : `${commandSysId}`,
        },
      )
      .andWhere(
        new Brackets((qb) => {
            qb.where(
              searchKeyword != undefined && searchKeyword != null && searchKeyword != ""
                ? "name LIKE :keyword"
                : "1=1",
              {
                keyword: `%${searchKeyword}%`,
              },
            )
        }),
      )
      .orderBy("commandSalary.createdAt", "ASC")
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getManyAndCount();
    return new HttpSuccess({ commandSalarys, total });
  }

  /**
   * API รายละเอียดรายการประเภทคำสั่ง
   *
   * @summary ORG_056 - CRUD ประเภทคำสั่ง (ADMIN) #61
   *
   * @param {string} id  Id  ประเภทคำสั่ง
   */
  @Get("{id}")
  async GetById(@Path() id: string) {
    const _commandSalary = await this.commandSalaryRepository.findOne({
      where: { id },
      select: ["id", "name", "commandSysId", "isActive"],
    });
    if (!_commandSalary) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
    }
    return new HttpSuccess(_commandSalary);
  }

  /**
   * API สร้างรายการ body ประเภทคำสั่ง
   *
   * @summary ORG_056 - CRUD ประเภทคำสั่ง (ADMIN) #61
   *
   */
  @Post()
  async Post(
    @Body()
    requestBody: CreateCommandSalary,
    @Request() request: { user: Record<string, any> },
  ) {
    const _commandSalary = Object.assign(new CommandSalary(), requestBody);

    // const checkName = await this.commandSalaryRepository.findOne({
    //   where: { name: requestBody.name },
    // });

    // if (checkName) {
    //   throw new HttpError(HttpStatusCode.NOT_FOUND, "ชื่อ Template นี้มีอยู่ในระบบแล้ว");
    // }

    const checkNameSys = await this.commandSysRepository.findOne({
      where: { id: requestBody.commandSysId },
    });

    if (!checkNameSys) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ชื่อประเภทนี้มีอยู่ในระบบ");
    }

    _commandSalary.createdUserId = request.user.sub;
    _commandSalary.createdFullName = request.user.name;
    _commandSalary.lastUpdateUserId = request.user.sub;
    _commandSalary.lastUpdateFullName = request.user.name;
    _commandSalary.createdAt = new Date();
    _commandSalary.lastUpdatedAt = new Date();
    await this.commandSalaryRepository.save(_commandSalary);
    return new HttpSuccess(_commandSalary.id);
  }

  /**
   * API  แก้ไขรายการ body ประเภทคำสั่ง
   *
   * @summary ORG_056 - CRUD ประเภทคำสั่ง (ADMIN) #61
   *
   * @param {string} id  Id ประเภทคำสั่ง
   */
  @Put("{id}")
  async Put(
    @Path() id: string,
    @Body()
    requestBody: UpdateCommandSalary,
    @Request() request: { user: Record<string, any> },
  ) {
    const _commandSalary = await this.commandSalaryRepository.findOne({ where: { id: id } });
    if (!_commandSalary) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล Template นี้");
    }
    // const checkName = await this.commandSalaryRepository.findOne({
    //   where: { id: Not(id), name: requestBody.name },
    // });
    // if (checkName) {
    //   throw new HttpError(HttpStatusCode.NOT_FOUND, "ชื่อนี้มีอยู่ในระบบแล้ว");
    // }

    const checkNameSys = await this.commandSysRepository.findOne({
      where: { id: requestBody.commandSysId },
    });

    if (!checkNameSys) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ชื่อประเภทนี้มีอยู่ในระบบ");
    }

    _commandSalary.lastUpdateUserId = request.user.sub;
    _commandSalary.lastUpdateFullName = request.user.name;
    _commandSalary.lastUpdatedAt = new Date();
    this.commandSalaryRepository.merge(_commandSalary, requestBody);
    await this.commandSalaryRepository.save(_commandSalary);
    return new HttpSuccess(_commandSalary.id);
  }

  /**
   * API ลบรายการประเภทคำสั่ง
   *
   * @summary ORG_056 - CRUD ประเภทคำสั่ง (ADMIN) #61
   *
   * @param {string} id  Id ประเภทคำสั่ง
   */
  @Delete("{id}")
  async Delete(@Path() id: string) {
    const _delCommandSalary = await this.commandSalaryRepository.findOne({
      where: { id: id },
    });
    if (!_delCommandSalary) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล Template นี้");
    }
    await this.commandSalaryRepository.delete(_delCommandSalary.id);
    return new HttpSuccess();
  }
}
