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 } 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 { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
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: './create-or-edit-clinic.component.html',
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()],
})
export class CreateEditClinicComponent 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;

    clinic: CreateOrEditClinicDto = new CreateOrEditClinicDto();
    address: CreateAddressInput = new CreateAddressInput();
    
    constructor(
        injector: Injector,
        private _clinicsServiceProxy: ClinicsServiceProxy,
        private _addressService: AddressServiceProxy,
        private _emailService: EmailServiceProxy,
        private _postalCodeService: PostalCodeServiceProxy,
        private _addressTypeService: AddressTypeServiceProxy,
        private router: Router,
        private route: ActivatedRoute
    ) {
        super(injector);

    }

    filteredCountries: any;
    filteredCities: any;
    filteredStates: any;
    filteredPostal: any;
    filteredAddressType: any;
    selectedPostalCode: string;
    selectedAddressType: any;

    filterChange = false

    ngOnInit() {
        this.route.paramMap.subscribe(params => {
            this.id = params.get("id")
        })
        var that = this;
        $('.kt-select2').select2();
        let maxcount = 1000;
        this.filterAddressTypes(maxcount);
        this.filterPostal();

        $("#postalSelectInput").change(function () {
            that.selectedPostalCode = $("#postalSelectInput option:selected").text();
            that.selectedPostalCode = $.trim(that.selectedPostalCode)
            that.filterChange = true;
            that.filterCountries(that.selectedPostalCode);
            that.filterStates(that.selectedPostalCode);
            that.filterCities(that.selectedPostalCode)


                        
        })
        
        

        $(document).ready(() => {
                    //ktwizard('kt_wizard_v2', this.options);
                     //this.KTWizard2();
                     $("#visibleToDriver").text("No");
                     
                     $("#Clinic_ClinicNotesVisibleToDriver").click(function(){
                              //var check = $("input[type='checkbox']").is(":checked");
                              if ($('#Clinic_ClinicNotesVisibleToDriver').is(":checked"))
                              {
                              $("#visibleToDriver").text("Yes");
                              }
                              else {
                              $("#visibleToDriver").text("No");
                              }
                              
                             
                     }); 

                     $("#addressTypeSelectInput").change(function () {
                         this.selectedAddressType = $("#addressTypeSelectInput option:selected").text();
                         $("#selectedAddressType").text(this.selectedAddressType);
                     });

                     $("#countrySelectInput").change(function () {
                         this.selectedCountry = $("#countrySelectInput option:selected").text();
                         $("#selectedCountry").text(this.selectedCountry);
                     });

                     $("#postalSelectInput").change(function () {
                         this.selectedPostalCode = $("#postalSelectInput option:selected").text();
                         $("#selectedPostalCode").text(this.selectedPostalCode);

                     });

                     $("#stateSelectInput").change(function () {
                         this.selectedState = $("#stateSelectInput option:selected").text();
                         $("#selectedState").text(this.selectedState);

                     });
                     $("#citySelectInput").change(function () {
                         this.selectedCity = $("#citySelectInput option:selected").text();
                         $("#selectedCity").text(this.selectedCity);
                     });



                     var KTWizard2=function(){
                         var e,r,i;
                         return{init:function(){var t;KTUtil.get("kt_wizard_v2"),e=$("#kt_form"),
                         (i=new KTWizard("kt_wizard_v2",
                         {startStep:1,clickableSteps:!0})).on("beforeNext",function(e){!0!==r.form()&&e.stop()}),
                         i.on("beforePrev",function(e){!0!==r.form()&&e.stop()}),i.on("change",function(e){KTUtil.scrollTop()}),
                         r=e.validate({ignore:":hidden",
                         rules:{companyName:{required:!0},
                         accountNumber:{required:!0},
                         Address1:{required:!0},
                         postalSelectInput:{required:!0},
                         countrySelectInput:{required:!0},
                         stateSelectInput:{required:!0},
                         citySelectInput:{required:!0}},
                         invalidHandler:function(e,r){KTUtil.scrollTop(),swal.fire({title:"",text:"There are some errors in your submission. Please correct them.",
                         type:"error",confirmButtonClass:"btn btn-secondary"})},
                         submitHandler:function(e){}})}}}();
                         jQuery(document).ready(function(){KTWizard2.init()});
                     
                    
        });

         if (!this.id) {
             this.clinic = new CreateOrEditClinicDto();
             this.clinic.id = this.id;
             
             
         } else {
             this._clinicsServiceProxy.getClinicForEdit(this.id).subscribe(result => {
                 this.clinic = result.clinic;
                 
                 this.address = result.clinic.address;
                 this.selectedPostalCodeId = this.address.postalCodeId;
                 
                 

                        this._postalCodeService.getPostalCodeEdit(this.selectedPostalCodeId).subscribe(resultPostalCode => {
                                
                                this.selectedCountry = resultPostalCode.country;
                                this.selectedState = resultPostalCode.state;
                                this.selectedCity = resultPostalCode.city;
                                this.selectedPostalCode = resultPostalCode.value;
                                
                                this.filterCountries(this.selectedPostalCodeValue)
                                this.filterStates(this.selectedPostalCodeValue)
                                this.filterCities(this.selectedPostalCodeValue)
                           
                        });
                
             });
         }

    }

  

    ngOnChanges(){
        // this.filterPostal();
        if(this.selectedPostalCodeValue){
            this.filterCountries(this.selectedPostalCodeValue)
            this.filterStates(this.selectedPostalCodeValue)
            this.filterCities(this.selectedPostalCodeValue)

            
        }
    }

    save(): void {
            this.saving = true;

           

            
            this.address.postalCodeId = Number((<HTMLInputElement>document.getElementById('postalSelectInput')).value);

            if (Number((<HTMLInputElement>document.getElementById('addressTypeSelectInput')).value) == 0) {
                this.address.addressTypeId = null;

            }
            else {
                this.address.addressTypeId = Number((<HTMLInputElement>document.getElementById('addressTypeSelectInput')).value);

            }
            
            this.clinic.address = this.address;

            this._clinicsServiceProxy.createOrEdit(this.clinic)
                         .pipe(finalize(() => { this.saving = false;}))
                         .subscribe(() => {
                            this.notify.info(this.l('SavedSuccessfully'));
                            this.router.navigate(['/app/main/laboratory/clinics']);
            });

           
    }



    filterPostal(): void {
        this._postalCodeService.getDistinctPostalCode(
            undefined
        ).subscribe(result => {
            this.filteredPostal = result.items;
        });
    }

    filterCountries(postalCode): void {
        this._postalCodeService.getDistinctCountry(
            postalCode,
            undefined
        ).subscribe(result => {
            this.filteredCountries = result.items;
            $("#selectedCountry").text(this.filteredCountries[0]['country']);
        });
    }

    filterStates(postalCode): void {
        this._postalCodeService.getDistinctState(
            postalCode,
            undefined
        ).subscribe(result => {
            this.filteredStates = result.items;
            $("#selectedState").text(this.filteredStates[0]['state']);
        });
    }

    filterCities(postalCode): void {
        this._postalCodeService.getDistinctCity(
            postalCode,
            undefined
        ).subscribe(result => {
            this.filteredCities = result.items;
            $("#selectedCity").text(this.filteredCities[0]['city']);
        });
    }

    filterAddressTypes(maxcount): void {
        this._addressTypeService.getAddressType(
            undefined,
            undefined,
            undefined,
            maxcount,
            undefined
        ).subscribe(result => {
            this.filteredAddressType = result.items;
        });
    }

   
}   
