import { Component, Injector, ViewChild, ViewEncapsulation, Input, Output, EventEmitter, OnInit, AfterViewInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppConsts } from '@shared/AppConsts';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ClinicsServiceProxy, CreateOrEditClinicDto, RouteDefinitionsServiceProxy, CreateOrEditRouteDefinitionDto, RouteTypesServiceProxy, RouteScheduleDetailsServiceProxy, RouteScheduleDetailDto, CreateOrEditRouteScheduleDetailDto, CreateOrEditClinicScheduleDto } from '@shared/service-proxies/service-proxies';
import { AddressServiceProxy, CreateAddressInput } from '@shared/service-proxies/service-proxies';
import { EmailServiceProxy, CreateEmailInput, AddressTypeServiceProxy, PostalCodeServiceProxy, } from '@shared/service-proxies/service-proxies';
import { RouteSchedulesServiceProxy, CreateOrEditRouteScheduleDto } from '@shared/service-proxies/service-proxies';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import {FormGroup, FormControl} from '@angular/forms';
import { finalize } from 'rxjs/operators';
import * as moment from 'moment';
import * as _ from 'lodash';
declare var KTWizard: any;
declare var $: any;
declare var KTApp: any;
declare let swal: any;

@Component({
    templateUrl: './clinic-schedule.component.html',
    styleUrls: ['./clinic-schedule.component.less'],
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()],
})
export class ClinicScheduleComponent extends AppComponentBase {

        
    
    
    

    @Input('selectedCountry') selectedCountry: string;
    @Input('selectedCity') selectedCity: string;
    @Input('selectedState') selectedState: string;
    @Input('postalCodeId') selectedPostalCodeId: number; 
    @Input('postalCodeValue') selectedPostalCodeValue: string;


    
    
    active = false;
    saving = false;
    id: any;
    newSchedule = false;
    //routeScheduleDetail: CreateOrEditRouteScheduleDetailDto = new CreateOrEditRouteScheduleDetailDto();
    scheduleContainer: any[] = [];
    clinic: CreateOrEditClinicDto = new CreateOrEditClinicDto();
    address: CreateAddressInput = new CreateAddressInput();
    postalInfo: any;
    routeTypes: any;
    routeDefinitions: any;
    designation: any;
    schedules: any;
    scheduleInput: CreateOrEditClinicScheduleDto = new CreateOrEditClinicScheduleDto;
    newSched: any = {};
    routeSchedules: CreateOrEditRouteScheduleDto = new CreateOrEditRouteScheduleDto();
    updateRouteSchedules: CreateOrEditRouteScheduleDetailDto = new CreateOrEditRouteScheduleDetailDto();
    routeScheduleId: any;
    constructor(
        injector: Injector,
        private _clinicsServiceProxy: ClinicsServiceProxy,
        private _addressService: AddressServiceProxy,
        private _emailService: EmailServiceProxy,
        private _postalCodeService: PostalCodeServiceProxy,
        private _addressTypeService: AddressTypeServiceProxy,
        private _routeDefinitionsServiceProxy: RouteDefinitionsServiceProxy,
        private _routeScheduleDetailsServiceProxy: RouteScheduleDetailsServiceProxy,
        private _routeSchedulesServiceProxy: RouteSchedulesServiceProxy,
        private _router: Router,
        private route: ActivatedRoute
    ) {
        super(injector);


    }

    dynamicArray: Array<any> = [];
    newDynamicArray: Array<any> = [];
    newDynamic: any = {};
    date: Date;
    eta: Array<any> = [];
    cutOff: Array<any> = [];
    effectivityDate: Array<any> = [];
    oorRate: Array<any> = [];
    savedDesignation: Array<any> = [];
    i: any; 
    savedSchedules: any = [];
    newSavedSchedules: Array<any> = [];
    designationSelect: any;

    ngOnInit() {
        //this.paginator.changePage(0);
        //this.primengTableHelper.showLoadingIndicator();
        this.route.paramMap.subscribe(params => {
            this.id = params.get("id")
        })
        var that = this;
        //$('.kt-select2').select2();
        let maxcount = 1000;
        
        this.designationSelect = ([
        {
            value: "auto",
            text: "Auto"
        },
        {
            value: "willCall",
            text: "Will Call"
        }
        ]); 
            
        console.log(this.designationSelect);     
        

            

            this._routeDefinitionsServiceProxy.getAllRouteTypeForLookupTable(
                undefined,
                undefined,
                undefined,
                maxcount
            ).subscribe(result => {
                
                that.routeTypes = result.items;
                console.log(that.routeTypes);


            });

            this._routeDefinitionsServiceProxy.getAll(
                undefined,
                undefined,
                undefined,
                undefined,
                undefined,
                undefined,
                undefined,
                maxcount
            ).subscribe(result => {
                that.routeDefinitions = result.items;
                
            }); 
            this.showSchedule(); 




        
             

    }   

  
    showSchedule()  {
        this.active = true;
        this._clinicsServiceProxy.getClinicForEdit(this.id).subscribe(result => {
                    //console.log(result);
                    this.spinnerService.show();
                    this.clinic = result.clinic;
                    
                    this.address = result.clinic.address;


                                    this._postalCodeService.getPostalCodeEdit(this.address.postalCodeId).subscribe(resultPostalCode => {
                                            this.spinnerService.show();
                                            this.selectedCountry = resultPostalCode.country;
                                            this.selectedState = resultPostalCode.state;
                                            this.selectedCity = resultPostalCode.city;
                                            this.selectedPostalCodeValue = resultPostalCode.value;
                                             this.spinnerService.hide();
                                                                                                 
                                    });



                
                    
            
        });
        var that = this;


        this._clinicsServiceProxy.getClinicSchedule(this.id).subscribe(result => { 
            this.schedules = result.items;
            that.savedSchedules = result.items;
            //console.log(this.schedules);
            //this.schedules.estimatedTimeOfArrival = this.schedules.estimatedTimeOfArrival.toDate(); 
            if(result.items.length == 0) {
                
            
                
             
           
                 that._routeSchedulesServiceProxy.getAll(
                     that.clinic.id,
                     undefined,
                     undefined,
                     undefined,
                     undefined,
                     undefined
                 ).subscribe(resultSched => {
                    that.routeScheduleId = resultSched.items;
                    let routeScheduleDetail = new CreateOrEditRouteScheduleDetailDto({
                        routeCode: "",
                        routeTypeId: undefined,
                        estimatedTimeOfArrival: undefined,
                        cutOff: undefined,
                        effectivityDate: undefined,
                        designation: "auto",
                        oorRate: undefined,
                        routeScheduleId: undefined,
                        automatic: undefined,
                        willCall: undefined,
                        id: undefined
                    });   
                    if(resultSched.items.length == 0) {
                        that.newSchedule = true;
                        routeScheduleDetail.routeScheduleId = undefined;
                        
                        
                    }
                    else {
                       
                        that.newSchedule = false;
                        routeScheduleDetail.routeScheduleId = that.routeScheduleId[0]['routeSchedule']['id'];
                    }
                    
                 });
                 

                           
                            
                //routeScheduleDetail.routeScheduleId = undefined;
                //this.newDynamic = {routeCode: "", routeType: "",eta:"", cutOff:"", effectivityDate:"", designation:"auto",oor:"6.18",routeScheduleId:this.schedules[0]['routeScheduleId']};
                

                             
            }
            else {

                result.items.forEach(function (value) {
                  console.log(value);
                 
                  that.eta.push(value.estimatedTimeOfArrival.toDate());
                  that.cutOff.push(value.cutOff.toDate())
                  that.effectivityDate.push(value.effectivityDate.toDate());
                  that.oorRate.push(value.oorRate);

                  if(value.willCall) {
                    that.savedDesignation.push("willCall");
                  }
                  else if(value.automatic) {
                    that.savedDesignation.push("auto");
                  }


                    
                });    
            }
           
              
            
        });
    }
    
    save(): void {
            var that = this;
            //this.routeScheduleDetail = this.schedules;
            //this.routeScheduleDetail = JSON.parse(this.schedules);
            //this.routeScheduleDetail = myObject;
            
            that.eta.forEach(function (value, i) {
                that.savedSchedules[i].estimatedTimeOfArrival = value;
            });
            that.cutOff.forEach(function (value, i) {
                that.savedSchedules[i].cutOff = value;
            });
            that.effectivityDate.forEach(function (value, i) {
                that.savedSchedules[i].effectivityDate = value;

            });
            that.oorRate.forEach(function (value, i) {
                that.savedSchedules[i].oorRate = value;
            });
            that.savedDesignation.forEach(function (value, i) {
                that.savedSchedules[i].designation = value;
            });
            
            that.savedSchedules.forEach(function(value, i) {
                let update = new CreateOrEditRouteScheduleDetailDto({
                   routeCode: value.routeCode,
                   routeTypeId: value.routeTypeId,
                   estimatedTimeOfArrival: value.estimatedTimeOfArrival,
                   cutOff: value.cutOff,
                   effectivityDate: value.effectivityDate,
                   designation: value.designation,
                   oorRate: value.oorRate,
                   automatic: value.automatic,
                   willCall: value.willCall,
                   routeScheduleId: value.routeScheduleId,
                   id: value.id
                });
                that.newSavedSchedules.push(update);
            });
            
            that.eta = [];
            that.cutOff = [];
            that.effectivityDate = [];
            that.oorRate = [];
            that.savedDesignation = [];


           
           that.routeSchedules.clinicId = that.clinic.id;
           
           //that.dynamicArray.push(that.updateRouteSchedules);

           that.scheduleInput = new CreateOrEditClinicScheduleDto({
               scheduleInput: 
                   that.dynamicArray,
                newSchedule: that.newSchedule,
                routeScheduleInput: that.routeSchedules,
                updateScheduleInput: that.newSavedSchedules,
                updateClinicInput: that.clinic                             
                                        
               
           });
           console.log(that.newSavedSchedules);
           //console.log(that.savedSchedules);
           that.dynamicArray = [];
           that.newSavedSchedules = []; 
           that._routeScheduleDetailsServiceProxy.createOrEditClinicSchedule(that.scheduleInput)
                                                                                                          .pipe(finalize(() => { this.saving = false;}))
                                                                                                          .subscribe(() => {
                                                                                                            this.saving = true;
                                                                                                            this.reloadPage();
                                                                                                           this.notify.info(this.l('SavedSuccessfully'));
                                                                                                             
            });
                                                                        
                        
          
    }

    addRow(index) { 

         console.log(this.routeScheduleId); 
         //let routeScheduleDetail = new CreateOrEditRouteScheduleDetailDto();
         //this.newDynamic = {routeCode:"",routeType:"",eta:"",cutOff:"",effectivityDate:"",designation:"auto",oor:"6.18",routeScheduleId:this.schedules[0]['routeScheduleId']};
         let routeScheduleDetail = new CreateOrEditRouteScheduleDetailDto({
            routeCode: "",
            routeTypeId: undefined,
            estimatedTimeOfArrival: undefined,
            cutOff: undefined,
            effectivityDate: undefined,
            designation: "auto",
            oorRate: undefined,
            automatic: undefined,
            willCall: undefined,
            routeScheduleId: undefined,
            id: undefined
         });


         this._routeSchedulesServiceProxy.getAll(
             this.clinic.id,
             undefined,
             undefined,
             undefined,
             undefined,
             undefined
         ).subscribe(resultSched => {
            this.routeScheduleId = resultSched.items;
                
            if(resultSched.items.length == 0) {
                this.newSchedule = true;
                routeScheduleDetail.routeScheduleId = undefined;
                
            }
            else {
               
                this.newSchedule = false;
                routeScheduleDetail.routeScheduleId = this.routeScheduleId[0]['routeSchedule']['id'];
            }
            
         });
         
         
         
         this.newDynamic = routeScheduleDetail;
         this.dynamicArray.push(this.newDynamic);
         //this.newDynamicArray = this.dynamicArray;
           
         //console.log(routeScheduleDetail.routeScheduleId);
         return true;
     }
     
     deleteRow(index) {
         
             this.dynamicArray.splice(index, 1);
             return true;
         
     }

     createOrEditClinic(url: any, id?: number){
         

         this.message.confirm(
             '',
             (isConfirmed) => {
                 if (isConfirmed) {

                    if(id != null){
                        var myurl = `${url}/${id}`;
                    }else{
                        var myurl = `${url}`;
                    }
                    console.log(myurl);

                    this._router.navigateByUrl(myurl);

                     
                 }
             }
         );
     }

     deleteRouteScheduleDetail(routeScheduleDetail: RouteScheduleDetailDto): void {
         this.message.confirm(
             '',
             (isConfirmed) => {
                 if (isConfirmed) {
                     this._routeScheduleDetailsServiceProxy.delete(routeScheduleDetail.id)
                         .subscribe(() => {
                             this.reloadPage();
                            
                             this.notify.success(this.l('SuccessfullyDeleted'));
                         });
                 }
             }
         );
     }

     reloadPage(): void {

          this.showSchedule(); 
     }

    handleChange(input) {
        if (input.value < 0) input.value = 0;
        if (input.value > 100) input.value = 2;
    }
    
}   
