import { Component, Injector, ViewChild, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AppConsts } from '@shared/AppConsts';
import { Router } from '@angular/router';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { EntityDtoOfInt64, ContactServiceProxy, ContactListDto, PostalCodeServiceProxy, AddressTypeServiceProxy } from '@shared/service-proxies/service-proxies';
import { FileDownloadService } from '@shared/utils/file-download.service';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { HttpClient } from '@angular/common/http';
import { FileUpload } from 'primeng/fileupload';
import { finalize } from 'rxjs/operators';

@Component({
    templateUrl: './vendors.component.html',
    encapsulation: ViewEncapsulation.None,
    styleUrls: ['./vendors.component.less'],
    animations: [appModuleAnimation()]
})
export class VendorsComponent extends AppComponentBase {

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

    //Filters
    filters: {
        id: number;
        firstName: string;
        lastName: string;
        filter: string,
        postalCodeValue: string,
        state: string,
        city: string,
        addressType: string,
        emailAddress: string,
        phoneNumber: string,
        addressLine1: string,
        addressLine2: string,

    } = <any>{};

    filteredPostal:any;
    filteredCountries:any;
    filteredStates:any;
    filteredCities:any;
    filteredAddressType:any;

    advancedFiltersAreShown = false;
    constructor(
        injector: Injector,
        private _contactService: ContactServiceProxy,
        private _addressTypeService: AddressTypeServiceProxy,
        private _postalCodeService: PostalCodeServiceProxy,
        private _activatedRoute: ActivatedRoute,
        private _httpClient: HttpClient,
        private _router: Router,
        private _fileDownloadService: FileDownloadService,
        

    ) {
        super(injector);
    }

    ngOnInit(){
        this.filterPostal();
        this.filterCities();
        this.filterStates();
        this.filterAddressTypes();
        $('.kt-select2').select2();
    }

    getContact(event?: LazyLoadEvent) {
        this.filters.postalCodeValue = (<HTMLInputElement>document.getElementById('postalCodeInput')).value!="0" ? (<HTMLInputElement>document.getElementById('postalCodeInput')).value : undefined;
        this.filters.state = (<HTMLInputElement>document.getElementById('stateSelectInput')).value!="0" ? (<HTMLInputElement>document.getElementById('stateSelectInput')).value : undefined;
        this.filters.city = (<HTMLInputElement>document.getElementById('citySelectInput')).value!="0" ? (<HTMLInputElement>document.getElementById('citySelectInput')).value : undefined;
        this.filters.addressType = (<HTMLInputElement>document.getElementById('addressTypeSelectInput')).value!="0" ? (<HTMLInputElement>document.getElementById('addressTypeSelectInput')).value : undefined;
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);

            return;
        }

        this.spinnerService.show();

        this._contactService.getContactVendorQPaged(
            undefined,
            undefined,
            undefined,
            undefined,
            this.filters.postalCodeValue,
            this.filters.state,
            this.filters.city,
            undefined,
            this.filters.addressLine1,
            undefined,
            undefined,
            this.filters.filter,
            this.filters.firstName,
            this.filters.lastName,
            this.filters.emailAddress,
            this.filters.phoneNumber,
            this.filters.addressType,
            this.primengTableHelper.getSorting(this.dataTable),
            this.primengTableHelper.getMaxResultCount(this.paginator, event),
            this.primengTableHelper.getSkipCount(this.paginator, event)
        ).pipe(finalize(() => this.spinnerService.hide())).subscribe(result => {
            this.primengTableHelper.totalRecordsCount = result.totalCount;
            this.primengTableHelper.records = result.items;
            this.spinnerService.hide();
        });
    }

    reloadPage(): void {
        this.paginator.changePage(this.paginator.getPage());
    }

    deleteContact(contact: ContactListDto): void {

        this.message.confirm(
            this.l('VendorDeleteWarningMessage', contact.firstName+" "+contact.lastName),
            this.l('AreYouSure'),
            (isConfirmed) => {
                if (isConfirmed) {
                    this._contactService.deleteContact(contact.id)
                        .subscribe(() => {
                            this.reloadPage();
                            this.notify.success(this.l('SuccessfullyDeleted'));
                        });
                }
            }
        );
    }

    createOrEditVendor(url: any, id?: number){
        if(id != null){
            var myurl = `${url}/${id}`;
        }else{
            var myurl = `${url}`;
        }
        console.log(myurl);
        this._router.navigateByUrl(myurl);
    }

     exportToExcel(): void {
        // this.filters.postalCodeValue = (<HTMLInputElement>document.getElementById('postalCodeInput')).value=="" ? (<HTMLInputElement>document.getElementById('postalCodeInput')).value : undefined;
        // this.filters.state = (<HTMLInputElement>document.getElementById('stateSelectInput')).value=="" ? (<HTMLInputElement>document.getElementById('stateSelectInput')).value : undefined;
        // this.filters.city = (<HTMLInputElement>document.getElementById('citySelectInput')).value=="" ? (<HTMLInputElement>document.getElementById('citySelectInput')).value : undefined;
        // this.filters.addressType = (<HTMLInputElement>document.getElementById('addressTypeSelectInput')).value=="" ? (<HTMLInputElement>document.getElementById('addressTypeSelectInput')).value : undefined;        this._contactService.getVendorToExcel(
        //     undefined,
        //     undefined,
        //     undefined,
        //     this.filters.postalCodeId,
        //     this.filters.nameFilter,
        //     this.filters.firstName,
        //     this.filters.lastName
        // )
        // .subscribe(result => {
        //     console.log(result);
        //     this._fileDownloadService.downloadTempFile(result);
        //  });
    }

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

    filterStates(): void {
        this._postalCodeService.getDistinctState(
            undefined,
            undefined
        ).subscribe(result => {
            this.filteredStates = result.items;
        });
    }

    filterCities(): void {
        this._postalCodeService.getDistinctCity(
            undefined,
            undefined
        ).subscribe(result => {
            this.filteredCities = result.items;
        });
    }

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