import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { MatTableDataSource } from '@angular/material/table';
import { ActivatedRoute, Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { DownoloadEmployeeInfo, Employee, FilesDocuments, ResponseDataEmployee } from 'src/app/interfaces/personal-managment/employee.interface';
import { ResponseData } from 'src/app/interfaces/response-data';
import { EncService } from 'src/app/services/enc/enc.service';
import { EmployeeService } from 'src/app/services/personal-management/employee.service';
import { SubcontratistService } from 'src/app/services/personal-management/subcontratist.service';
import { WorkTeamService } from 'src/app/services/personal-management/work-team.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';

@Component({
  selector: 'app-employee-form',
  templateUrl: './employee-form.component.html',
  styleUrls: ['./employee-form.component.css']
})
export class EmployeeFormComponent implements OnInit {

  public idEmployee: string;
  private infoEmployee!: DownoloadEmployeeInfo;
  public enable: string;
  public btnSmall: boolean;
  public formGroup: FormGroup;
  public isLoadingForm: boolean;
  public users!: Array<any>;
  public workteams!: Array<any>;
  public subcontratists!: Array<any>;
  public countries!: Array<any>;

  public officeDoc!: Array<any>;
  public certDoc!: Array<any>;
  public authoDoc!: Array<any>;
  public officeDoc2!: Array<any>;
  public certDoc2!: Array<any>;
  public authoDoc2!: Array<any>;
  public nameUpdateDocument!: string;

  public formData: FormData = new FormData();
  public documentsEmployee!: Array<any>;

  public dataSource: MatTableDataSource<any>;
  public displayedColumns: string[] = ['name', 'size', 'type', 'update', 'action'];
  public documents!: Array<FilesDocuments>;


  constructor(
    private _activatedRoute: ActivatedRoute,
    private _employeeService: EmployeeService,
    private _resourcesService: ResourcesService,
    private _workteamService: WorkTeamService,
    private _subcontratistsService: SubcontratistService,
    private _encService: EncService,
    private _router: Router,
    private _dialog: MatDialog,
  ) {
    this.idEmployee = "";
    this.enable = "";
    this.btnSmall = false;
    this.formGroup = this.createFormGroup();
    this.isLoadingForm = false;
    this.officeDoc = [];
    this.certDoc = [];
    this.authoDoc = [];
    this.officeDoc2 = [];
    this.certDoc2 = [];
    this.authoDoc2 = [];
    this.nameUpdateDocument = "";
    this.documents = [];
    this.documentsEmployee = [];
    this.dataSource = new MatTableDataSource<any>();
  }

  ngOnInit(): void {
    this.idEmployee = this._activatedRoute.snapshot.paramMap.get('id')!;
    this.enable = this._activatedRoute.snapshot.paramMap.get('enable')!;
    this.decript();
    this.getWorkteams();
    this.getSubcontratists();
    this.getCountries();
  }

  private createFormGroup() {
    return new FormGroup({
      documentsAutho: new FormControl(''),
      documentOffice: new FormControl(''),
      documentsCert: new FormControl(''),
      userId: new FormControl('', Validators.required),
      contactName: new FormControl('', Validators.required),
      contactLada: new FormControl('', Validators.required),
      contactTelephone: new FormControl('', Validators.required),
      contactAddress: new FormControl('', Validators.required),
      contractType: new FormControl('', Validators.required),
      speciality: new FormControl('', Validators.required),
      subcontratistId: new FormControl('', Validators.required),
      workteamId: new FormControl('', Validators.required),
      updateDocuments: new FormControl(''),
    })
  }

  private async decript() {
    this.idEmployee = await this._encService.desencriptar(this.idEmployee);
    await this.getUsers();
    if (this.idEmployee != "0") {
      this.getData();
    }
  }

  public changeContractType() {
    if (this.enable == "1") {
      if (this.contractType?.value == "Subcontratista") {
        this.subcontratistId?.enable();
      } else {
        this.subcontratistId?.disable();
        this.subcontratistId?.setValue(null);
      }
    }
  }

  public alert() {
    if (this.idEmployee == "0") {
      this._dialog.open(AlertComponent, {
        data: {
          title: 'Registrar Empleado',
          description: '¿Está seguro que desea registrar al empleado?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.storeEmployee();
        }
      });
    } else {
      this._dialog.open(AlertComponent, {
        data: {
          title: 'Actualizar Empleado',
          description: '¿Está seguro que desea actualizar al empleado?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.updateEmployee();
        }
      });
    }

  }

  private async storeEmployee() {
    this.isLoadingForm = true;
    await lastValueFrom(this._employeeService.storeEmployee(await this.employeeObject())).then(
      (responseData: ResponseData) => {
        this._resourcesService.openSnackBar("¡Registro Exitoso!");
        this._router.navigate(["/sam/GPRS/employee"]);
      }, (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
    this.isLoadingForm = false;
  }

  private async updateEmployee() {
    this.isLoadingForm = true;
    await lastValueFrom(this._employeeService.updateEmployee(await this.employeeObject(), this.idEmployee)).then(
      (responseData: ResponseData) => {
        this._resourcesService.openSnackBar("Actualización Exitosa!");
        this._router.navigate(["/sam/GPRS/employee"]);
      }, (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
    this.isLoadingForm = false;
  }

  private async getUsers() {
    console.log(this.idEmployee);
      await lastValueFrom(this._employeeService.getAvaibleUsers(this.idEmployee)).then(
        (responseData: any) => {
          this.users = responseData.response;
        }, (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
      );
  }

  private async getWorkteams() {
    await lastValueFrom(this._workteamService.getActiveWorkteams()).then(
      (responseData: any) => {
        this.workteams = responseData.response;
      }, (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
  }

  private async getSubcontratists() {
    await lastValueFrom(this._subcontratistsService.getActiveSubcontratists()).then(
      (responseData: any) => {
        this.subcontratists = responseData.response;
      }, (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
  }

  private async getCountries() {
    await lastValueFrom(this._subcontratistsService.getCountries()).then(
      (responseData: any) => {
        this.countries = responseData.response;
      }, (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
  }


  private async getData() {
    await lastValueFrom(this._employeeService.getEmployeeById(this.idEmployee)).then(
      (responseData: ResponseDataEmployee) => {
        if (this.enable != "1") {
          this.users.forEach(user => {
            if (user.ID_USER == responseData.response.USER_ID) {
              responseData.response.USER_ID = user.NAME
            }
          });

          this.workteams.forEach(workteam => {
            if (workteam.WORKTEAM_ID == responseData.response.WORKTEAM_ID) {
              responseData.response.WORKTEAM_ID = workteam.NAME
            }
          });

          this.subcontratists.forEach(subcontratist => {
            if (subcontratist.ID_SUBCONTRATIST == responseData.response.SUBCONTRATIST_ID) {
              responseData.response.SUBCONTRATIST_ID = subcontratist.NAME
            }
          });

        }

        this.putDataOnForm(responseData.response);
        this.infoEmployee = {
          SAVED_BY_USER: this.userId.value,
          EMPLOYEE: responseData.response,
        };
      }, (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );

    await lastValueFrom(this._employeeService.getLastDocumentsByEmployee(this.idEmployee)).then(
      (responseData: any) => {
        if (responseData.response.length > 0) {
          responseData.response.forEach((document: any) => {
            this.documentsEmployee.push(document);
          });
        }
      }, (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );


  }

  private async putDataOnForm(employee: Employee) {
    this.userId.setValue(employee.USER_ID)
    this.contactName.setValue(await this._encService.desencriptar(employee.CONTACT_NAME))
    this.contactTelephone.setValue(await this._encService.desencriptar(employee.CONTACT_TELEPHONE))
    this.contactLada.setValue(await this._encService.desencriptar(employee.CONTACT_LADA))
    this.contactAddress.setValue(await this._encService.desencriptar(employee.CONTACT_ADDRESS))
    this.contractType.setValue(employee.CONTRACT_TYPE)
    this.speciality.setValue(employee.SPECIALITY)
    this.subcontratistId.setValue(employee.SUBCONTRATIST_ID)
    this.workteamId.setValue(employee.WORKTEAM_ID)
  }

  private async employeeObject(): Promise<FormData> {
    this.formData.append('USER_ID', this.userId.value);

    if (this.officeDoc.length > 0) { this.formData.append('DOCUMENT_OFFICE', this.officeDoc[0]); }
    this.officeDoc.length > 1 ? this.formData.append('DOCUMENT_OFFICE_UPDATE', this.officeDoc[1]) : this.formData.append('DOCUMENT_OFFICE_UPDATE', "0")

    if (this.authoDoc.length > 0) { this.formData.append('DOCUMENTS_AUTHO', this.authoDoc[0]); }
    this.authoDoc.length > 1 ? this.formData.append('DOCUMENTS_AUTHO_UPDATE', this.authoDoc[1]) : this.formData.append('DOCUMENTS_AUTHO_UPDATE', "0")

    if (this.authoDoc2.length > 0) { this.formData.append('DOCUMENTS_AUTHO2', this.authoDoc2[0]); }
    this.authoDoc2.length > 1 ? this.formData.append('DOCUMENTS_AUTHO2_UPDATE', this.authoDoc2[1]) : this.formData.append('DOCUMENTS_AUTHO2_UPDATE', "0")

    if (this.certDoc.length > 0) { this.formData.append('DOCUMENTS_CERT', this.certDoc[0]); }
    this.certDoc.length > 1 ? this.formData.append('DOCUMENTS_CERT_UPDATE', this.certDoc[1]) : this.formData.append('DOCUMENTS_CERT_UPDATE', "0")

    if (this.certDoc2.length > 0) { this.formData.append('DOCUMENTS_CERT2', this.certDoc2[0]); }
    this.certDoc2.length > 1 ? this.formData.append('DOCUMENTS_CERT2_UPDATE', this.certDoc2[1]) : this.formData.append('DOCUMENTS_CERT2_UPDATE', "0")

    this.formData.append('CONTACT_NAME', await this._encService.encriptar(this.contactName.value.trim()));
    this.formData.append('CONTACT_TELEPHONE', await this._encService.encriptar(this.contactTelephone.value.toString()));
    this.formData.append('CONTACT_LADA', await this._encService.encriptar(this.contactLada.value.toString()));
    this.formData.append('CONTACT_ADDRESS', await this._encService.encriptar(this.contactAddress.value));
    this.formData.append('CONTRACT_TYPE', this.contractType.value);
    this.formData.append('SPECIALITY', this.speciality.value.trim());
    if (this.subcontratistId.value != null) { this.formData.append('SUBCONTRATIST_ID', this.subcontratistId.value); }
    this.formData.append('WORKTEAM_ID', this.workteamId.value);
    this.formData.append('SAVED_BY_USER', this._resourcesService.getUser());
    this.formData.append('LINE_NUMBER', "1");
    return this.formData;
  }

  public saveDocumentToUpdate(event: string) {
    this.nameUpdateDocument = event;
  }

  public checkFile(event: any, type: string) {
    let file: any = event.target.files[0];

    if (file.name.split(".")[1] != 'pdf') {
      return this._resourcesService.openSnackBar('Solo se permiten archivos PDF');
    }

    if (type == "Autho") {
      this.documents.push({
        index: 0,
        file: file,
        type: "Autorización",
        update: this.nameUpdateDocument
      });
      this.authoDoc.push(file);
      if (this.nameUpdateDocument != "") {
        this.authoDoc.push(this.nameUpdateDocument);
      }
    }

    if (type == "Autho2") {
      this.documents.push({
        index: 1,
        file: file,
        type: "Autorización",
        update: this.nameUpdateDocument
      });
      this.authoDoc2.push(file);
      if (this.nameUpdateDocument != "") {
        this.authoDoc2.push(this.nameUpdateDocument);
      }
    }

    if (type == "Office") {
      this.documents.push({
        index: 2,
        file: file,
        type: "Oficio",
        update: this.nameUpdateDocument
      });
      this.officeDoc.push(file);
      if (this.nameUpdateDocument != "") {
        this.officeDoc.push(this.nameUpdateDocument);
      }
    }

    if (type == "Cert") {
      this.documents.push({
        index: 3,
        file: file,
        type: "Certificación",
        update: this.nameUpdateDocument
      });
      this.certDoc.push(file);
      if (this.nameUpdateDocument != "") {
        this.certDoc.push(this.nameUpdateDocument);
      }
    }

    if (type == "Cert2") {
      this.documents.push({
        index: 4,
        file: file,
        type: "Certificación",
        update: this.nameUpdateDocument
      });
      this.certDoc2.push(file);
      if (this.nameUpdateDocument != "") {
        this.certDoc2.push(this.nameUpdateDocument);
      }
    }

    this.dataSource = new MatTableDataSource(this.documents);
    event.target.value = '';
    // Limpia el select de los documentos
    this.nameUpdateDocument = "";
    this.updateDocuments.setValue("");
  }

  public deleteFiles(element: any) {
    if (element.type === "Autorización") {
      if (element.index == 0) {
        this.authoDoc = this.authoDoc = [];
      } else {
        this.authoDoc2 = this.authoDoc2 = [];
      }
    } else if (element.type === "Certificación") {
      if (element.index == 3) {
        this.certDoc = this.certDoc = [];
      } else {
        this.certDoc2 = this.certDoc2 = [];
      }
    } else {
      this.officeDoc = [];
    }
    this.refactorTable(element.index);
  }

  private refactorTable(index: number) {
    let arrayTemp = [];
    for (let i = 0; i < this.documents.length; i++) {
      if (this.documents[i].index !== index) {
        arrayTemp.push(this.documents[i])
      }
    }
    this.documents = arrayTemp;
    this.dataSource = new MatTableDataSource(this.documents);
  }

  public async openDialog(typeForm: string, element?: any) {
    if (typeForm === 'PDF') {
      this._dialog.open(AlertComponent, {
        data: {
          title: 'Ficha de Empleado',
          description: '¿Visualizar la ficha de empleado en PDF?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this._employeeService.DownoloadEmployeeInfoOnPdf(this.infoEmployee).subscribe(
            (val) => window.open(val.response.replace('localhost', '192.168.1.50:8000'))
          );
        }
      });
    } else {
      this._dialog.open(AlertComponent, {
        data: {
          title: 'Ficha de Empleado',
          description: '¿Descargar la ficha de empleado en Excel?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this._employeeService.DownoloadEmployeeInfoOnExcel(this.infoEmployee).subscribe(
            (val) => window.open(val.response.replace('localhost', '192.168.1.50:8000'))
          );
        }
      });
    }
  }

  // Método para reajustar los botones según sus dimensiones
  public onResize(): void {
    this.btnSmall = window.innerWidth <= 1405;
  }

  get contactName() {
    return this.formGroup.get('contactName')!;
  }

  get contactTelephone() {
    return this.formGroup.get('contactTelephone')!;
  }

  get contactLada() {
    return this.formGroup.get('contactLada')!;
  }

  get contactAddress() {
    return this.formGroup.get('contactAddress')!;
  }

  get contractType() {
    return this.formGroup.get('contractType')!;
  }

  get speciality() {
    return this.formGroup.get('speciality')!;
  }

  get subcontratistId() {
    return this.formGroup.get('subcontratistId')!;
  }

  get workteamId() {
    return this.formGroup.get('workteamId')!;
  }
  get userId() {
    return this.formGroup.get('userId')!;
  }
  get updateDocuments() {
    return this.formGroup.get('updateDocuments')!;
  }

}

export interface TempFileInfo {
  id?: number,
  name: string,
  size: string
}
