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, CreateOrderV2Input, PickupDetailInput, ContactInput, AddressInput, DestinationDetailInput, PackageInput, PostalCodeListDto, CreateNoteInput, CreateEmailInput, CreatePhoneInput } 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: './create-order.component.html',
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()]
})
export class CreateOrderComponent extends AppComponentBase {

    saving = false;
    createInput: CreateOrderV2Input = new CreateOrderV2Input();  

    pickupDetailInput: PickupDetailInput = new PickupDetailInput(); 
    pickupContactInput: ContactInput = new ContactInput();
    pickupContactAddress: AddressInput = new AddressInput;
    
    destinationDetailInput: DestinationDetailInput = new DestinationDetailInput; 
    destinationContactInput: ContactInput = new ContactInput;
    destinationContactAddress: AddressInput = new AddressInput;

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

    tagTypeFilter: TagTypeListDto = new TagTypeListDto();
    filteredTagType: any;
    tagType: any;
    packageFilter: ShippingPackageListDto = new ShippingPackageListDto();
    filteredPackage: any;
    filteredLocationPackages: any;


    filteredCountries: any;
    filteredCities: any;
    filteredStates: any;
    filteredPostal: any;
    noteInput: string;

    packages: Array<PackageInput> = []; 
    pickUpTo: any;
    pickUpFrom: any;
    deliveryFrom: any;
    deliveryTo: any;
    pickupEta: Date;
    deliveryEta: Date;

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

    pickuppostalId: PostalCodeListDto = new PostalCodeListDto();
    destinationpostalId: PostalCodeListDto = new PostalCodeListDto();
    locationInput: number;
    pickupPhone: string;
    pickupEmail: string;
    destinationPhone: string;
    destinationEmail: string;
    toAdd: PackageInput;


    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 _packageService: ShippingPackageServiceProxy,
        private router: Router
    ) {
        super(injector);
    }

    ngOnInit(){
        this.ktwizard2();
        this.filterLocation();
        this.filterTagType();

        // this.filterPostal();

        this.filterPackage();
        // this.filterLocationPackages();
        this.createInput = new CreateOrderV2Input();
        this.createInput.packageInput = Object();    
        this.pickuppostalId = new PostalCodeListDto();
        this.destinationpostalId = new PostalCodeListDto();
        this.locationInput = 0;
        this.pickupPhone = "";
        this.pickupEmail = "";
        this.destinationPhone = "";
        this.destinationEmail = "";
        this.createInput.destinationDetailInput = new DestinationDetailInput();
        this.createInput.pickupDetailInput = new PickupDetailInput();
        this.createInput.noteInput = new CreateNoteInput();
        this.createInput.destinationDetailInput.email = new CreateEmailInput();
        this.createInput.destinationDetailInput.phone = new CreatePhoneInput();
        this.createInput.pickupDetailInput.email = new CreateEmailInput();
        this.createInput.pickupDetailInput.phone = new CreatePhoneInput();
        this.createInput.tagType = new TagTypeListDto();
        this.orderPackageInput = new Object();
        this.toAdd = new PackageInput();
        var that = this;

        // $("#location").change(function(){
        //         this.selectedLocation = $("#location option:selected").text();
        //         $("#selectedLocation").text(this.selectedLocation);
        //         that.filterLocationPackages(undefined, $("#location").val());
        // });

        $("#packages").change(function(){
            // this.selectedLocation = $("#packages option:selected").text();
            // $("#selectedLocation").text(this.selectedLocation);
            // console.log(that.filterLocationPackages($("#packages").val(), $("#location").val()));
        });

        $("#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(){
        $('.kt-select2').select2({ 
            placeholder: "Select..",
            id: function(data){return {id: data.id};}
        });

       $('#kt_daterangepicker_5').daterangepicker({
                   buttonClasses: ' btn',
                   applyClass: 'btn-primary',
                   cancelClass: 'btn-secondary',

                   singleDatePicker: true,
                   showDropdowns: true,
                   locale: {
                       format: 'MM/DD/YYYY'
                   }
               }, function(start, end, label) {
                   $('#kt_daterangepicker_5 .form-control').val( start.format('MM/DD/YYYY') + ' / ' + end.format('MM/DD/YYYY'));
        });
    }

    save(): void {
 
        this.saving = true;
        this.pickupContactInput.addressInput = this.pickupContactAddress;
        this.pickupContactInput.addressInput.countryId =  Number((<HTMLInputElement>document.getElementById('pickupCountryInput')).value);
        this.pickupContactInput.addressInput.cityId = Number((<HTMLInputElement>document.getElementById('pickupCityInput')).value);
        this.pickupContactInput.addressInput.stateId = Number((<HTMLInputElement>document.getElementById('pickupStateInput')).value);
        this.pickupContactInput.addressInput.postalCodeId = Number((<HTMLInputElement>document.getElementById('pickupPostalInput')).value);
        this.createInput.pickupDetailInput.contactInput = this.destinationContactInput;
        this.createInput.pickupDetailInput.email.value = this.pickupEmail;
        this.createInput.pickupDetailInput.phone.value = this.pickupPhone;

        this.destinationContactInput.addressInput = this.destinationContactAddress;
        this.destinationContactInput.addressInput.countryId = Number((<HTMLInputElement>document.getElementById('destinationCountryInput')).value);
        this.destinationContactInput.addressInput.cityId =  Number((<HTMLInputElement>document.getElementById('destinationCityInput')).value);
        this.destinationContactInput.addressInput.stateId = Number((<HTMLInputElement>document.getElementById('destinationStateInput')).value);
        this.destinationContactInput.addressInput.postalCodeId = Number((<HTMLInputElement>document.getElementById('destinationPostalInput')).value);
        this.createInput.destinationDetailInput.contactInput = this.destinationContactInput;
        this.createInput.destinationDetailInput.email.value = this.destinationEmail;
        this.createInput.destinationDetailInput.phone.value = this.destinationPhone;
        
        // this.createInput.locationId = this.locationInput;
        this.createInput.locationId =  Number((<HTMLInputElement>document.getElementById('location')).value);
        this.createInput.tagType.id =  Number((<HTMLInputElement>document.getElementById('TagType')).value);
     
        // this.createInput.locationId =  Number((<HTMLInputElement>document.getElementById('selectPreview')).value);
        this.createInput.pickupDetailInput.etaStart = moment.utc(moment(this.pickupEta).format('YYYY-MM-DD') + ' ' + moment(this.pickUpFrom).format('HH:mm:ss'));
        this.createInput.pickupDetailInput.etaEnd = moment.utc(moment(this.pickupEta).format('YYYY-MM-DD') + ' ' + moment(this.pickUpTo).format('HH:mm:ss'));

        this.createInput.destinationDetailInput.etaStart = moment.utc(moment(this.deliveryEta).format('YYYY-MM-DD') + ' ' + moment(this.deliveryFrom).format('HH:mm:ss'));
        this.createInput.destinationDetailInput.etaEnd = moment.utc(moment(this.deliveryEta).format('YYYY-MM-DD') + ' ' + moment(this.deliveryTo).format('HH:mm:ss'));

        this.createInput.noteInput.content = this.noteInput;

        this.createInput.packageInput = this.packages;


        this._orderAppService.createOrderV2(this.createInput)
            .pipe(finalize(() => { }))
            .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;
    //     });
    // }

    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 PackageInput();
        // console.log((<HTMLInputElement>document.getElementById('packages')).selectedOptions);
        this.toAdd.packageId = Number((<HTMLInputElement>document.getElementById('packages')).value);
        this.toAdd.quantity = this.packageQuantity;
        this.spinnerService.show();
        this.toAdd.packageName =  (String(await this.getpackageName(this.toAdd.packageId))) ? 'Adding...' : 'Failed to Add';
        this.spinnerService.hide();
        this.addPackage = '';
        this.packageQuantity = undefined;
        this.packages.push(this.toAdd);
        this.packageNameMessageError=false; 
        this.packageQtyMessageError=false; 
        }
    };

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

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

     // 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 ($('#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());
                // console.log(wizardObj.currentStep)
            });
            // 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();
    }
    onChange(newValue) {
        console.log(newValue);
    }

  
}
