import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {ComprobanteRetencionDto} from "../../model/ComprobanteRetencionDto";
import {Table} from "primeng/table";
import {CretencionService} from "../../services/cretencion.service";
import {FileService} from "../../../../../_service/utils/file.service";
import {AppService} from "../../../../../_service/app.service";
import {ConfirmationService} from "primeng/api";
import {severities} from "../../../../../_enums/constDomain";
import {ConsultasService} from "../../services/consultas.service";
import {ClienteDto} from "../../model/ClienteDto";
import {needsCleaning} from "@angular/compiler-cli/ngcc/src/packages/build_marker";
import {DetalleCretencionService} from "../../services/detalleCretencion.service";
import {DetalleCRetencionDto} from "../../model/DetalleCRetencionDto";

@Component({
  selector: 'app-cretencion-table',
  templateUrl: './cretencion-table.component.html',
  styleUrls: ['./cretencion-table.component.scss']
})
export class CretencionTableComponent implements OnInit {
    proceso: string = 'cretencion';

    @Input() listCretencion: ComprobanteRetencionDto[];

    @Input() loading : Boolean=false;

    cretencionSelect: ComprobanteRetencionDto;
    selectedCretencion: ComprobanteRetencionDto[];
    submitted: boolean;
    exportColumns:any[];
    mensajeEliminacion:string;
    visibleFormato: boolean;
    clienteDTO: ClienteDto;

    listDetalleCRetencion: DetalleCRetencionDto[];

    valorTotalDetalle: number;

    cols:any[];


    constructor(
        private  cretencionService: CretencionService,
        public fileService: FileService,

        public appservice: AppService,

        private consultaService: ConsultasService,

        private detalleCompService: DetalleCretencionService,
        private confirmationService: ConfirmationService,

    ) { }


    construirTabla() {
        this.cols = [
            {field: 'codigoCRetencion', header: 'COMPROBANTE RETENCIÓN'},
            {field: 'fechaComprobanteRetString', header: 'FECHA'},
            {field: 'totalRet', header: 'VALOR TOTAL RETENIDO'},
            {field: 'estadoSriRet', header: 'ESTADO SRI'},

        ];
        this.exportColumns = this.cols.map(col => ({title: col.header, dataKey: col.field}));
        //this.loading = false;
    }


    clear(table: Table) {
        table.clear();
    }


    loadData(event) {
        this.loading = true;
        setTimeout(() => {
            this.cretencionService.getAll().subscribe(res => {
                this.listCretencion = res.listado;
                this.loading = false;
            })
        }, 1000);
    }





    hideDialog() {
        this.submitted = false;
    }

    exportPdf() {
        this.appservice.exportPdf(this.exportColumns, this.listCretencion, 'Comprobante Retención', "p");
    }




    descargarArchivo(fileName: string) {
        try {
            this.fileService.getFileByName(fileName, this.proceso);
        } catch (error) {
            this.appservice.msgInfoDetail('error', 'Error', 'Error al descargar el archivo');
        }
    }


    exportExcel() {
        let indexLista: number = 0;
        this.listCretencion.forEach(element => {
            indexLista++;
            element.idComprobanteRetencion=indexLista;
            element.idUsuarioRet=null;
            element.fechaComprobanteRet=null;
        });
        this.appservice.exportExcel(this.listCretencion, 'Comprobante Retención');
    }



    presentarFormato(dto: ComprobanteRetencionDto){

        this.clienteDTO= new ClienteDto();
        this.visibleFormato= true;
        this.cretencionSelect= dto;

        this.cargarCliente();
        this.cargarDetalleComp();



    }



    async  cargarCliente(){
        await this.consultaService.getClienteByCedula(this.cretencionSelect.ncedCliente, this.cretencionSelect.tipoCliente).subscribe({
                next: data => {
                    this.clienteDTO = data.objeto;
                }
            }
        );
    }

    async  cargarDetalleComp(){
        this.valorTotalDetalle = 0;
        await this.detalleCompService.listaDetalleXidComp(this.cretencionSelect.idComprobanteRetencion).subscribe({
                next: data => {
                    this.listDetalleCRetencion = data.listado;
                },complete: () => {

                for (let dto of this.listDetalleCRetencion) {
                    this.valorTotalDetalle = this.valorTotalDetalle + dto.valorRetenido;
                }

                }

            }
        );
    }


  ngOnInit(): void {
        this.construirTabla();
        this.visibleFormato= false;
        this.cretencionSelect= new ComprobanteRetencionDto();
        this.clienteDTO= new ClienteDto();
  }



  async printComprobante(){


      const printContent = document.getElementById("printComp");
      const WindowPrt = window.open('', '', 'left=0,top=0');
      WindowPrt.document.write(printContent.innerHTML);
      WindowPrt.document.close();
      WindowPrt.focus();
      WindowPrt.print();
      WindowPrt.close();


  }


    async generarReporte(dto: ComprobanteRetencionDto){

        this.cretencionService.getReporte(dto.idComprobanteRetencion).subscribe((response) =>{

                const file = new Blob([response], { type: 'application/pdf' });
                const fileURL = URL.createObjectURL(file);
                window.open(fileURL);

            }
        )
    }

}
