import { HttpClientDataService } from './../../service/http-client-data.service';
import { StruttureResponse } from './../../interface/strutture-response';
import { Struttura } from './../../interface/struttura';
import { FattureResponse } from './../../interface/fatture-response';
import { FattureRequest } from './../../interface/fatture-request';
import { Fattura } from './../../interface/fattura';
import { Component, OnInit } from '@angular/core';
import { UtilService } from './../../service/util.service';
import { AuthService } from 'src/app/auth/service/auth.service';
import { SegreteriaService } from './../../service/segreteria.service';
import { ErrorResponse } from '../../auth/interface/error-response';
import { Platform, Events } from '@ionic/angular';
import { DatePicker } from '@ionic-native/date-picker/ngx';

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

  constructor(
    private authService: AuthService, 
    private  utilService: UtilService, 
    private segreteriaService: SegreteriaService,
    public platform: Platform,
    private datePicker: DatePicker,
    public httpClientDataService: HttpClientDataService,
    public events: Events
  ) 
  { 
    this.events.publish('functionCall:startup', null);
    this.initPage();
    if(AuthService.clienteSelezionato.id != null)
    { 
      this.loadStrutture();
      this.loadFatture('initial');
    }
    this.events.subscribe('functionCall:clienteCambiato', eventData => {
      this.loadStrutture();
      this.loadFatture('initial');
    });
  }

  segreteria: string;
  fatture: Fattura[];
  idCliente;
  strutturaSel: Struttura;
  idStrutturaSel;
  strutture: Struttura[];
  date1;
  date2;


  initPage()
  {
    this.fatture = [];
    var date : Date;
    date = new Date();
    this.date1 = this.utilService.getDateString(date);
    this.date2 = this.utilService.getDateString(date);
    this.segreteria = "fatture";
    this.strutturaSel = null;
    this.idStrutturaSel = null;
    this.strutture = [];
  }

  changeSel(sel)
  {
    this.segreteria = sel;
  }

  setDateDa()
  {
    this.datePicker.show({
      date: new Date(),
      mode: 'date',
      androidTheme: this.datePicker.ANDROID_THEMES.THEME_HOLO_DARK
    }).then(
      date => this.date1 = this.utilService.getDateString(date),
      err => console.log('Error occurred while getting date: ', err)
    );
  }

  setDateA()
  {
    this.datePicker.show({
      date: new Date(),
      mode: 'date',
      androidTheme: this.datePicker.ANDROID_THEMES.THEME_HOLO_DARK
    }).then(
      date => this.date2 = this.utilService.getDateString(date),
      err => console.log('Error occurred while getting date: ', err)
    );
  }

  getNotula(idNotula, nomeFile, isProgNotula)
  {
    var tipo = "";
    if(isProgNotula) tipo = "P";
    else tipo = "N";
    var fileUrl = this.httpClientDataService.BASE_ADDRESS+"/intranet/notula.do?idcliente="+AuthService.clienteSelezionato.id+"&idnotula="+idNotula+"&tipo="+tipo;
    this.utilService.downloadDocumento(fileUrl, nomeFile);
  }

  getEstrattoConto(idCliente, nomeFile, idStruttura)
  {
    var fileUrl = this.httpClientDataService.BASE_ADDRESS+"/intranet/estrattoconto.do?idcliente="+idCliente+"&idstruttura="+idStruttura;
    this.utilService.downloadDocumento(fileUrl, nomeFile);
  }

  async redirectTo2p2()
  {
    var id = await this.authService.getId();
    this.segreteriaService.getP2pToken(id).subscribe((res)=>{
      var token = res.token;
      window.open(this.httpClientDataService.P2PSingleSignOnUrl+token, "_system");
    },
    (error: ErrorResponse) => {
      this.utilService.presentAlert("Errore", "", error.errorMsg, ["OK"]);
    });
  }

  cambiaStruttura()
  {
    var i;
    for(i = 0;i < this.strutture.length;i++)
    {
      if(this.idStrutturaSel == this.strutture[i].id) 
        this.strutturaSel = this.strutture[i];
    }
  }

  loadStrutture()
  {
    //this.utilService.showLoading();
    this.segreteriaService.getStrutture(AuthService.clienteSelezionato.id).subscribe((res: StruttureResponse)=>{
      //this.utilService.closeLoading();
      this.strutture = res.strutture;
      if(this.strutture.length > 0) this.strutturaSel = this.strutture[0];
    },
    (error: ErrorResponse) => {
      //this.utilService.closeLoading();
      this.utilService.presentAlert("Errore", "", error.errorMsg, ["OK"]);
    });
  }

  downloadEstrattoConto()
  {}

  cercaFatture()
  {
    this.loadFatture("ricerca");
  }

  loadFatture(fase)
  {
    this.utilService.showLoading();
    var request: FattureRequest;
    this.idCliente = AuthService.clienteSelezionato.id;
    if(fase == "initial") request = this.segreteriaService.createFatturaRequest(this.idCliente, 10, null, null); 
    else request = this.segreteriaService.createFatturaRequest(this.idCliente,null, this.utilService.dateFormatConvert(this.date1), this.utilService.dateFormatConvert(this.date2));
    this.segreteriaService.getFatture(request).subscribe((res: FattureResponse)=>{
      this.utilService.closeLoading();
      if(res.error){
        this.utilService.presentAlert("Errore", "", res.error, ["OK"]);
      }
      else 
      {
        this.fatture = res.notule;
      }
    },
    (error: ErrorResponse) => {
      this.utilService.closeLoading();
      this.utilService.presentAlert("Errore", "", error.errorMsg, ["OK"]);
    });
  }

  ngOnInit() {
  }

  trackByDoc(index: number, seg: Fattura): number { return seg.id; }

}
