import {
  Component,
  OnInit,
  OnDestroy,
  ViewChild,
  ChangeDetectorRef,
  AfterViewInit,
} from '@angular/core';
import { MaterialModule } from '../../material/material.module';
import { WorkflowFormComponent } from 'src/app/samwf/workflow-form/workflow-form.component';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { WorkflowInterface } from '../../interfaces/samwf/workflow-interface';
import { WorkflowService } from '../../services/samwf/workflow.service';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { ModulosInterface } from '../../interfaces/samwf/modulos-interface';
import { lastValueFrom, Observable } from 'rxjs';
import { ProgressBarMode } from '@angular/material/progress-bar';
import { RequestWorkflowFormComponent } from './request-workflow-form/request-workflow-form.component';
import { ResponseData } from 'src/app/interfaces/response-data';
import { MatSnackBar } from '@angular/material/snack-bar';

@Component({
  selector: 'app-workflow-request-workflow',
  templateUrl: './workflow-request-workflow.component.html',
  styleUrls: ['./workflow-request-workflow.component.css'],
})
export class WorkflowRequestWorkflowComponent implements OnInit {
  workflows: any[] = [];
  data_empty = false;
  data: any;
  statusData: any[] = [
    { state: 0, textState: 'Pendientes' },
    { state: 1, textState: 'Validadas' },
  ];
  requests: any[] = [];
  selectedOpcion = 0;
  filter_empty = false;
  displayedColumns: string[] = [
    'name',
    'modulo',
    'created_at',
    'updated_at',
    'accion',
  ];

  showProgressBar = false;

  mode: ProgressBarMode = 'buffer';
  dataSource: MatTableDataSource<any> = new MatTableDataSource<any>(
    this.workflows
  );
  dataSourceAux: MatTableDataSource<any> = new MatTableDataSource<any>(
    this.requests
  );
  minDate: Date;
  maxDate: Date;
  modules: any[] = [];
  filterCreatedDate: any;
  filterValidatedDate: any;
  filterModule: any;

  @ViewChild(MatPaginator) paginator: MatPaginator;

  constructor(
    public dialog: MatDialog,
    private router: Router,
    private translate: TranslateService,
    private _samwfService: WorkflowService,
    private changeDetectorRef: ChangeDetectorRef,
    private _snackBar: MatSnackBar
  ) {
    this.dataSource.data.length > 0
      ? (this.data_empty = false)
      : (this.data_empty = true);

    const currentYear = new Date().getFullYear();
    this.minDate = new Date(currentYear - 2, 0, 0);
    this.maxDate = new Date(currentYear + 1, 0, 0);
    translate.setDefaultLang('es');
  }

  ngOnInit(): void {
    /* this.value = (20 / 25) * 100; */
    this.getRequestUser();
    this.getRequestAux();
  }

  updatePaginator() {
    this.translate.get('paginador').subscribe((data: any) => {
      this.dataSource.paginator = this.paginator;
      this.paginator._intl.itemsPerPageLabel = data[0];
      this.paginator._intl.firstPageLabel = data[1];
      this.paginator._intl.lastPageLabel = data[2];
      this.paginator._intl.nextPageLabel = data[3];
      this.paginator._intl.previousPageLabel = data[4];
    });
  }

  ngAfterViewInit(): void {
    this.translate.get('paginador').subscribe((data: any) => {
      this.dataSource.paginator = this.paginator;
      this.paginator._intl.itemsPerPageLabel = data[0];
      this.paginator._intl.firstPageLabel = data[1];
      this.paginator._intl.lastPageLabel = data[2];
      this.paginator._intl.nextPageLabel = data[3];
      this.paginator._intl.previousPageLabel = data[4];
    });

    this.dataSource.filterPredicate = function (data, filter: string): boolean {
      return (
        data.name.toString().toLowerCase().includes(filter) ||
        data.description.toString().toLowerCase().includes(filter) ||
        data.created_at.toString().includes(filter)
      );
    };
  }

  filterData(state: any) {
    this.selectedOpcion = state;
    let arr: any[] = [];
    arr = this.workflows.filter((e: any) => {
      return e.isCompleted == state;
    });

    this.dataSource.data = arr;
    this.dataSource.data.length > 0
      ? (this.data_empty = false)
      : (this.data_empty = true);
  }

  applyFilter(filterValue: any) {
    this.dataSource.filter = filterValue.target.value.trim().toLowerCase();
  }

  openDialogConfirmAction(action: any, item: any) {
    let dataAction = {
      action: action,
      item: item,
    };

    const dialogRef = this.dialog.open(RequestWorkflowFormComponent, {
      data: dataAction,
    });

    dialogRef.afterClosed().subscribe((result) => {
      if (result) {
        if (result.reasons == '') {
          let objAux = { isValidated: result.isValidated };
          this.updateRequest(item.id, objAux);
        } else {
          this.updateRequest(item.id, result);
        }
      }
    });
  }

  clearFilter() {
    this.ngOnInit();
    this.data_empty = false;
    this.filter_empty = false;
  }

  filter() {
    let arrFilter: any[] = this.workflows;
    let dateAux: string = '';
    let arrAux: any[] = [];
    if (this.filterCreatedDate != undefined) {
      dateAux = this.formatDate(this.filterCreatedDate);
      for (let index = 0; index < arrFilter.length; index++) {
        if (arrFilter[index].created_at == dateAux) {
          arrAux.push(arrFilter[index]);
        }
      }
      this.filterValidate(arrAux);
    } else {
      this.filterValidate(arrFilter);
    }
  }

  filterValidate(arrFilter: any[]) {
    let dateAux: string = '';
    let arrAux: any[] = [];
    if (this.filterValidatedDate != undefined && arrFilter.length > 0) {
      dateAux = this.formatDate(this.filterCreatedDate);
      for (let index = 0; index < arrFilter.length; index++) {
        if (arrFilter[index].validated == dateAux) {
          arrAux.push(arrFilter[index]);
        }
      }
      this.filterModuleFunction(arrAux);
    } else {
      this.filterModuleFunction(arrFilter);
    }
  }

  filterModuleFunction(arrFilter: any[]) {
    let arrAux: any[] = [];
    if (this.filterModule != undefined && arrFilter.length > 0) {
      for (let index = 0; index < arrFilter.length; index++) {
        if (arrFilter[index].module == this.filterModule) {
          arrAux.push(arrFilter[index]);
        }
      }
      this.dataSource.data = arrAux;
      this.dataSource.data.length > 0
        ? (this.filter_empty = false)
        : (this.filter_empty = true);
    } else {
      this.dataSource.data = arrAux;
      this.dataSource.data.length > 0
        ? (this.filter_empty = false)
        : (this.filter_empty = true);
    }
  }

  public async updateRequest(request: any, idRequest: any) {
    await lastValueFrom(
      this._samwfService.updateRequests(request, idRequest)
    ).then(
      (data: ResponseData) => {
        this.showProgressBar = true;
        this._snackBar.open(data.msg, 'Cerrar', {
          duration: 3000,
        });

        this.showProgressBar = false;
      },
      (error) => {
        this._snackBar.open(error.message, 'Cerrar', { duration: 3000 });
      }
    );
    this.ngOnInit();
  }

  private async getRequestUser() {
    await lastValueFrom(this._samwfService.getRequestUser(1)).then(
      (data: any) => {
        this.workflows = data;

        this.dataSource.data = data.filter((e: any) => {
          e.created_at = e.created_at.slice(0, 10);
          e.updated_at = e.updated_at.slice(0, 10);

          return e.isCompleted == this.selectedOpcion;
        });
        this.dataSource.data.length > 0
          ? (this.data_empty = false)
          : (this.data_empty = true);
      },
      (error: any) => {
        console.log(error);
        this._snackBar.open(error.message, 'Cerrar', { duration: 3000 });
      }
    );

    await lastValueFrom(this._samwfService.getModules()).then(
      (data: any) => {
        this.modules = data;
      },
      (error: any) => {
        console.log(error);
        this._snackBar.open(error.message, 'Cerrar', { duration: 3000 });
      }
    );
  }

  private async getRequestAux() {
    await lastValueFrom(this._samwfService.getAllRequests()).then(
      (data: any) => {
        this.requests = data;
      },
      (error: any) => console.log(error)
    );

    await lastValueFrom(this._samwfService.getModules()).then(
      (data: any) => {
        this.modules = data;
      },
      (error: any) => {
        console.log(error);
        this._snackBar.open(error.message, 'Cerrar', { duration: 3000 });
      }
    );
  }

  private formatDate(date: Date) {
    var d = new Date(date),
      month = '' + (d.getMonth() + 1),
      day = '' + d.getDate(),
      year = d.getFullYear();

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    return [year, month, day].join('-');
  }
}
