import { Component, Injector, ViewChild, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';

import { OrderServiceProxy, OrderListDto, LocationServiceProxy, LocationListDto, UpdateOrderV2Input, DestinationDetailListDto, ContactListDto, AddressListDto, TagTypeListDto, TagListDto, EmailListDto, PhoneListDto, PostalCodeInAddressListDto, NoteListDto, OrderPackageListDto, ShippingPackageListDto, TagTypeServiceProxy, PostalCodeServiceProxy, ShippingPackageServiceProxy, OrderPackageServiceProxy } from '@shared/service-proxies/service-proxies';

import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { finalize } from 'rxjs/operators';
import * as moment from 'moment';
import { CreateOrderModalComponent } from './create-order-modal.component';
import { PrimengTableHelper } from '@shared/helpers/PrimengTableHelper';
import * as _ from 'lodash';
declare var KTWizard: any;
declare var $: any;
declare var KTBootstrapDaterangepicker: any;

@Component({
    templateUrl: './update-order.component.html',
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()]
})
export class UpdateOrderComponent extends AppComponentBase {

    // @ViewChild('dataTable', {static: true}) dataTable: Table;
    // @ViewChild('paginator', {static: true}) paginator: Paginator;
    // @ViewChild('createOrderModal') createOrderModal: CreateOrderModalComponent;

    active = false;
    saving = false;
    forUpdateInput: UpdateOrderV2Input = new UpdateOrderV2Input();
    orderInput: OrderListDto = new OrderListDto(); 
    
    // createInput: CreateOrderV2Input = new CreateOrderV2Input();  

    pickupDetailInput: DestinationDetailListDto = new DestinationDetailListDto(); 
    pickupContactInput: ContactListDto = new ContactListDto();
    pickupContactAddress: AddressListDto = new AddressListDto;
    
    destinationDetailInput: DestinationDetailListDto = new DestinationDetailListDto; 
    destinationContactInput: ContactListDto = new ContactListDto;
    destinationContactAddress: AddressListDto = new AddressListDto;

    locationFilter: LocationListDto = new LocationListDto();
    filteredLocation: any;

    tagTypeFilter: TagTypeListDto = new TagTypeListDto();
    filteredTagType: any;

    tag: TagListDto = new TagListDto();

    pickupEmail: EmailListDto = new EmailListDto()
    pickupPhone: PhoneListDto = new PhoneListDto()

    deliveryEmail: EmailListDto = new EmailListDto()
    deliveryPhone: EmailListDto = new EmailListDto()

    pickupEta: Date;
    deliveryEta: Date;
    pickUpTo: Date;
    pickUpFrom: Date;
    deliveryFrom: Date;
    deliveryTo: Date;
    pickuppostalId: PostalCodeInAddressListDto = new PostalCodeInAddressListDto();

    destinationpostalId: PostalCodeInAddressListDto = new PostalCodeInAddressListDto();
    
    noteInput: NoteListDto = new NoteListDto();
    orderPackages: Array<OrderPackageListDto> = [];
    packages: any = []; 
    packageFilter: ShippingPackageListDto = new ShippingPackageListDto();
    filteredPackage: any;
    filteredCountries: any;
    filteredCities: any;
    filteredStates: any;
    filteredPostal: any;

    orderPackageInput: Object = new Object();
    addPackage: any;
    packageQuantity: number;
    packageNameMessageError: boolean;
    packageQtyMessageError: boolean;

    locationInput: any;
    id: any;
    toAdd: OrderPackageListDto;
    toAddP: ShippingPackageListDto;

    selectedLocation: any;
    selectedTagType: any;
    selectedPickupCountry: any;
    selectedPickupPostalCode: any;
    selectedPickupState: any;
    selectedPickupCity: any;
    selectedDestinationCountry: any;
    selectedDestinationPostalCode: any;
    selectedDestinationState: any;
    selectedDestinationCity: any;

    constructor(
        injector: Injector,
        private _orderAppService: OrderServiceProxy,
        private _locationAppService: LocationServiceProxy,
        private _tagTypeAppService: TagTypeServiceProxy,
        private _postalCodeService: PostalCodeServiceProxy,

        // private _cityService: CityServiceProxy,
        // private _countryService: CountryServiceProxy,
        // private _stateService: StateServiceProxy,

        private _packageService: ShippingPackageServiceProxy,
        private _orderPackageService: OrderPackageServiceProxy,
        private route: ActivatedRoute,
        private router: Router
    ) {
        super(injector);
        
    }

    ngOnInit(){
        this.ktwizard2();
        this.route.paramMap.subscribe(params => {
            this.id = params.get("id")
        })
        
        this.packages = new ShippingPackageListDto();
        this.packageQuantity = undefined;
        this._orderAppService.getOrderForUpdate(this.id)
        .pipe()
        .subscribe(result => {
            this.orderInput = result;
            this.pickupDetailInput = result.pickupDetail;
            this.pickupContactInput = result.pickupDetail.contact;
            this.pickupContactAddress = result.pickupDetail.contact.address;
            
            this.destinationDetailInput = result.deliveryDetail; 
            this.destinationContactInput = result.deliveryDetail.contact; 
            this.destinationContactAddress = result.deliveryDetail.contact.address;




            this.locationFilter = result.location; 

            // $('#location').val = this.locationFilter.id;


            // this.tag = result.orderTags.tag; 

            // this.tagTypeFilter = result.orderTags.tag.tagType; 


            this.pickupEmail = result.pickupDetail.contact.emails;
            this.pickupPhone = result.pickupDetail.contact.phones;

            this.deliveryEmail = result.deliveryDetail.contact.emails;
            this.deliveryPhone = result.deliveryDetail.contact.phones;

            this.pickupEta = moment.utc(result.pickupDetail.etaEnd).toDate();
            this.pickUpTo = moment.utc(result.pickupDetail.etaEnd).toDate();
            this.pickUpFrom = moment.utc(result.pickupDetail.etaStart).toDate();

            this.deliveryEta = moment.utc(result.deliveryDetail.etaEnd).toDate();
            this.deliveryTo = moment.utc(result.deliveryDetail.etaEnd).toDate();
            this.deliveryFrom = moment.utc(result.deliveryDetail.etaStart).toDate();

            this.pickuppostalId = result.pickupDetail.contact.address.postalCode;
            
            this.destinationpostalId = result.deliveryDetail.contact.address.postalCode;

            this.selectedLocation =  result.location.name;

            // this.selectedTagType = result.orderTags.tag.name;

            
            this.selectedPickupPostalCode = result.pickupDetail.contact.address.postalCode.value;
            
            this.selectedDestinationPostalCode = result.deliveryDetail.contact.address.postalCode.value;

            this.noteInput = result.note;

            this.orderPackages = result.orderPackages;

            
            $('.kt-select2').select2({ 
                placeholder: "Select.."
            });
            this.filterLocation();
            this.filterTagType();

            // this.filterPostal();
            // this.filterCountries();
            // this.filterCities();
            // this.filterStates();

            this.filterPackage();

            console.log(this.orderPackages);


        });

    $("#location").change(function(){
            this.selectedLocation = $("#location option:selected").text();
            $("#selectedLocation").text("select");
            
    });

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

            
    });

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

            
    });

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

            
    });

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

            
    });

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

            
    });



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

            
    });

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

            
    });

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

            
    });

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

            
    });
    }

    ngAfterViewInit(){
    }

    save(): void {
        this.saving = true;
            this.forUpdateInput.id = this.orderInput.id;
            this.forUpdateInput.userId = this.orderInput.user.id;
            this.forUpdateInput.location = this.locationFilter;
            this.forUpdateInput.location.id =  Number((<HTMLInputElement>document.getElementById('location')).value);
            this.forUpdateInput.pickupDetails = this.pickupDetailInput;
            this.forUpdateInput.pickupDetails.contact.address = this.pickupContactAddress;
            
            
            this.forUpdateInput.pickupDetails.contact.address.postalCode.id = Number((<HTMLInputElement>document.getElementById('pickupPostalInput')).value);
            // this.forUpdateInput.pickupDetails.contact.address.city.id = this.pickupcityId.id;
            // this.forUpdateInput.pickupDetails.contact.address.country.id = this.pickupcountryId.id;
            // this.forUpdateInput.pickupDetails.contact.address.state.id = this.pickupstateId.id;
            // this.forUpdateInput.pickupDetails.contact.address.postalCode.id = this.pickuppostalId.id;
            this.forUpdateInput.pickupDetails.contact.emails = this.pickupEmail;
            this.forUpdateInput.pickupDetails.contact.phones = this.pickupPhone;
    
            this.forUpdateInput.pickupDetails.etaStart = moment.utc(moment(this.pickupEta).format('YYYY-MM-DD') + ' ' + moment(this.pickUpFrom).format('HH:mm:ss'));
            this.forUpdateInput.pickupDetails.etaEnd = moment.utc(moment(this.pickupEta).format('YYYY-MM-DD') + ' ' + moment(this.pickUpTo).format('HH:mm:ss'));
    
            this.forUpdateInput.deliveryDetails = this.destinationDetailInput;
            this.forUpdateInput.deliveryDetails.contact.address = this.destinationContactAddress;
            this.forUpdateInput.deliveryDetails.contact.address.postalCode.id = Number((<HTMLInputElement>document.getElementById('destinationPostalInput')).value);
            // this.forUpdateInput.deliveryDetails.contact.address.city.id = this.destinationcityId.id;
            // this.forUpdateInput.deliveryDetails.contact.address.country.id = this.destinationcountryId.id;
            // this.forUpdateInput.deliveryDetails.contact.address.state.id = this.destinationstateId.id;
            // this.forUpdateInput.deliveryDetails.contact.address.postalCode.id = this.destinationpostalId.id;
            this.forUpdateInput.deliveryDetails.contact.emails = this.deliveryEmail;
            this.forUpdateInput.deliveryDetails.contact.phones = this.deliveryPhone;
    
            this.forUpdateInput.deliveryDetails.etaStart = moment.utc(moment(this.deliveryEta).format('YYYY-MM-DD') + ' ' + moment(this.deliveryFrom).format('HH:mm:ss'));
            this.forUpdateInput.deliveryDetails.etaEnd = moment.utc(moment(this.deliveryEta).format('YYYY-MM-DD') + ' ' + moment(this.deliveryTo).format('HH:mm:ss'));
    
            this.forUpdateInput.note = this.noteInput;
    
            this.forUpdateInput.tag = this.tag;
            this.forUpdateInput.tag.tagType.id = Number((<HTMLInputElement>document.getElementById('TagType')).value);
            this.forUpdateInput.orderPackages = this.orderPackages;
            this._orderAppService.updateOrderV2(this.forUpdateInput)
            .pipe(finalize(() => { this.saving = false; }))
            .subscribe(() => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.saving = false;
                this.router.navigateByUrl("/app/sprintship/order");
            });
    }

    filterLocation(): void {
        this._locationAppService.getLocation(
            undefined,
            undefined,
            undefined,
            undefined,
            undefined
        ).subscribe(result => {
            this.filteredLocation = result.items;
        });
      }

    filterTagType(): void {
        this._tagTypeAppService.getTagType(
            undefined,
            undefined,
            undefined,
            undefined,
            undefined
        ).subscribe(result => {
            this.filteredTagType = result.items;
        });
      }



    // filterPostal(): void {
    //     this._postalCodeService.getPostalCode(
    //         undefined,
    //         undefined,
    //         undefined,
    //         undefined,
    //         undefined
    //     ).subscribe(result => {
    //         this.filteredPostal = result.items;
    //     });
    // }
  
    // filterCountries(): void {
    //     this._countryService.getCountry(
    //         undefined,
    //         undefined,
    //         undefined,
    //         undefined,
    //         undefined
    //     ).subscribe(result => {
    //         this.filteredCountries = result.items;
    //     });
    // }
  
    // filterCities(): void {
    //     this._cityService.getCity(
    //         undefined,
    //         undefined,
    //         undefined,
    //         undefined,
    //         undefined
    //     ).subscribe(result => {
    //         this.filteredCities = result.items;
    //     });
    // }

    // filterStates(): void {
    //     this._stateService.getState(
    //         undefined,
    //         undefined,
    //         undefined,
    //         undefined,
    //         undefined
    //     ).subscribe(result => {
    //         this.filteredStates = result.items;
    //     });
    // }



    filterPackage(): void {
        this._packageService.getShippingPackage(
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined
        ).subscribe(result => {
            this.filteredPackage = result.items;
        });
    }


    async addPackages(): Promise<void> {
        var packages_id = Number((<HTMLInputElement>document.getElementById('packages')).value);
        if ((packages_id === 0 || packages_id == null) && (this.packageQuantity === 0 || this.packageQuantity == null)) {
            this.packageNameMessageError = true;
            this.packageQtyMessageError = true;
        } else if ((packages_id === 0 || packages_id == null)) {
            this.packageNameMessageError = true;
            this.packageQtyMessageError = false;
        } else if ((this.packageQuantity === 0 || this.packageQuantity == null)) {
            this.packageNameMessageError = false;
            this.packageQtyMessageError = true;
        } else {

        this.toAdd = new OrderPackageListDto();
        this.toAddP = new ShippingPackageListDto();

        this.packages = new ShippingPackageListDto();
        // this.packageQuantity = undefined;
        
        this.toAdd.packageId = Number((<HTMLInputElement>document.getElementById('packages')).value);
        this.toAdd.quantity = this.packageQuantity;
        this.getpackageName(this.toAdd.packageId);
        // this.toAddP.name =  String(await this.getpackageName(this.toAdd.packageId));
    
        // this.toAdd.packageId = this.packages.id;
        // this.toAddP.name = this.packages.name;
        // this.toAdd.quantity = this.packageQuantity;
        this.toAdd.package = this.toAddP;
        console.log(this.toAdd);
        this.packages = '';
        this.packageQuantity = undefined;
        this.orderPackages.push(this.toAdd);
        }
    };

    removePackage(toDel): void {
        _.remove(this.orderPackages, toDel);

        this._orderPackageService.deleteOrderPackage(toDel.id).subscribe(result => {
            
        });
    };
    
    getpackageName(id){
        this._packageService.getShippingPackage(  
            id,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined
        ).subscribe(result => {
            this.toAddP.name = result.items[0].name;
            console.log(result);
        });
    }

    // Class definition
    ktwizard2(): void {
        // Base elements
        var wizardEl;
        var formEl;
        var validator;
        var wizard;


        // Private functions
        var initWizard = function () {
            // Initialize form wizard
            wizard = new KTWizard('kt_wizard_v2', {
                startStep: 1,
            });
            function validateEmail(sEmail) {
                var filter =/^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i;
                if (filter.test(sEmail)) {
                return true;
                }
                else {
                return false;
                }
            }
            // Validation before going to next page
            wizard.on('beforeNext', function (wizardObj) {
                // if (wizardObj.currentStep == 1) {
                //     if (($('#location').val() == null || $('#TagType').val() == null) || $('#Tag').val() == '') {
                //         wizardObj.stop();  // don't go to the next step
                //     }
                // } else 
                if (wizardObj.currentStep == 1) {
                    if ($('#pickupFirstNameInput').val() == '' || $('#pickupLastNameInput').val() == ''
                        || $('#PickupEta').val() == ''
                        || $('.pickUpFrom input').val()==''
                        || $('.pickUpTo input').val()=='') {
                        wizardObj.stop();  // don't go to the next step
                    }
                    if(!validateEmail($('#pickupEmailInput').val())){
                        wizardObj.stop(); 
                    }
                } else if (wizardObj.currentStep == 2) {

                    if ($('#pickupAddress1Input').val() == ''
                        || $('#pickupCountryInput').val() == null || $('#pickupPostalInput').val() == null
                        || $('#pickupStateInput').val() == null
                        || $('#pickupCityInput').val() == null) {
                        wizardObj.stop();  // don't go to the next step
                    }
                } else if (wizardObj.currentStep == 3) {

                    if ($('#destinationFirstNameInput').val() == '' || $('#destinationLastNameInput').val() == ''
                         || $('#DeliveryEta').val() == ''
                        || $('.deliveryFrom input').val()==''
                        || $('.deliveryTo input').val()=='') {
                        wizardObj.stop();  // don't go to the next step
                    }
                    if(!validateEmail($('#destinationEmailInput').val())){
                        wizardObj.stop(); 
                    }
                } else if (wizardObj.currentStep == 4) {
                    if ($('#destinationAddress1Input').val() == ''
                        || $('#destinationCountryInput').val() == null || $('#destinationPostalInput').val() == null
                        || $('#destinationStateInput').val() == null
                        || $('#destinationCityInput').val() == null) {
                        wizardObj.stop();
                    }
                } else if (wizardObj.currentStep == 5) {
                    if ($("#addedPackages tr").length <= 2) { //second tr
                        wizardObj.stop();
                    }
                } else if (wizardObj.currentStep == 6) {
                    if ($('#noteInput').val() == '') {
                        wizardObj.stop();
                    }
                }
                //console.log($(#nameInput).val());
            });
            // Change event
            wizard.on('change', function (wizard) {
                KTUtil.scrollTop();
            });
        }
        wizardEl = KTUtil.get('kt_wizard_v2');
        formEl = $('#kt_form').serialize();

        return initWizard();
        //return initValidation();
        //return initSubmit();
    }

}
