import { DOCUMENT } from '@angular/common';
import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { ResourcesService } from '../../../services/resources.service';
import { CorrectiveMaintenanceService } from '../../../services/corrective-maintenance.service';
import { GdelService } from '../../../services/gdel.service';
import { EncService } from '../../../services/enc.service';
import { FunctionsService } from '../../../services/functions.service';
import { lastValueFrom } from 'rxjs';
import { ReportsListItem, ReportsListResponse } from '../../../interfaces/corrective-maintenance.interface';

@Component({
    selector: 'app-reports-production',
    templateUrl: './reports-production.component.html',
    styleUrl: './reports-production.component.css',
    standalone: false
})
export class ReportsProductionComponent implements OnInit {
  public btnSmall: boolean = false;

  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  hasSearched: boolean;

  dataSource: MatTableDataSource<any>;
  displayedColumns = ['ID', 'NOMBRE', 'FECHA', 'ACCIONES'];

  startDate: Date | null;
  endDate: Date | null;

  actionControl: FormControl;
  reportTypeControl: FormControl;
  startDateControl: FormControl;
  endDateControl: FormControl;
  orderStateControl: FormControl;

  @ViewChild(MatPaginator) paginator?: MatPaginator;
  @ViewChild(MatSort) sort?: MatSort;

  constructor(
    @Inject(DOCUMENT) private _document: Document,
    private _resourcesService: ResourcesService,
    private _correctiveMaintenanceService: CorrectiveMaintenanceService,
    private _gdelService: GdelService,
    private _encService: EncService,
    private _functionsService: FunctionsService,
  ) {
    this.btnSmall = window.innerWidth <= 1405;
    
    this.isLoading = false;
    this.hasError = false;
    this.errorStr = '';
    this.hasSearched = false;

    this.dataSource = new MatTableDataSource();

    this.startDate = null;
    this.endDate = null;

    this.actionControl = new FormControl('register');
    this.reportTypeControl = new FormControl('');
    this.startDateControl = new FormControl({value: this.startDate, disabled: true});
    this.endDateControl = new FormControl({value: this.endDate, disabled: true});
    this.orderStateControl = new FormControl({value: '', disabled: true});
  }
  
  ngOnInit(): void {
    this.reportTypeControl.valueChanges.subscribe(value => {
      if(value == 'ESTAD'){
        this.orderStateControl.enable();
      }else{
        this.orderStateControl.disable();
      }

      this.startDateControl.enable();
      this.endDateControl.enable();
    });

    this.startDateControl.valueChanges.subscribe((startDate: Date) => {
      this.startDate = startDate;
    });

    this.endDateControl.valueChanges.subscribe((endDate: Date) => {
      this.endDate = endDate;
    });
  }

  public onResize():void {
    this.btnSmall = window.innerWidth <= 1405;
  }

  clearFilters(){
    this.startDate = null;
    this.endDate = null;

    this.reportTypeControl.setValue('');
    this.startDateControl.setValue(null);
    this.endDateControl.setValue(null);
    this.orderStateControl.setValue('');

    this.startDateControl.disable();
    this.endDateControl.disable();
    this.orderStateControl.disable();

    this.dataSource = new MatTableDataSource();
    this.dataSource.paginator = this.paginator!;
    this.dataSource.sort = this.sort!;
  }

  executeAction(){
    let action = this.actionControl.value;
    if(action == 'register'){
      this.generateReport();
    }else if(action == 'search'){
      this.searchReports();
    }
  }

  private async generateReport(){
    try{
      this._resourcesService.openSnackBar('Generando informe...');

      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('report_type', this.reportTypeControl.value);

      if(this.startDate != null){
        let startDateStr = `${this.startDate.getFullYear()}-${this.startDate.getMonth() + 1}-${this.startDate.getDate()}`;
        formData.append('start_date', startDateStr);
      }

      if(this.endDate != null){
        let endDateStr = `${this.endDate.getFullYear()}-${this.endDate.getMonth() + 1}-${this.endDate.getDate()}`;
        formData.append('end_date', endDateStr);
      }

      let orderState = this.orderStateControl.value;
      if(orderState != null && orderState != undefined && orderState != ''){
        formData.append('order_state', orderState);
      }

      let response = await lastValueFrom(this._correctiveMaintenanceService.generateReport(formData));
      let idFile = await this._encService.decrypt(response.response.report);
      let downloadToken = await lastValueFrom(this._gdelService.getDownloadToken(response.response.report, idUser, 1));
      let download = this._document.getElementById(`download`) as HTMLAnchorElement;
  
      download.href = `http://git.ittec.mx/sam/public/api/download-file/${downloadToken.response.TOKEN}/${idUser}/1`;
      download.download = idFile;
      download.click();

      this._resourcesService.openSnackBar('Descarga realizada.');
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  private async searchReports(){
    try{
      this.hasSearched = true;
      this.isLoading = true;
      this.hasError = false,
      this.errorStr = '';

      let idUser = localStorage.getItem('idusuario')!;
      let reportType = '-';
      let startDate = '-';
      let endDate = '-';

      if(this.reportTypeControl.value != null && this.reportTypeControl.value != undefined && this.reportTypeControl.value != ''){
        reportType = this.reportTypeControl.value;
      }

      if(this.startDate != null){
        let startYear = this.startDate.getFullYear();
        let startMonth = this.startDate.getMonth() + 1 < 10 ? `0${this.startDate.getMonth() + 1}` : `${this.startDate.getMonth() + 1}`;
        let startDay = this.startDate.getDate() < 10 ? `0${this.startDate.getDate()}` : `${this.startDate.getDate()}`;

        startDate = `${startYear}-${startMonth}-${startDay}`;
      }

      if(this.endDate != null){
        let endYear = this.endDate.getFullYear();
        let endMonth = this.endDate.getMonth() + 1 < 10 ? `0${this.endDate.getMonth() + 1}` : `${this.endDate.getMonth() + 1}`;
        let endDay = this.endDate.getDate() < 10 ? `0${this.endDate.getDate()}` : `${this.endDate.getDate()}`;

        endDate = `${endYear}-${endMonth}-${endDay}`;
      }

      let reports: ReportsListResponse = await lastValueFrom(this._correctiveMaintenanceService.getReports(reportType, startDate, endDate, idUser, 1));

      this.hasError = reports.error;
      this.errorStr = reports.msg;

      if(!this.hasError){
        let reportsArr: ReportsListItem[] = [];
        for(const report of reports.response){
          report.ID_INFORME = await this._encService.decrypt(report.ID_INFORME);
          report.DOCUMENTO = await this._encService.decrypt(report.DOCUMENTO);
          report.FECREG = this._functionsService.orderDate(report.FECREG);

          reportsArr.push(report);
        }

        this.dataSource = new MatTableDataSource(reportsArr);
        this.dataSource.paginator = this.paginator!;
        this.dataSource.sort = this.sort!;
      }

      this.isLoading = false;
    }catch(error: any){
      console.log(error);
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  async downloadReport(document: string){
    try{
      this._resourcesService.openSnackBar('Descargando informe...');

      let idUser = localStorage.getItem('idusuario')!;
      let documentEnc = await this._encService.encrypt(document);
      let downloadToken = await lastValueFrom(this._gdelService.getDownloadToken(documentEnc, idUser, 1));
      let download = this._document.getElementById(`download`) as HTMLAnchorElement;
  
      download.href = `http://git.ittec.mx/sam/public/api/download-file/${downloadToken.response.TOKEN}/${idUser}/1`;
      download.download = documentEnc;
      download.click();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }
}
