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, PackagesServiceProxy, CreateOrderApiInput, TagInput, CreateOrderDefaultInput } 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;
declare let swal: any;
@Component({
    templateUrl: './create-order.component.html',
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()],
    styleUrls: ['create-order.component.less']
})
export class CreateOrderComponent extends AppComponentBase {

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

    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;
    packagePrice: any;


    filteredCountries: any;
    filteredCities: any;
    filteredStates: any;
    filteredPostal: any;
    filteredDestinationCountries: any;
    filteredDestinationStates: any;
    filteredDestinationCities: any;

    filteredDestinationPostal: any;
    filteredPackages: any;
    noteInput: string;

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

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

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


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

    pickupFilterChange = false;
    destinationFilterChange = false;
    
    tagValue: string;

    constructor(
        injector: Injector,
        private _orderAppService: OrderServiceProxy,
        private _locationAppService: LocationServiceProxy,
        private _tagTypeAppService: TagTypeServiceProxy,
        private _postalCodeService: PostalCodeServiceProxy,
        private _packageService: ShippingPackageServiceProxy,
        private _packagesServiceProxy: PackagesServiceProxy,

        private router: Router
    ) {
        super(injector);
    }

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

        this.filterPostal();

        this.filterPackage();
        // this.filterLocationPackages();
        this.createInput = new CreateOrderDefaultInput();
        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);
            this.selectedPickupPostalCode = this.selectedPickupPostalCode.trim();
            that.pickupFilterChange = true;
            that.filterCountries(this.selectedPickupPostalCode)
            that.filterStates(this.selectedPickupPostalCode)
            that.filterCities(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);
            this.selectedDestinationPostalCode = this.selectedDestinationPostalCode.trim()
            that.destinationFilterChange = true
            that.filterDestinationCountries(this.selectedDestinationPostalCode)
            that.filterDestinationStates(this.selectedDestinationPostalCode)
            that.filterDestinationCities(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);
        });
        // $("#packagess").change(function () {
        //     that.filterPackages($("#packagess").val());
        // });
    }

    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'));
        });

        var KTWizard2 = function () {
            var e, r, i;
            $(".pickUpFrom input").attr("name", "pickUpFrom");
            $(".pickUpTo input").attr("name", "pickUpTo");
            $(".deliveryFrom input").attr("name", "deliveryFrom");
            $(".deliveryTo input").attr("name", "deliveryTo");

            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: {
                                pickupFirstNameInput: { required: !0 },
                                pickupLastNameInput: { required: !0 },
                                pickupEmailInput: { required: !0, email: !0 },
                                PickupEta: { required: !0 },
                                pickUpFrom: { required: !0 },
                                pickUpTo: { required: !0 },
                                deliveryFrom: { required: !0 },
                                deliveryTo: { 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() });
    }

    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.createInput.pickUpPostalCodeId = Number((<HTMLInputElement>document.getElementById('pickupPostalInput')).value);
        // this.createInput.pickupDetailInput.contactInput = this.destinationContactInput;
        // this.createInput.pickUpEmail = this.pickupEmail;
        // this.createInput.pickUpPhone = 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.createInput.destinationPostalCodeId = Number((<HTMLInputElement>document.getElementById('destinationPostalInput')).value);
        // this.createInput.destinationDetailInput.contactInput = this.destinationContactInput;
        // this.createInput.destinationEmail = this.destinationEmail;
        // this.createInput.destinationPhone = 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.pickUpEtaStart = moment.utc(moment(this.pickupEta).format('YYYY-MM-DD') + ' ' + moment(this.pickUpFrom).format('HH:mm:ss'));
        this.createInput.pickUpEtaEnd = moment.utc(moment(this.pickupEta).format('YYYY-MM-DD') + ' ' + moment(this.pickUpTo).format('HH:mm:ss'));
        this.createInput.destinationEtaStart = moment.utc(moment(this.deliveryEta).format('YYYY-MM-DD') + ' ' + moment(this.deliveryFrom).format('HH:mm:ss'));
        this.createInput.destinationEtaEnd = moment.utc(moment(this.deliveryEta).format('YYYY-MM-DD') + ' ' + moment(this.deliveryTo).format('HH:mm:ss'));
        this.createInput.noteInput = this.noteInput;
        this.createInput.packageInput = this.packageList;
        this.createInput.tagInput = this.tagList;

        console.log(this.createInput);

        this._orderAppService.createOrderDefault(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,
            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.getDistinctPostalCode(
            undefined
        ).subscribe(result => {
            this.filteredPostal = result.items;
            this.filteredDestinationPostal = result.items
        });
    }

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

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

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

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

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

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



    filterPackage(): void {
        this.spinnerService.show();
        this._packagesServiceProxy.getAll(
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined
        ).subscribe(result => {
            this.filteredPackage = result.items;
            this.spinnerService.hide();
        });
    }


    filterPackages(id): void {
        this._packagesServiceProxy.getPackageForView(id
        ).subscribe(result => {
            this.filteredPackages = result;
            //console.log(this.filteredPackages['package']['price']);
            $("#packagePrice").val(this.filteredPackages['package']['price']);
        });
    }

    addTag() {
        
        let key, tagTypeId, tagValue, key2, arrAny = {};
        tagTypeId = Number((<HTMLInputElement>document.getElementById('tagType')).value);
        tagValue = $("#tagValue").val();
        if ((tagTypeId === 0 || tagTypeId == null) && (tagValue === "" || tagValue == null)) {
            this.tagNameMessageError = true;
            this.tagValueMessageError = true;
        } else if ((tagTypeId === 0 || tagTypeId == null)) {
            this.tagNameMessageError = true;
            this.tagValueMessageError = false;
        } else if ((tagValue === "" || tagValue == null)) {
            this.tagNameMessageError = false;
            this.tagValueMessageError = true;
        } else {
            for (key in this.filteredTagType) {
                if (tagTypeId == this.filteredTagType[key].id) {
                        this.toAddTag = new TagInput();
                        this.toAddTag.tagTypeName = this.filteredTagType[key].name;
                        this.toAddTag.tagTypeId =  this.filteredTagType[key].id;
                        this.toAddTag.value =  tagValue;
                        this.tagList.push(this.toAddTag)
                    // $("#nextStep").attr("disabled", false);
                }
            }
            this.tagNameMessageError = false;
            this.tagValueMessageError = false;
            $("#tagValue").val(0);
        }
    }

    removeTag(tag) {
        let key;
        for (key in this.tagList) {
            if (tag.tagTypeId == this.tagList[key].tagTypeId) {
                this.tagList.splice(key, 1)
            }
        }
    }

    addPackageToList() {
        let key, packageId, packagePrice, tagValue, key2, arrAny = {};
        packageId = Number((<HTMLInputElement>document.getElementById('packagess')).value);
        if ((packageId === 0 || packageId == null) && (this.packageQuantity === 0 || this.packageQuantity == null)) {
            this.packageNameMessageError = true;
            this.packageQtyMessageError = true;
        } else if ((packageId === 0 || packageId == null)) {
            this.packageNameMessageError = true;
            this.packageQtyMessageError = false;
        } else if ((this.packageQuantity === 0 || this.packageQuantity == null)) {
            this.packageNameMessageError = false;
            this.packageQtyMessageError = true;
        } else {
            for (key in this.filteredPackage) {
                if (packageId === this.filteredPackage[key]['package']['id']) {
                        this.toAdd = new PackageInput();
                        this.toAdd.packageName = this.filteredPackage[key]['package']['name'];
                        this.toAdd.packageId = this.filteredPackage[key]['package']['id'];
                        this.toAdd.quantity =  this.packageQuantity;
                        this.toAdd.price =  this.filteredPackage[key]['package']['price'];
                        console.log(this.toAdd);
                    this.packageList.push(this.toAdd)
                }
                this.packageNameMessageError = false;
                this.packageQtyMessageError = false;
            }
        }
    }
    removePackageToList(packages) {
        let key;
        for (key in this.packageList) {
            if (packages.packageId == this.packageList[key].packageId) {
                this.packageList.splice(key, 1)
            }
        }
    }
}
