import { Component, OnInit, Input, Output, EventEmitter, OnDestroy, SimpleChanges, OnChanges } from '@angular/core';
import { NotificationsService } from 'angular2-notifications';
import { forkJoin, Observable, of } from 'rxjs';
import { catchError, map, } from 'rxjs/operators';
import moment = require('moment');
import * as shared from '../../../../validators/shared.validator';
import { BlurAnimation } from '../../../../shared/animations/router.animation';
import { CollapseExpandAnimation } from '../../../../shared/animations/collapse.animation';
import { ComboData, GetComboOptionById } from '../../../../models/combo-data.model';
import { AuthenticationService } from '../../../../services/authentication.service';
import { DiarizationService } from '../../../../services/diarization.service';
import { EnvironmentService } from '../../../../services/environment.service';
import { EvaluationFormatService } from '../../../../services/evaluation-format.service';
import { EvaluationPlanService } from '../../../../services/evaluation-plan.service';
import { LanguageService } from '../../../../services/language.service';
import { LoadingService } from '../../../../services/loading.service';
import { ProcessService } from '../../../../services/process.service';
import { FilterInteraction, FilterInteractionConfig } from '../../../../models/filter-interaction.model';
import { ListGroupModalComponent } from '../../../../shared/list-group-modal/list-group-modal';
import { ModalGenericService } from 'services/modal-generic.service';
import { ModalGenericComponent } from '../../../../shared/modal/modal-generic.component';
import { ModalService } from '../../../../services/modal.service';
import { AdItem } from '../../../../models/ad-item.model';
import { ModalComponent } from '../../../../shared/modal/modal.component';
import { WorkGroupSupervisor } from '../../../../models/workgroupsupervisor.model';

@Component({
    moduleId: module.id,
    selector: 'limit-agent-interactions-cmp',
    templateUrl: 'limit-agent-interactions.html',
    styleUrls: [],
    animations: [
        CollapseExpandAnimation('sectionExpand', 500),
        BlurAnimation('routerTransition')
    ]
})

export class EvaluationPlanLimitAgentInteractionsComponent implements OnInit, OnChanges, OnDestroy {
    private translateCategory : string = 'limitInteractionsAgent';
    private limitType: ComboData = new ComboData('','');
    private typeLimitInteractionsByChannel: string ='S'
    private interactionsByAgentConfiguration: boolean = false;
    private limitTypeOptions: ComboData[] = [
        new ComboData('Agent', this.languageService.GetMessage(this.translateCategory, 'LIMIT_BY_AGENT')),
        new ComboData('WorkGroup', this.languageService.GetMessage(this.translateCategory, 'LIMIT_BY_WORKGROUP')),
    ];
    private limitInteractionsNumber: number = 0;
    private channels = [];
    private disabledLimit: boolean = true;
    private agentsLoading: boolean = true;
    private _externalFilterLoading: boolean = false;
    //private originalFilterAgents: ComboData[] = [];


    @Input()
    private filtersConfig: FilterInteractionConfig = new FilterInteractionConfig();
    @Input()
    private filters: FilterInteraction = new FilterInteraction();
    @Input()
    private workgroupsOptions: ComboData[] = [];
    @Input()
    private environmentType: string = '';

    @Input()
    set externalFiltersLoading(externalFilterLoading: boolean) {
        if (!externalFilterLoading) {
            this.filtersConfig.filterItems.sort((a, b) => {
                return a.order < b.order ? -1 : 1;
            });
        }
        this._externalFilterLoading = externalFilterLoading;
        this.disabledLimit = externalFilterLoading;
    }

    @Output() private channelChanged: EventEmitter<any[]> = new EventEmitter<any[]>();
    @Output() private limitConfigurationChanged: EventEmitter<any> = new EventEmitter<any>();
    @Output() private cleanSearchResults: EventEmitter<any> = new EventEmitter<any>();
    @Output() private selectedWorkGroups: EventEmitter<any> = new EventEmitter<any>();
    @Output() private initAgentsByLimitType: EventEmitter<any> = new EventEmitter<any>();
    @Output() private selectedAgents: EventEmitter<any> = new EventEmitter<any>();
    @Output() private typeLimitByChannelOption: EventEmitter<any[]> = new EventEmitter<any[]>();


    constructor(
        private authenticationService: AuthenticationService,
        private languageService: LanguageService,
        private loadingService: LoadingService,
        private notificationsService: NotificationsService,
        private environmentService: EnvironmentService,
        private evaluationFormatService: EvaluationFormatService,
        private evaluationPlanService: EvaluationPlanService,
        private processService: ProcessService,
        private diarizationService: DiarizationService,

        private modalService: ModalService,
        private modalGenericService: ModalGenericService,




    ) { }

    ngOnInit() : void {
        this.Initialize();
        
    }

    ngOnChanges(changes: SimpleChanges) : void {}

    ngOnDestroy() : void {
        this.loadingService.Close();
    }

    /**
     * 
     */

    // Método modificado para abrir el modal y pasarle los datos
    private openWorkGroupsModal(): void {
        let modalData: any = {
            workgroupsOptions: this.workgroupsOptions 
          };
        let modal: ModalGenericComponent = this.modalGenericService.GetModal();
        modal.headerTitle = "Listado de grupos"; // Puedes usar `this.languageService` para traducciones
        modal.hideCloseButton = false;
        modal.hideFooter = true;
        modal.modalClass = 'modal-lg modal-error'; 
        modal.cancelButtonLabel = this.languageService.GetMessage(this.translateCategory, 'CANCEL');
        modal.submitButtonLabel = this.languageService.GetMessage(this.translateCategory, 'DELETE');
        modal.adItem = new AdItem(
            ListGroupModalComponent,
            modalData
        );

        let subscriptionClose: any;

        // Si el formulario se cierra sin aceptar, cierra la subscripción.
        subscriptionClose = this.modalService.onClose.subscribe(() => {
            subscriptionClose.unsubscribe();
        });

        // Abre el formulario modal.
        modal.open();
    }


    private Initialize(): void {
        this.loadingService.Open();
        this.InitControlsToLimitInteractionsByAgent();
        //this.isLoading = true;
        this.selectedWorkGroups.emit(null);
        // Obtenemos los datos del vcc del localstorage
        let vcc : any = this.authenticationService.GetVCC();

        let promiseArray: Observable<any>[] = [];
        //promiseArray.push(this.GetEvaluationFormatOptions());

        // Ejecutamos todas las consultas para cargar combos
        forkJoin(promiseArray).subscribe({
            next: () => {
                // Setteamos idioma de transcripción
                this.loadingService.Close();
            },
            error: err => {
                //this.isLoading = false;
                this.loadingService.Close();

                this.notificationsService.error(
                    this.languageService.GetMessage(this.translateCategory, 'ERROR'),
                    this.languageService.GetMessage(this.translateCategory, err)
                );
            }
        });
    }

    OnChangeLimitType(limitType) {
        this.limitType = limitType;
        this.initAgentsByLimitType.emit(limitType.value);
        //Reiniciar valores de límites
        this.limitInteractionsNumber = 0;
        let filteredTypes: string[] = [];
        if (this.filters.interactionType && this.filters.interactionType.length !== 0){
            this.filters.interactionType.map(element => {
                if (element.status) {
                    filteredTypes.push(element.value);
                }
            });
            this.channels = filteredTypes.map(ft =>{
                return {name: ft, value: 0}
            })
            this.channelChanged.emit(this.channels)
        }
        
    }

    OnChangeTypeLimitInteractionsByChannel(typeLimitInteractionByChannel){
        this.typeLimitInteractionsByChannel = typeLimitInteractionByChannel;
        this.typeLimitByChannelOption.emit(typeLimitInteractionByChannel)
        let filteredTypes: string[] = [];
        this.limitInteractionsNumber = 0;
        if (this.filters.interactionType && this.filters.interactionType.length !== 0) {
            this.filters.interactionType.map(element => {
                if (element.status) {
                    filteredTypes.push(element.value);
                }
            });
            this.channels = filteredTypes.map(ft => {
                return { name: ft, value: 0 }
            })

            this.channelChanged.emit(this.channels)

        }


    }

    OnChangeLimitConfiguration(limitConfiguration){
        this.limitConfigurationChanged.emit(limitConfiguration)
       if(!limitConfiguration){
        this.InitControlsToLimitInteractionsByAgent()
       }   
       this.cleanSearchResults.emit(true) 
    }


    SetFilterInteractionType(e){
     let filteredTypes: string[] = [];
        if (this.filters.interactionType && this.filters.interactionType.length !== 0){
            this.filters.interactionType.map(element => {
            if (element.status) {
                    filteredTypes.push(element.value);
                }
            });
            this.channels = filteredTypes.map(ft =>{
                return {name: ft, value: 0}
            })

            this.channelChanged.emit(this.channels)

        }
    }

    SetFilterWorkGroup(filteredWorkGroups){
        let selectedWorkGroups = filteredWorkGroups.filter(wg => wg.status === true).map(fwg => fwg.value);
        this.selectedWorkGroups.emit(selectedWorkGroups);
    }

    SetFilterAgent(agent){
        let filteredAgents: string[] = [];
    if (this.filters.agent && this.filters.agent.length !== 0)
        filteredAgents = this.filters.agent.filter(a => a.status).length != this.filters.agent.length ?
            this.filters.agent.filter(a => a.status && a.value).map(a => a.value?.userId || a.value)
            :
            []
    this.selectedAgents.emit(filteredAgents)
        
    }

    UpdateChannelValue(){
        this.channelChanged.emit(this.channels)
    }

    UpdateChannelUniqueValue(limitInteractionsNumber){
        let filteredTypes: string[] = [];
        this.filters.interactionType.map(element => {
            if (element.status) {
                filteredTypes.push(element.value);
            }
        });
        this.channels = filteredTypes.map(ft =>{
            return {name: ft, value: 0}
        })

        this.channels = this.channels.map(cl =>{
            return {name: cl.name, value: limitInteractionsNumber}
        })
        this.channelChanged.emit(this.channels)
    }

    InitControlsToLimitInteractionsByAgent(){
        this.typeLimitInteractionsByChannel = 'S'
        this.limitType = new ComboData('','');
        this.limitInteractionsNumber = 0;
        let filteredTypes: string[] = [];
        this.filters.interactionType.map(element => {
            if (element.status) {
                filteredTypes.push(element.value);
            }
        });
        this.channels = filteredTypes.map(ft =>{
            return {name: ft, value: 0}
        })
        this.cleanSearchResults.emit(true)
    } 
}