import { Component, OnInit, OnDestroy, TemplateRef } from "@angular/core";
import { takeUntil, finalize } from "rxjs/operators";
import { Page, IUserAccount, IResource } from "@shared/models";
import { AppData, ResourceService, HttpService, NotifyService } from "@shared/services";
import { NgbModal, NgbModalRef } from "@ng-bootstrap/ng-bootstrap";
import { FormGroup, FormBuilder, FormArray, Validators } from "@angular/forms";
import { ApiResources, UtilHelper } from "@shared/helpers";
import { HttpErrorResponse } from "@angular/common/http";
import { DoctorUnits, TagDoctors } from "@shared/entities";
import { Observable } from "rxjs";


class FilterOptions {
    code: string = null;
    doctorUnitMasterId: number;
    locationId: number = null;
}
class Filters {
    options: FilterOptions;
    applied: boolean;
    constructor() {
        this.init();
    }

    init() {
        this.options = new FilterOptions();
        this.applied = undefined;
    }
}

@Component({
    templateUrl: "./doctor-unit.html",
})

export class DoctorUnitPage implements OnInit, OnDestroy {
    page: Page;
    submitting: boolean;
    modalRef: NgbModalRef;
    loading: boolean;
    submitted: boolean;
    doctorunitForm: FormGroup;
    locations: Array<IResource>;
    currenrLocation: number;
    departments: Array<IResource>;
    loadDepartments: boolean;
    loadProvider: boolean;
    providers: Array<IResource>;
    loadlocation: boolean;
    addSlotTimingsArrayForm: FormGroup;
    records: Array<DoctorUnits>
    filters: Filters;
    loadingUnitNames: boolean;
    filterUnitName: Array<IResource>
    selectedDoctor: Array<IResource>;
    doctors: Observable<Array<IResource>>;


    constructor(
        private readonly appData: AppData,
        private readonly modalService: NgbModal,
        private readonly formBuilder: FormBuilder,
        private readonly resourceService: ResourceService,
        private readonly httpService: HttpService,
        private readonly notifyService: NotifyService,

       
        
       
    ) {
       
        this.page = new Page();
        this.buildForm();
        this.filters = new Filters();
        this.records = new Array<DoctorUnits>();
        
    }

    private buildForm() {
        this.doctorunitForm = this.formBuilder.group({
            doctorUnitMasterId: 0,
            unitName: [null, [Validators.required]],
            code: [null, [Validators.required]],
            locationId: [null, [Validators.required]],
            departmentId: 0,
            tagDoctor: this.formBuilder.array([]),

        })

        this.doctorunitForm.get("locationId").valueChanges.subscribe((value: number)=> {
            this.fetchProviders(value)
        })

        //this.doctorunitForm.get("providerId").valueChanges.subscribe((value?: number) => {
        //    this.selectedDoctor = new Array<IResource>();
        //    if (value) {
        //        this.selectedDoctor = UtilHelper.cloneList(this.providers);
        //        var getIndexOfSelectedPatient = this.selectedDoctor.findIndex(x => x.id === value);
        //        if (getIndexOfSelectedPatient >= 0) {
        //            this.selectedDoctor.splice(getIndexOfSelectedPatient, 1);
        //        }
        //    } else {
        //        this.selectedDoctor = new Array<IResource>();
        //    }
        //});
    }
    private buildTagDoctorForm(tagDoctor?: TagDoctors) {
        if (this.tagDoctorArray.length <= 0) {
            return this.formBuilder.group({
                providerId: [tagDoctor ? tagDoctor.providerId : null, [Validators.required]],
                designation: [tagDoctor ? tagDoctor.designation : "Senior", [Validators.required]],
                tagDoctorId: [tagDoctor ? tagDoctor.tagDoctorId : null],
                //doctorUnitMasterId: [tagDoctor ? tagDoctor.doctorUnitMasterId:0]

            });
        }
        else {
            return this.formBuilder.group({
                providerId: [tagDoctor ? tagDoctor.providerId : null, [Validators.required]],
                designation: [tagDoctor ? tagDoctor.designation : null, [Validators.required]],
                tagDoctorId: [tagDoctor ? tagDoctor.tagDoctorId : null],
                //doctorUnitMasterId: [tagDoctor ? tagDoctor.doctorUnitMasterId:0]

            });
        }
    }
    onAddTagDoctor() {
        this.tagDoctorArray.push(this.buildTagDoctorForm());
       
    }
    get tagDoctorArray() { return this.doctorunitForm.controls["tagDoctor"] as FormArray }


    get tagForm() {
        return this.tagDoctorArray;
    }

    get form() {
        return this.doctorunitForm.controls;
    }
    
    onRemoveTagDoctor(index: number) {
        this.tagDoctorArray.removeAt(index);
       
    }
    onChangeProvider(data: any) {
        //if (data) {
        //    let index = this.providers.findIndex(s => s.id == data.id);
        //    this.providers.splice(index, 1);
        //}        
        if (data) {     
            this.doctorunitForm.patchValue({
                providerId: null
            });
            let docArray = this.doctorunitForm.value.tagDoctor as Array<any>;
            let ifExists = docArray.filter(l => l.providerId === data.id);
            if (ifExists.length > 1) {
                this.notifyService.warningToast("This Doctor is already added.,Please change the Doctor");  
               // this.doctorunitForm.get("tagDoctor").patchValue({ providerId: null })
                return;
            }
           // let form = this.buildLabArrayForm(lab);
        }
    }
    onChangeProvider1(control: FormGroup) {
        const providerIdValue = control.controls["providerId"].value;
        const providerId = control.controls["providerId"];
        let docArray = this.doctorunitForm.value.tagDoctor as Array<any>;
        let ifExists = docArray.filter(l => l.providerId === providerIdValue);
        if (ifExists.length > 1) {
            this.notifyService.warningToast("This Doctor is already added.,Please change the Doctor");
            providerId.setValue(null);
            providerId.updateValueAndValidity();
            control.updateValueAndValidity();
            return;
        }
    }
    //onAddLabToForm(lab: LabMainDetail) {
    //    if (lab) {
    //        this.billForm.patchValue({
    //            term: null
    //        });
    //        let labArray = this.billForm.value.labs as Array<any>;
    //        let ifExists = labArray.filter(l => l.labMainDetailId === lab.labMainDetailId);
    //        if (ifExists.length > 0) {
    //            this.notifyService.warningToast("This lab already added.");
    //            return;
    //        }
    //        let form = this.buildLabArrayForm(lab);
    //        form.patchValue({
    //            charges: lab.charges
    //        });
    //        this.forms.labsFormArray.push(form);
    //    }
    //}


    onApplyFilters() {
        this.filters.applied = UtilHelper.isFiltersApplied(this.filters.options);
        this.loading = true;
        this.fetchAll();
        
    }

    onResetFilters() {
        this.loading = true;
        this.filters.init();
        this.fetchAll();
        this.fetchFilterUnitNames(null);
    }
    private fetchLocations() {
        this.loadlocation = true;
        this.resourceService.locations()
            .pipe(finalize(() => { this.loadlocation = false }))
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: Array<IResource>) => {
                this.locations = response;
                //this.doctorunitForm.patchValue({
                //    locationId: this.currenrLocation
                //})
            });
    }
    //private fetchDepartments() {
    //    this.loadDepartments = true;
    //    this.resourceService.department()
    //        .pipe(finalize(() => { this.loadDepartments = false }))
    //        .pipe(takeUntil(this.page.unSubscribe))
    //        .subscribe((response: Array<IResource>) => {
    //            this.departments = response;
    //        });
    //}
    private fetchProviders(id?: number) {
        this.loadProvider = true;
        this.resourceService.providerAccountLocationMap(id)
            .pipe(finalize(() => { this.loadProvider = false }))
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: Array<IResource>) => {
                this.providers = response;
            });
    }
    onChangeLocation(data: any) {
        if (data) {
            this.fetchFilterUnitNames(data.id);
        }
        else {
            this.fetchFilterUnitNames(null);
        }
    }
    onOpenModel(content: TemplateRef<any>, record?: DoctorUnits) {
        this.buildForm();
        //this.fetchProviders(null);
        if (record) {
            this.doctorunitForm.patchValue({
                doctorUnitMasterId: record.doctorUnitMasterId,
                unitName: record.unitName,
                code: record.code,
                locationId: record.locationId,
                departmentId: record.departmentId
            })
            record.tagDoctor.forEach((item) => {
                var each = this.buildTagDoctorForm(item);
                this.tagDoctorArray.push(each);
                //this.providers.splice(item.tagDoctorId, 1);
            })
        }
        else {
            this.onAddTagDoctor();
        }
        this.modalRef = this.modalService.open(content, {
            backdrop: "static",
            keyboard: false,
            centered: false,
            windowClass: "custom-modal effect-scale"
        });
        
    }
    onCloseModal() {
        try {
            this.modalRef.close();
            this.modalRef = undefined;
        }
        catch(e) {
            
        }
        this.loading = false;
        this.submitting = undefined;
        this.submitted = undefined;
    }

    onSubmit() {
        this.submitted = true;
        if (this.doctorunitForm.invalid) {
            return;
        }
        this.submitting = true;
        const request = {
            ...this.doctorunitForm.getRawValue(),
            createdBy: this.page.userAccount.accountId,
            createdByName: this.page.userAccount.fullName,
            loginRoleId: this.page.userAccount.roleId,
            active: true,
        };
        var url = ApiResources.getURI(ApiResources.doctorUnit.base, ApiResources.doctorUnit.insert);
        if (request["doctorUnitMasterId"] > 0) {
            url = ApiResources.getURI(ApiResources.doctorUnit.base, ApiResources.doctorUnit.update);
        }
        this.httpService.post(url, request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.submitted = this.submitting = false))
            .subscribe(
                (response: string) => {
                    this.notifyService.successToast(response);
                    this.onCloseModal();
                    this.fetchAll();
                    
                },
                (error: HttpErrorResponse) => {
                    const errorMessage = UtilHelper.handleError(error);
                    if (errorMessage) {
                        this.notifyService.warningToast(errorMessage);
                    } else {
                        this.notifyService.defaultError();
                    }
                }
            );
    }
    onModifyStatus(test: DoctorUnits, status: boolean) {

        this.notifyService.confirm(`You want to ${status ? 'Activate' : 'Deactivate'} this unit name?`, () => {
            const request = {
                modifiedBy: this.page.userAccount.accountId,
                active: status,
                doctorUnitMasterId: test.doctorUnitMasterId,
                modifiedByName: this.page.userAccount.fullName,
                createdByRole: this.page.userAccount.roleName,
                loginRoleId: this.page.userAccount.roleId,
                unitName: test.unitName
            };

            this.httpService.post(ApiResources.getURI(ApiResources.doctorUnit.base, ApiResources.doctorUnit.modifyStatus), request)
                .pipe(takeUntil(this.page.unSubscribe))
                .pipe(finalize(() => { this.loading = false }))
                .subscribe((response: number) => {
                    if (response > 0) {
                        this.notifyService.successToast(`${status ? 'Activated' : 'Deactivated'} successfully.`);
                    }
                    this.fetchAll();
                }, (error: HttpErrorResponse) => {
                    this.notifyService.errorToast(error.error);
                });
        });
    }
    fetchFilterUnitNames(locationId: number) {
        this.loadingUnitNames = true;
        this.resourceService.doctorUnit(locationId)
            .pipe(finalize(() => { this.loadingUnitNames = false }))
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: Array<IResource>) => {
                this.filterUnitName = response;
            });
    }

    private fetchAll() {
        this.loading = true;
        const request = {
            ...this.filters.options
        };
        this.httpService.post(ApiResources.getURI(ApiResources.doctorUnit.base, ApiResources.doctorUnit.fetch), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loading = false))
            .subscribe((response: Array<DoctorUnits>) => {
                this.records = response;
                (error: HttpErrorResponse) => {
                    const errorMessage = UtilHelper.handleError(error);
                    if (errorMessage) {
                        this.notifyService.warningToast(errorMessage);
                    } else {
                        this.notifyService.defaultError();
                    }
                }
            });
    
    }
    ngOnInit() {
        this.appData.userAccount
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((userAccount: IUserAccount) => {
                if (userAccount) {
                    this.page.userAccount = userAccount;
                    this.currenrLocation = userAccount.locationId;
                    this.fetchLocations();
                    this.fetchAll();
                    this.fetchFilterUnitNames(null);
                } else {
                    this.page.userAccount = undefined;
                }
            });
    }

    ngOnDestroy() {
        this.onCloseModal();
        this.page.unsubscribeAll();
    }
}