// Questo file fa parte di MyTown.
// MyTown è software libero: puoi ridistribuirlo e/o modificarlo secondo
// i termini della GNU Affero General Public License come pubblicata dalla
// Free Software Foundation, versione 3.
// Distribuito senza ALCUNA GARANZIA; vedi la GNU AGPL v3 per i dettagli.
// Copyright (C) Kondor Consulting & Services S.r.l.
// SPDX-License-Identifier: AGPL-3.0-or-later

import { Component, OnInit, ViewChild } from '@angular/core';
import { Location, DatePipe } from '@angular/common';
import { ModalController } from '@ionic/angular';
import { TranslateService } from '@ngx-translate/core';
import { Subscription } from 'rxjs';
import { InfiniteScrollCustomEvent, IonPopover } from '@ionic/angular';

import { ConfigService } from 'src/app/providers/config.service';
import { OrdersService } from 'src/app/providers/orders.service';
import { FatturaService } from 'src/app/providers/fattura.service';
import { StatoFatturaResp } from 'src/app/models/fattura.model';
import { ActivatedRoute, Router } from '@angular/router';

import { ModalOrderDetailComponent } from 'src/app/components/modal-order-detail/modal-order-detail.component';

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

  constructor(
    private activatedRoute: ActivatedRoute,
    private ordersService: OrdersService,
    private translate: TranslateService,
    private location: Location,
    private router: Router,
    private datePipe: DatePipe,
    private modalService: ModalController,
    private configService: ConfigService,
    private fatturaService: FatturaService,
  ){}

  // VARIABILI
  filtriModalOpen = false;
  ordinamentoModalOpen = false;
  onlineshopImageUrl = '';
  errorMessage = '';
  lstData: any[] = [];
  lstFilter: any[] = [];
  /** Stato fattura per ord_id (per il pulsante "Stampa fattura"). */
  invoiceStatus: Record<number, StatoFatturaResp> = {};
  filter:any;
  dataDA: string = '';
  dataA: string = '';
  cmp_id!: number;
  prt_id!: number;
  limitda: number = 1;
  totalrows: number = 0;
	pageelement: number = 20;
	pagenum: number = 1;
  filter_temp: any = {};
	cerca = '';
  lstStati: any[]= [];
  flagPermessiSezione = false;
  lstOrdinamento: any[] = [];
	order: string = '';
  idcliente = 0;
  anno = 0;
  mese = 0;
  responsiveOptions: any[] = [
    { breakpoint: '1024px', numVisible: 5 },
    { breakpoint: '768px', numVisible: 3 },
    { breakpoint: '560px', numVisible: 1 }
  ];
  state: any = { text: ' ------ ', value: '-1' };
  ordinamento: any = { text: ' ------ ', value: '' };
  lstOrd: any[]= [{ text: ' recenti_meno ', value: 'ord_date ASC' }, { text: ' recenti_piu ', value: 'ord_date DESC' }];
  @ViewChild('popover_ordinamento_product', { static: false }) popover_ordinamento_product!: IonPopover;
  @ViewChild('ord_user_date_da_popover', { static: false }) ord_user_date_da_popover!: IonPopover;
  @ViewChild('ord_user_date_a_popover', { static: false }) ord_user_date_a_popover!: IonPopover;
  resetButtons = [
    {
      text: 'No',
      handler: () => {
      }
    },
    {
      text: 'Sì',
      cssClass: 'alert-button-confirm',
      handler: () => {
        this.resetFilters();
        this.search();
        this.filtriModalOpen = false;
      }
    }
  ]

  // --------------------INIZIALIZZAZIONE PAGINA-----------------------------
  private paramsSubscription!: Subscription;
  ngOnInit(): void{
    this.onlineshopImageUrl = this.configService.onlineshopImageUrl;
    this.paramsSubscription = this.activatedRoute.params.subscribe((params) => {
			if (params['cmp_id']) this.cmp_id = +params['cmp_id'];
      if (params['prt_id']) this.prt_id = +params['prt_id'];
		});
    this.resetFilters();
    this.resetSearch();
    this.orderstate();
  }
   
  ionViewWillEnter() {
    fetch('./assets/config/sort_order.json').then(res => res.json()).then(json => {
      this.lstOrdinamento = json;
    });
  }

  // RESET FILTERS

  resetFilters(){
    this.filter = {};
    this.filter.cmp_id = this.cmp_id;
    this.filter.stato = -1;
    this.filter.pagina = this.limitda;
    this.filter.righePagina = this.pageelement;
    this.filter.orderBy = 'ord_date desc';
    this.filter.section = 'profile';
    this.filter.ord_date_da = '';
    this.filter.ord_date_a = '';
    this.filter.desc = '';
  }

  resetSearch() {
    this.state.value = -1;
    this.ordinamento.value = '';
		this.cerca = '';
    this.dataDA = '';
    this.dataA = '';
    this.order = '';
		this.search();
	}
   
  // LISTA ORDINI
  getOrdini() {
      this.ordersService.get_orders_list(this.filter).subscribe((res: any) => {
        if (res) {
          this.lstData = res;
          if (this.lstData.length > 0) {
            this.totalrows = this.lstData[0].ord_totalrows;
          } else {
            this.totalrows = 0;
          }
          this.loadInvoiceStatuses();
        }
      });
    }

  // ── Fattura ──────────────────────────────────────────────────────

  /** Carica lo stato fattura per ogni ordine visibile. */
  private loadInvoiceStatuses() {
    this.invoiceStatus = {};
    for (const ord of this.lstData) {
      const id = Number(ord?.ord_id);
      if (!(id > 0)) continue;
      this.fatturaService.getInvoiceStatus(this.cmp_id, 'ECOMMERCE', id).subscribe((st) => {
        this.invoiceStatus[id] = st;
      });
    }
  }

  fatturaStampabile(ord: any): boolean {
    const st = this.invoiceStatus[Number(ord?.ord_id)];
    // Fattura di cortesia stampabile appena esiste (anche DA_INVIARE), si genera dai dati DB.
    return !!st && st.esiste && !!st.fatId;
  }

  fatturaInEmissione(ord: any): boolean {
    const st = this.invoiceStatus[Number(ord?.ord_id)];
    return !!st && st.esiste && st.stato !== 'INVIATA';
  }

  printInvoice(ord: any) {
    const st = this.invoiceStatus[Number(ord?.ord_id)];
    if (!st?.fatId) return;
    this.fatturaService.printInvoice(st.fatId).subscribe({
      next: (blob) => this.fatturaService.openPdf(blob),
      error: () => this.configService.presentToastError('Errore nella stampa fattura'),
    });
  }

  // STATO DELL'ORDINE
  orderstate() {
    this.lstStati = [];
    let state: any = { text: ' ------ ', value: '-1' };
    this.lstStati.push(state);
    
    this.ordersService.orderstate('profile').subscribe((res: any[]) => {
      res.forEach((element: any) => {
        this.translate.get('onlineshop.orders.state.' + element).subscribe((res: any) => {
          let text = res;
          let item = { text: text, value: element };
          this.lstStati.push(item);
        });
      });
    });
  }

  // ORDINAMENTO

  viewOrdinamentoModal(e: Event) {
    this.popover_ordinamento_product.event = e;
    this.ordinamentoModalOpen = true;
  }
  setOrdinamento(ord: any) {
    this.filter.orderBy = ord.value;
    this.ordinamentoModalOpen = false;
    this.filter.pagina = 1;
    this.search();
  }

  // FILTERS
  openFiltri() {
    this.filtriModalOpen = true;

    this.filter_temp = {};
    this.filter_temp.ord_date_da = this.filter.ord_date_da;
    this.filter_temp.ord_date_a = this.filter.ord_date_a;
    this.filter_temp.stato = this.filter.stato;
  }
  searchFilter() {
    let f: any = {};
    f = this.renderFiltro('ord_date_da', this.filter_temp.ord_date_da);
    this.setFiltro(f);

    f = this.renderFiltro('ord_date_a', this.filter_temp.ord_date_a);
    this.setFiltro(f);

    f = this.renderFiltro('stato', this.filter_temp.stato);
    this.setFiltro(f);

    this.filtriModalOpen = false;
    this.lstData = [];
    this.filter.pagina = 1;
    this.search();
  }

  renderFiltro(value: string, id: any): any {
    let label = '';
    if (id !== '' && id !== '-1') {
      switch (value) {
        case 'ord_date_da':
          this.translate.get("table.orders.data_da").subscribe(r => {
            label = r + ' ' + this.datePipe.transform(new Date(id), "dd/MM/yyyy");
          });
          break;
        case 'ord_date_a':
          this.translate.get("table.orders.data_a").subscribe(r => {
            label = r + ' ' + this.datePipe.transform(new Date(id), "dd/MM/yyyy");
          });
          break;
        case 'stato':
          label = this.lstStati.find(x => x.value === id).text;
          break;
        default:
          break;
      }
    }

    let f: any = {};
    f.value = value;
    f.label = label;
    f.id = id;
    return f;
  }

  setFiltro(f: any) {
    if (f.id !== '' && f.id !== '-1') {
      let fTemp = this.lstFilter.find(el => el.value === f.value);
      if (fTemp) {
        fTemp.label = f.label;
      } else {
        fTemp = {};
        fTemp.value = f.value;
        fTemp.label = f.label;
        this.lstFilter.push(fTemp);
      }
    } else {
      this.lstFilter = this.lstFilter.filter(x => x.value !== f.value);
    }

    switch (f.value) {
      case 'ord_date_da':
        this.filter.ord_date_da = f.id;
        break;
      case 'ord_date_a':
        this.filter.ord_date_a = f.id;
        break;
      case 'stato':
        this.filter.stato = f.id;
        break;
    }
  }
  
  delFilter(f: any) {
    f.id = '-1';
    switch (f.value) {
      case 'ord_date_da':
      case 'ord_date_a':
        f.id = '';
        break;
      default:
        break;
    }

    this.setFiltro(f);

    this.lstData = [];
    this.filter.pagina = 1;
    this.search();
  }

  search(setTotal = true) {
    this.filter.pagina = this.limitda;
    this.getOrdini();
	}
  
  async setDataDa(e: any) {
    this.filter_temp.ord_date_da = this.datePipe.transform(new Date(e.detail.value), "yyyy-MM-dd")
    await this.ord_user_date_da_popover.dismiss();
  }

  async setDataA(e: any) {
    this.filter_temp.ord_date_a = this.datePipe.transform(new Date(e.detail.value), "yyyy-MM-dd")
    await this.ord_user_date_a_popover.dismiss();
  }


  // MODAL ORDINE DETTAGLIO
  async OrderDetail(ord_id: number, section: string){
      const modal =  await this.modalService.create({
        component:ModalOrderDetailComponent,
         componentProps: {
          id: ord_id,
          section: section,
          cmp_id: this.cmp_id,
         }
      });
      modal.onDidDismiss().then(() => {this.search();});

    return await modal.present();
  }

  // INDIRIZZAMENTI

  prd_detail(prd_id: number){
    this.router.navigate(['/portale', this.prt_id, 'company', this.cmp_id, 'service', 'onlineshop', 'product-detail', prd_id ]);
  }
  
  goBack(): void{
    this.location.back();
  }

  onIonInfinite(ev: any) {
    this.filter.pagina++;
    this.search(false);

    if (ev) {
      setTimeout(() => {
        (ev as InfiniteScrollCustomEvent).target.complete();
      }, 1000);
    }
  }
}
