import { Component, Injector, EventEmitter, Output, ViewChild } from "@angular/core";
import { appModuleAnimation } from "@shared/animations/routerTransition";
import { AppComponentBase } from "@shared/common/app-component-base";
import { OrderServiceProxy, LocationServiceProxy, TagTypeServiceProxy, PostalCodeServiceProxy, ShippingPackageServiceProxy, OrderPackageServiceProxy, PackageInput, OrderListDto, OrderPackageListDto, PackagesServiceProxy, NoteServiceProxy, CreateNoteInput, UpdateNoteInput, UpdateOrderInput } from "@shared/service-proxies/service-proxies";
import { ActivatedRoute, Router } from "@angular/router";
import { Location} from "@angular/common";
import * as moment from 'moment';
import { ModalDirective } from "ngx-bootstrap";
import { finalize } from "rxjs/operators";
declare var KTWizard: any;
declare let swal: any;
import { HttpClientModule } from '@angular/common/http';
@Component({
    templateUrl: './view-order.component.html',
    styleUrls: ['./view-order.component.css'],
    animations: [appModuleAnimation()],
    selector: 'viewOrderComponent'
})

export class ViewOrderComponent extends AppComponentBase {

    @ViewChild('createOrEditModal', { static: true }) modal: ModalDirective;
    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    id: any;
    packageQuantity: number;
    packageNameMessageError: boolean = false;
    packageQtyMessageError: boolean = false;
    filteredPackage: any;
    toAdd: PackageInput;
    packageList: Array<PackageInput> = [];
    orderPackages: Array<OrderPackageListDto> = [];
    orderInput: OrderListDto = new OrderListDto();

    location: string;
    customerName: string;
    creationTime: string;
    pickUpContact: string;
    deliveryContact: string;
    pickupEta: Date;
    pickUpTo: Date;
    pickUpFrom: Date;
    deliveryEta: Date;
    deliveryTo: Date;
    deliveryFrom: Date;
    note: string;
    noteId: number;

    deliveryName: string;
    deliveryCompany: string;
    deliveryAddressLine1: string;
    deliveryAddressLine2: string;
    deliveryCity: string;
    deliveryState: string;
    deliveryPostalCode: string;
    deliveryPhone: string;
    deliveryEmail: string;

    pickUpName: string;
    pickUpCompany: string;
    pickUpAddressLine1: string;
    pickUpAddressLine2: string;
    pickUpCity: string;
    pickUpState: string;
    pickUpPostalCode: string;
    pickUpPhone: string;
    pickUpEmail: string;

    CreateNoteInput: CreateNoteInput = new CreateNoteInput();
    UpdateNoteInput: UpdateNoteInput = new UpdateNoteInput();
    UpdateOrderInput: UpdateOrderInput = new UpdateOrderInput();
    active: boolean = false;
    saving: boolean = false;
    trackingIdentifier : string = "None";
    orderNumber: string = "None";


    constructor(
        injector: Injector,
        private _orderAppService: OrderServiceProxy,
        private _locationAppService: LocationServiceProxy,
        private _tagTypeAppService: TagTypeServiceProxy,
        private _postalCodeService: PostalCodeServiceProxy,
        private _packageService: ShippingPackageServiceProxy,
        private _orderPackageService: OrderPackageServiceProxy,
        private route: ActivatedRoute,
        private router: Router,
        private _packagesServiceProxy: PackagesServiceProxy,
        private _noteServiceProxy: NoteServiceProxy,
        private _location: Location
    ) { super(injector); }

    ngOnInit() {
        $('.kt-select2').select2({
            placeholder: "Select..",
        });
        this.packageList=[];
        // this.ktwizard2();
        this.route.paramMap.subscribe(params => {
            this.id = params.get("id")
        });
        this.filterPackage();
        this._orderAppService.getOrderForUpdate(this.id)
            .pipe()
            .subscribe(result => {
                this.orderInput = result;
                console.log(this.orderInput.deliveryDetail.contact.address.id);
                this.location = this.orderInput.location.name;
                this.customerName = this.orderInput.pickupDetail.contact.firstName + " " +this.orderInput.pickupDetail.contact.lastName;
                this.creationTime = moment(moment.utc(this.orderInput.creationTime)).format('YYYY-MM-DD hh:mm:ss A');
                this.pickUpContact = this.orderInput.pickupDetail.contact.firstName + " " +this.orderInput.pickupDetail.contact.lastName
                +", " +this.orderInput.pickupDetail.contact.address.addressLine1 + ", "
                    + this.orderInput.pickupDetail.contact.address.postalCode.city + ", " + this.orderInput.pickupDetail.contact.address.postalCode.state + ", "
                    + this.orderInput.pickupDetail.contact.address.postalCode.value;
                this.deliveryContact = this.orderInput.deliveryDetail.contact.firstName + ", " + this.orderInput.deliveryDetail.contact.address.addressLine1 + ", "
                    + this.orderInput.deliveryDetail.contact.address.postalCode.city + ", " + this.orderInput.deliveryDetail.contact.address.postalCode.state + ", "
                    + this.orderInput.deliveryDetail.contact.address.postalCode.value;
                this.pickupEta = moment.utc(this.orderInput.pickupDetail.etaEnd).toDate();
                this.pickUpTo = moment.utc(this.orderInput.pickupDetail.etaEnd).toDate();
                this.pickUpFrom = moment.utc(this.orderInput.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.note = (this.orderInput.note == null || this.orderInput.note == undefined) ? "" : this.orderInput.note.content;
                this.noteId = (this.orderInput.note == null || this.orderInput.note == undefined) ? null : this.orderInput.note.id;
                this.pickUpName = this.orderInput.pickupDetail.contact.firstName;
                this.pickUpCompany = this.orderInput.pickupDetail.contact.firstName;
                this.pickUpAddressLine1 = this.orderInput.pickupDetail.contact.address.addressLine1;
                this.pickUpAddressLine2 = this.orderInput.pickupDetail.contact.address.addressLine2;
                this.pickUpCity = this.orderInput.pickupDetail.contact.address.postalCode.city;
                this.pickUpState = this.orderInput.pickupDetail.contact.address.postalCode.state;
                this.pickUpPostalCode = this.orderInput.pickupDetail.contact.address.postalCode.value;
                this.pickUpPhone = (this.orderInput.pickupDetail.contact.phones == null || this.orderInput.pickupDetail.contact.phones == undefined) ? "" : this.orderInput.pickupDetail.contact.phones.value;
                this.pickUpEmail = (this.orderInput.pickupDetail.contact.emails == null || this.orderInput.pickupDetail.contact.emails == undefined) ? "" : this.orderInput.pickupDetail.contact.emails.value;


                this.deliveryName = this.orderInput.deliveryDetail.contact.firstName;
                this.deliveryCompany = this.orderInput.deliveryDetail.contact.firstName;
                this.deliveryAddressLine1 = this.orderInput.deliveryDetail.contact.address.addressLine1;
                this.deliveryAddressLine2 = this.orderInput.deliveryDetail.contact.address.addressLine2;
                this.deliveryCity = this.orderInput.deliveryDetail.contact.address.postalCode.city;
                this.deliveryState = this.orderInput.deliveryDetail.contact.address.postalCode.state;
                this.deliveryPostalCode = this.orderInput.deliveryDetail.contact.address.postalCode.value;
                this.deliveryPhone = (this.orderInput.deliveryDetail.contact.phones == null || this.orderInput.deliveryDetail.contact.phones == undefined) ? "" : this.orderInput.deliveryDetail.contact.phones.value;
                this.deliveryEmail = (this.orderInput.deliveryDetail.contact.emails == null || this.orderInput.deliveryDetail.contact.emails == undefined) ? "" : this.orderInput.deliveryDetail.contact.emails.value;

                this.orderPackages = this.orderInput.orderPackages;
                let key, key2;
                for (key in this.orderPackages) {
                    this.toAdd = new PackageInput();
                    this.toAdd.packageName = this.orderPackages[key]['package']['name'];
                    this.toAdd.packageId = this.orderPackages[key]['package']['id'];
                    this.toAdd.price = this.orderPackages[key]['package']['price'];
                    this.toAdd.quantity = this.orderPackages[key]['quantity'];
                    if(this.orderPackages[key]['package']['name']!=="Default"){
                        this.packageList.push(this.toAdd);
                    }
                    console.log(this.packageList.length)
                }
                if (this.orderInput.orderTags.length!=0){
                    for (key2 in this.orderInput.orderTags){
                        if(this.orderInput.orderTags[key2]['tag']['tagType']['name']=="Tracking Identifier"){
                            this.trackingIdentifier = this.orderInput.orderTags[key2]['tag']['name'];
                        }
                        if(this.orderInput.orderTags[key2]['tag']['tagType']['name']=="Order Number"){
                            this.orderNumber = this.orderInput.orderTags[key2]['tag']['name'];
                        }
                    }
                }else{
                  this.trackingIdentifier = 'None';
                  this.orderNumber = "None";
                }
            });
    }

    ngAfterViewInit() {
    }

    saveNote() {
        if (this.noteId == null) {
            this.CreateNoteInput.content = this.note;
            this._noteServiceProxy.createNote(this.CreateNoteInput).pipe(finalize(() => { this.saving = false; }))
                .subscribe(result => {
                    this.UpdateOrderInput.id = this.id;
                    this.UpdateOrderInput.deliveryDetailsId = this.orderInput.deliveryDetail.id;
                    this.UpdateOrderInput.pickupDetailsId = this.orderInput.pickupDetail.id;
                    this.UpdateOrderInput.locationId = this.orderInput.location.id;
                    this.UpdateOrderInput.noteId = result;
                    this.UpdateOrderInput.userId = this.orderInput.user.id;
                    this._orderAppService.updateOrder(this.UpdateOrderInput).pipe().subscribe(result => {
                        // this.router.navigateByUrl("/app/sprintship/order-update/" +this.id);
                        this.router.navigateByUrl("/app/sprintship/order-update/", { skipLocationChange: true }).then(() => {
                            console.log(this._location.path())
                            this.router.navigate([this._location.path()]);
                        }); 
                        this.notify.info(this.l('SavedSuccessfully'));
                    });
                });
        } else {
            this.UpdateNoteInput.id = this.noteId;
            this.UpdateNoteInput.content = this.note;
            this._noteServiceProxy.updateNote(this.UpdateNoteInput).pipe(finalize(() => { this.saving = false; }))
                .subscribe((
                ) => {
                    // this.router.navigateByUrl("/app/sprintship/order-update/" +this.id, { skipLocationChange: true }).then(() => {
                    //     console.log(this._location.path())
                    //     this.router.navigate(["/app/sprintship/order-update/" +this.id]);
                    // }); 
                    this.ngOnInit();
                    this.notify.info(this.l('SavedSuccessfully'));
                });
        }
    }
    close(): void {

        this.active = false;
        this.modal.hide();
    }

    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)
                    console.log(this.packageList);
                }
                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)
            }
        }
    }

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

    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) {
                } else if (wizardObj.currentStep == 2) {

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

    viewOrderSave(v:boolean){
        this.ngOnInit();
    }

}