import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import swal from 'sweetalert2';
import { Subscriber, Subscription, Observable } from 'rxjs';
import { ApiService } from 'app/api.service';

@Component({
  selector: 'app-reports',
  templateUrl: './reports.component.html',
  styleUrls: ['./reports.component.scss']
})
export class ReportsComponent implements OnInit {

  public export: Subscription = null;
  public filterKardex:any = {from: new Date(), to: new Date() };
  public filterAccounts:any = {from: new Date(), to: new Date() };
  constructor(private title: Title, public apiService: ApiService) {
    this.title.setTitle("Reportes");
    this.filterKardex.from.setDate(this.filterKardex.from.getDate() - 30);
    this.filterAccounts.from.setDate(this.filterAccounts.from.getDate() - 30);
  }

  ngOnInit() {
  }
  enDate(fecha:Date) {
    let d = new Date(fecha),
        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('-');
  }
  kardex() {
    this.export = this.apiService.excelKardex(this.enDate(this.filterKardex.from), this.enDate(this.filterKardex.to)).subscribe((data:any)=> {
      console.log('export complete', data);
      swal.close();
      if (data.res == "OK") {
        this.apiService.showOk("Listo","Se ha iniciado la descarga!");
      }
      else {
        this.apiService.showError("Error",data.msg);
      }
    });
    let sw = swal({
      title: 'Generando reporte',
      html: 'No cierres este cuadro hasta que descarguemos tu informe',
      onBeforeOpen: () => {
        swal.showLoading()
      },
      onClose: () => {
        this.export.unsubscribe();
      }
    }).then((result) => {
      console.log('swal_close', result);
    });
  }
  accounts() {
    this.export = this.apiService.excelAccounts(this.enDate(this.filterAccounts.from), this.enDate(this.filterAccounts.to)).subscribe((data:any)=> {
      console.log('export complete', data);
      swal.close();
      if (data.res == "OK") {
        this.apiService.showOk("Listo","Se ha iniciado la descarga!");
      }
      else {
        this.apiService.showError("Error",data.msg);
      }
    });
    let sw = swal({
      title: 'Generando reporte',
      html: 'No cierres este cuadro hasta que descarguemos tu informe',
      onBeforeOpen: () => {
        swal.showLoading()
      },
      onClose: () => {
        this.export.unsubscribe();
      }
    }).then((result) => {
      console.log('swal_close', result);
    });
  }

}
