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 { ActivatedRoute, Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { Employee, 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;
  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 officeDocs!: Array<any>;
  public certDocs!: Array<any>;
  public authoDocs!: Array<any>;
  public formData: FormData = new FormData();

  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.officeDocs = [];
    this.certDocs = [];
    this.authoDocs = [];
  }

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

  private readOnlyForm() {
    this.enable == '1' ? this.documentsAutho?.enable() : this.documentsAutho?.disable()
    this.enable == '1' ? this.documentOffice?.enable() : this.documentOffice?.disable()
    this.enable == '1' ? this.documentsCert?.enable() : this.documentsCert?.disable()
    this.enable == '1' ? this.contactName?.enable() : this.contactName?.disable()
    this.enable == '1' ? this.contactTelephone?.enable() : this.contactTelephone?.disable()
    this.enable == '1' ? this.contactAddress?.enable() : this.contactAddress?.disable()
    this.enable == '1' ? this.contractType?.enable() : this.contractType?.disable()
    this.enable == '1' ? this.speciality?.enable() : this.speciality?.disable()
    this.enable == '1' ? this.subcontratistId?.enable() : this.subcontratistId?.disable()
    this.enable == '1' ? this.workteamId?.enable() : this.workteamId?.disable()
    this.enable == '1' ? this.userId?.enable() : this.userId?.disable()
  }

  private createFormGroup() {
    return new FormGroup({
      documentsAutho: new FormControl(''),
      documentOffice: new FormControl(''),
      documentsCert: new FormControl(''),
      userId: new FormControl('', Validators.required),
      contactName: 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);
    if (this.idEmployee != "0") {
      this.getData();
    }
    console.log(this.idEmployee);
  }

  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;
    console.log(await this.employeeObject());
    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;
    console.log("Fallo 1");
    console.log(await this.employeeObject());
    console.log("Fallo 2");
    await lastValueFrom(this._employeeService.updateEmployee(await this.employeeObject(), this.idEmployee)).then(
      (responseData: ResponseData) => {
        this._resourcesService.openSnackBar("¡Registro Exitoso!");
        this._router.navigate(["/sam/GPRS/employee"]);
      }, (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
    this.isLoadingForm = false;
  }

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

  public 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 getData() {
    console.log(this.idEmployee);
    await lastValueFrom(this._employeeService.getEmployeeById(this.idEmployee)).then(
      (responseData: ResponseDataEmployee) => {
        this.putDataOnForm(responseData.response);
      }, (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.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.officeDocs.length > 0) { this.formData.append('DOCUMENT_OFFICE', this.officeDocs[0]); }
    if (this.authoDocs.length > 0) { this.formData.append('DOCUMENTS_AUTHO', this.authoDocs[0]); }
    if (this.authoDocs.length > 1) { this.formData.append('DOCUMENTS_AUTHO2', this.authoDocs[1]); }
    if (this.certDocs.length > 0) { this.formData.append('DOCUMENTS_CERT', this.certDocs[0]); }
    if (this.certDocs.length > 1) { this.formData.append('DOCUMENTS_CERT2', this.certDocs[1]); }
    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_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");
    if(this.updateDocuments.value) { this.formData.append('UPLOAD_NEW_DOCUMENTS', "Y")} else { this.formData.append('UPLOAD_NEW_DOCUMENTS', "N") }
    return this.formData;
  }

  checkFile(event: any, type: string) {
    let filesArray: Array<any> = event.target.files;

    if (type == "Autho") {
      if (event.target.files.length > 2 || (event.target.files.length > 1 && this.authoDocs.length == 1)) {
        this._resourcesService.openSnackBar('El maximo de archivos permitidos es de 2');
        this.documentsAutho.reset();
      } else {
        Array.from(filesArray).forEach(value => {
          if (value.name.split(".")[1] != 'pdf') {
            this.documentsAutho.reset();
            this.authoDocs = [];
            return this._resourcesService.openSnackBar('Solo se permiten archivos PDF');
          }
          this.authoDocs.push(value);

        });
        console.log(this.authoDocs);
      }
    }

    if (type == "Cert") {
      if (event.target.files.length > 2 || (event.target.files.length > 1 && this.certDocs.length == 1)) {
        this._resourcesService.openSnackBar('El maximo de archivos permitidos es de 2');
        this.documentsCert.reset();
      } else {
        Array.from(filesArray).forEach(value => {
          if (value.name.split(".")[1] != 'pdf') {
            this.documentsCert.reset();
            this.certDocs = [];
            return this._resourcesService.openSnackBar('Solo se permiten archivos PDF');
          }
          this.certDocs.push(value);

        });
        console.log(this.certDocs);
      }
    }

    if (type == "Office") {
      if (filesArray[0].name.split(".")[1] != 'pdf') {
        this.documentOffice.reset();
        this.officeDocs = [];
        return this._resourcesService.openSnackBar('Solo se permiten archivos PDF');
      }
      this.officeDocs.push(filesArray[0]);
    }
  }

  public deleteFiles(type: string) {
    if (type === "Autho") {
      this.documentsAutho.reset();
      this.authoDocs = [];
    } else if (type === "Cert") {
      this.documentsCert.reset();
      this.certDocs = [];
    } else {
      this.documentOffice.reset();
      this.officeDocs = [];
    }
  }

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

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

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

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

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

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

  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
}
