import { HttpErrorResponse } from "@angular/common/http";
import { Component, OnDestroy, OnInit, TemplateRef, ViewChild } from "@angular/core";
import { FormBuilder, FormGroup, Validators, FormControl, FormArray } from "@angular/forms";
import { Router, ActivatedRoute, Params } from "@angular/router";
import { NgbModal, NgbModalRef, NgbDateStruct, NgbCalendar, NgbDate } from "@ng-bootstrap/ng-bootstrap";
import { Admission, Patient, PatientFamily, MedicationInfo, InsuranceAdmission, PatientInsurance, BedManagement, Appointment, Setting, DoctorUnits } from "@shared/entities";
import { ApiResources, DateHelper, UtilHelper } from "@shared/helpers";
import { IResource, ISlot, IUserAccount, Page, Pagination, GenericResponse, GenericStatus, LookUpModel } from "@shared/models";
import { VideoLinkService, AppData, HttpService, NotifyService, ResourceService, MenuService, BillNotificationService } from "@shared/services";
import { Observable, of, Subject } from "rxjs";
import { catchError, debounceTime, distinctUntilChanged, finalize, switchMap, takeUntil, tap } from "rxjs/operators";
import { DatePipe } from "@angular/common";
import { MenuType } from "../../../../../shared/enums";
import * as moment  from 'moment';
import { ProviderSpecialization } from "../../../../../shared/entities/provider-specialization.entity";
import { WhiteSpaceValidator } from "../../../../../shared/validators";
import { ICounsellingDetails } from "./local-helper";
import { AdmissionTransferRequest } from "../../../../../shared/entities/admission-transfer-request.entity";
//import { DomSanitizer } from "@angular/platform-browser";

class TrackBy {
    admission(item: Admission) {
        return item.admissionId;
    }

    resource(item: IResource) {
        return item.id;
    }
    doctorUnits(item: DoctorUnits) {
        return item.doctorUnitMasterId;
    }
}

class FilterOptions {
    providerId?: number = null;
    patientId?: number = null;
    locationId: number = null;
    patientMobile: string = null;
    admissionNo: string = null;
    fromDate: string = null;
    toDate: string = null;
    dischargeDate: string = null;
    isDischarged?: boolean = false;
    status?: boolean = null;
    umrNo: string = null;
    active?: boolean = true;
}

class Filters {
    options: FilterOptions;
    applied: boolean;

    constructor() {
        this.init();
    }

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

class Priority {
    id: number;
    name: string;
    icon: string;
    color: string;
}

@Component({
    templateUrl: "./view.html",
    styleUrls: ['./view.css']
})
export class AdmissionsViewPage implements OnInit, OnDestroy {
    @ViewChild("templatePatientAppointment", { static: true }) templatePatientAppointment: TemplateRef<any>;

    page: Page;
    today = DateHelper.ngbToday;
    minDate = DateHelper.minDate;

    priorities: Array<Priority>;
    filters: Filters;
    trackBy: TrackBy;
    pagination: Pagination;

    loading: boolean;
    admissions: Array<Admission>;
    @ViewChild("templateBookAdmission", {static: true}) templateBookAdmission: TemplateRef<any>;

    loadingPatients: boolean;
    patients: Array<IResource>;

    patient: Patient;
    selectedPatient: Patient;
    familyMembers: Array<PatientFamily>;
    department: Observable<Array<IResource>>;
    provider: Observable<Array<IResource>>;
    patientsInput = new Subject<string>();
    departmentsInput = new Subject<string>();
    providerInput = new Subject<string>();
    providersInput = new Subject<string>();
    spinners = false;
    meridian = false;
    maxAdmissionDate: string;

    loadingSurgeryTypes: boolean;
    loadingCountries: boolean;
    countries: Array<IResource>;

    loadingWards: boolean;
    loadingRooms: boolean;
    loadingBeds: boolean;
    loadingProviderLocations: boolean;
    loadingProviders: boolean;
    loadingDepartments: boolean;
    loadingRelationShips: boolean;
    providerLocations: Array<IResource>;
    providers: Array<IResource>;
    departments: Array<IResource>;
    surgeryTypes: Array<IResource>;
    relationships: Array<IResource>;
    wards: Array<BedManagement>;
    rooms: Array<BedManagement>;
    beds: Array<BedManagement>;
    selectedWard: BedManagement;
    selectedRoom: BedManagement;
    selectedBed: BedManagement;
    selectedBedManagement: BedManagement;
    visitors: Array<LookUpModel>;
    isVisitTypeloading: boolean;
    providerSpecialization: Array<ProviderSpecialization>
    modalRef: NgbModalRef;
    documentModalRef: NgbModalRef;
    loadingFamilyMember: boolean;
    submitting: boolean;
    submitted: boolean;
    modifying: boolean;
    modifyingContent: string;
    showWards = false;
    showRooms = false;
    showBeds = false;

    bookAdmissionForm: FormGroup;
    rescheduleAdmissionForm: FormGroup;
    selectedAdmission: Admission;
    loadingSlots: boolean;
    noOfSlots: number;
    morningSlots: Array<ISlot>;
    afternoonSlots: Array<ISlot>;
    eveningSlots: Array<ISlot>;
    nightSlots: Array<ISlot>;
    providerId: number;
    departmentId: number;
    admissionId: number;
    reason: string;
    resultsType = "today";
    minRequiredDate: NgbDateStruct;
    finalAmount: number;
    admissionNo: number;
    showSeriveOrder: boolean;
    showProgressReport: boolean;

    routingValue: string;
    urlPatientId: number;
    isPatientFilters = true;
    isShowInternalMedicine: boolean;
    isLoadingMedicationInfo: boolean;

    currentPopover: any;
    isFromAdmissions = true;
    isConvertedFromOPtoIp: boolean;
    insuranceApprovals: Array<InsuranceAdmission>;
    @ViewChild('patientInsurances', { static: false }) patientInsurancetemplate: TemplateRef<any>;
    @ViewChild('insuranceAdmission', { static: false }) insurancetemplate: TemplateRef<any>;
    tempTemplate: TemplateRef<any>;
    patientForm: FormGroup;
    formArrayIndex: number;
    message: string;
    loadingInsurances: boolean;
    insurances: Array<IResource>;
    tpa: Array<IResource>;
    insuranceCompanies: Array<IResource>;
    loadingCompanies: boolean;
    appointmentId: number;
    patientProviders: Array<IResource>;
    pid: any;
    fromOp: any;
    setMaxDate: NgbDate;
    setMinDate: NgbDate;
    dischargeDate: number;
    eDate: any;
    maxDischargeDate: any;
    minDatetoday = moment(new Date()).format('YYYY-MM-DD');
    checkLength: number;
    loadingPayTypes: boolean;
    payType: Array<IResource>;
    isSalucro: boolean;
    loadingSettings: boolean;
    loadingfutureAppointment: boolean;
    patientFutureAppointments: Array<Appointment>;
    loadingCaseTypes: boolean;
    loadingEmergencyCaseTypes: boolean;
    caseTypes: Array<IResource>;
    emergencyCaseTypes: Array<IResource>;
    loadingAdmissionPayTypes: boolean;
    admissionPayTypes: Array<IResource>;
    loadingchargeCategory: boolean;
    chargeCategory: Array<IResource>;
    loadingReferraldoctor: boolean;
    referraldoctors: Array<IResource>;
    yearsfordisplay: number;
    monthsfordisplay: number;
    daysfordisplay: number;
    filterPatient: Array<IResource>;
    surrogacyA: any;
    emergency: any;
    showDiv: boolean;
    trustee = ["Trustee", "Consultant", "Others"];
    councelled = ["Councelled", "Not Councelled"];
    bedAssoData: any;
    isCouncelled: string;
    selectedDoctorUnit: DoctorUnits;
    surrogacyValues: any;
    nRIDataDetailsValues: any;
    DoctorUnits: Array<DoctorUnits>
    loadingTpas: boolean;
    showEmergency = false;
    showSurrogacy = false;
    loadingDoctorUnits: boolean;
    chargeCategoryId: number;

    loadingPackages: boolean;
    packages: Array<IResource>;
    raiseBedChangeRequestForm: FormGroup;
    chargeCategories: Array<IResource>;
    loadingChargeCategories: boolean;
    umrNo: string;
    isAdmissionCancel: boolean;
    isAdmissionEdit: boolean;
    admissionCancelMinutes: number;
    admissionEditMinutes: number;

    counsellingFilter: Array<string>;
    loadingCounsellings: boolean;
    counsellingDetails: Array<ICounsellingDetails>;
    selectedCounsellingId: number;
    loadingCategories: boolean;
    categories: Array<IResource>;
    maxFiles = 3;
    files: Array<File>;
    raiseDoctorUnitRequestForm: FormGroup;
    logoBasics: Setting;
    isDoctorUnit: boolean;
    isShowTemplate: boolean;
    loadingLocationChargeTemplates: boolean;
    locationChargeTemplates: IResource[];
    chargeBillingCategoryId: number;

    constructor(
        private readonly route: ActivatedRoute,
        private readonly httpService: HttpService,
        private readonly resourceService: ResourceService,
        private readonly modalService: NgbModal,
        private readonly notifyService: NotifyService,
        private readonly formBuilder: FormBuilder,
        private readonly appData: AppData,
        private readonly router: Router,
        public readonly videoLinkService: VideoLinkService,
        private readonly calendar: NgbCalendar,
        private readonly menuService: MenuService,
        private readonly datePipe: DatePipe,
        private readonly billNotificationService: BillNotificationService
        //private sanitizer: DomSanitizer
    ) {
        this.showSeriveOrder = this.menuService.menus(MenuType.SubMenu, "Services & Payments").length > 0;
        this.showProgressReport = this.menuService.menus(MenuType.SubMenu, "Progress Report").length > 0;
        this.isShowInternalMedicine = this.menuService.menus(MenuType.SubMenu, "Internal Medicine").length > 0;
        this.counsellingFilter = new Array<string>();
        this.counsellingDetails = new Array<ICounsellingDetails>();

        this.priorities = new Array<Priority>();
        this.loading = true;
        this.isLoadingMedicationInfo = true;

        this.page = new Page();
        this.filters = new Filters();
        this.trackBy = new TrackBy();

        this.minRequiredDate = this.calendar.getToday();
        this.insuranceApprovals = new Array<InsuranceAdmission>();
        this.insurances = new Array<IResource>();
        this.tpa = new Array<IResource>();
        this.insuranceCompanies = new Array<IResource>();
        this.departments = new Array<IResource>();
        this.patients = new Array<IResource>();
        this.initPagination();
        this.DoctorUnits = new Array<DoctorUnits>();
        this.selectedDoctorUnit = new DoctorUnits();
        this.admissions = new Array<Admission>();
        this.packages = new Array<IResource>();
        this.patient = new Patient();
        this.locationChargeTemplates = new Array<IResource>();
    }

    safe = (url: any) => {
        if (url) {
            return `${ApiResources.getURI(ApiResources.resources.base, ApiResources.resources.getProfileImage)}?imagePath=${url}`;
        }
    }


    private initPagination() {
        this.pagination = new Pagination();
        this.pagination.pageSize = 10;
        this.pagination.pageIndex = 1;
    }
    private fetchCategories() {
        this.loadingCategories = true;
        this.resourceService.documentCategories()
            .pipe(finalize(() => { this.loadingCategories = false }))
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: Array<IResource>) => {
                this.categories = response;
            });
    }
    onOpenDocumentModal(content: TemplateRef<any>) {
        this.documentModalRef = this.modalService.open(content, {
            keyboard: false,
            centered: true,
            size: "lg",
            windowClass: "custom-modal effect-scale",
            backdrop: "static"
        });
    }
    onCloseDocumentModel() {
        try {
            this.documentModalRef.close();
            this.documentModalRef = undefined;
        } catch (e) {
            // ignored;
        }
    }
    onFileSelect(files: Array<File>) {
        this.files = files;
    }
    private buildBookAdmissionForm() {
        function adjust(val) {
            if (val > 9) {
                return val.toString();
            } else {
                return '0' + val.toString();
            }
        }

        const today = new Date();
        const date = today.getFullYear() + '-' + adjust(today.getMonth() + 1) + '-' + adjust(today.getDate());
        const time = adjust(today.getHours()) + ":" + adjust(today.getMinutes());
        const dateTimeNow = `${date}T${time}`;
        this.maxAdmissionDate = `${date}T${time}`;

        const counsellingCodeControl = new FormControl(null);
        this.bookAdmissionForm = this.formBuilder.group({
            admissionId: [0],
            counsellingCode: counsellingCodeControl,
            admissionNo: [null],
            providerId: [null, [Validators.required]],
            patientId: [null, [Validators.required]],
            patientFamilyId: [null],
            doctorUnitMasterId: [null, [Validators.required]],
            departmentId: [null, [Validators.required]],
            //patientType: ["I", [Validators.required]],
            surgeryTypeId: [null],
            roomId: [null],
            bedId: [null, [Validators.required]],
            wardId: [null],
            isMaternity: [null],
            isDischarged: [false],
            admissionDate: [dateTimeNow, [Validators.required]],
            admissionTime: [null],
            admissionTimeString: [null],
            admissionNotes: [null],
            attendantName: [null],
            attendantContactNo: [null],
            attendantRelationWithPatient: [null],
            createdBy: [this.page.userAccount.accountId, [Validators.required]],
            modifiedBy: [null],
            logFrom: [this.page.userAccount.roleId],
            visitTypeId: [null, [Validators.required]],
            patientPriorityId: [null],
            breakfast: [null],
            lunch: [null],
            dinner: [null],
            providerName: [null],
            admissionPayTypeId: [null, [Validators.required]],
            paymentNumber: [null],
            paymentStatus: [null],
            caseTypeId: [null, [Validators.required]],
            insuranceCompanyId: [null, [Validators.required]],
            tpaId: [null, [Validators.required]],
            patientOrganization: [null, [Validators.required]],
            chargeCategoryId: [null],
            chargeBillingCategoryId:[null],
            referralDoctorId: [null, [Validators.required]],
            packageModuleId: null,
            admissionPackageId: null,
            documentName: null,
            documentType: null,
            description: null,
            chargeModuleTemplateId:[null],
            nriData: this.formBuilder.group({
                isNri: [null], memberIdcardNo: [null], unit: [null], policyNo: [null], cardHolder: [null], serviceNo: [null], refDate: [null], rank: [null], refSerialNo: [null], insuranceCode: [null], organisation: [null], insuranceCo: [null], panCardNo: [null], passportNo: [null], ppAddress: [null], phoneNo: [null], ppIssuePlace: [null], afterDischarge: [null]
            }),
            bedAssociatedData: this.formBuilder.group({
                packageName: [null], diagnosis: [null], approxCost: [null], email: [null], patientAddress: [null], trusteeRadiobtn: [null], trustee: [null], relation: [null], recommended: [null], criticalDr: [null], coConsultantdr: [null], councelled: [null]
            }),
            emergencyInfo: this.formBuilder.group({
                emergencyContactNo: [null], emergencyTypeId: [null]
            }, { optional: true }),
            surrogacyData: this.formBuilder.group({
                geneticMotherName: [null], age: [null], geneticFatherName: [null], address: [null],
                phoneNo: [null], bloodGroup: [null], rhType: [null], fromDate: [null], toDate: [null]
            }, { optional: true })
        });

        counsellingCodeControl.valueChanges.subscribe(code => {
            const counselling = this.counsellingDetails.find(x => x.counsellingNo === code);
            if (counselling) {
                this.onSelectPayType(this.admissionPayTypes);

                this.selectedCounsellingId = counselling.counsellingId;
                const chargeCategoryId = counselling.chargeCategoryId ? counselling.chargeCategoryId : null;
                const doctorUnit = this.DoctorUnits.length ? this.DoctorUnits[0].doctorUnitMasterId : null;
                this.selectedDoctorUnit = this.DoctorUnits[0];
                const providerId = this.DoctorUnits[0].tagDoctor[0].providerId;

                this.bookAdmissionForm.patchValue({
                    patientId: counselling.patientId,
                    caseTypeId: this.caseTypes.length ? (this.caseTypes[0].id || null) : null,
                    referralDoctorId: this.referraldoctors.length ? this.referraldoctors[0].id : null,
                    admissionPayTypeId: counselling.payTypeId ? counselling.payTypeId : null,
                    insuranceCompanyId: counselling.insuranceCompanyId ? counselling.insuranceCompanyId : null,
                    tpaId: counselling.tpaId ? counselling.tpaId : null,
                    patientOrganization: counselling.patientOrganization || null,
                    chargeCategoryId: chargeCategoryId,
                    doctorUnitMasterId: doctorUnit,
                    providerId: providerId
                }, { emitEvent: false });

                const foundPayType = this.admissionPayTypes.find(x => x.id === counselling.payTypeId);
                const payTypeName = foundPayType
                    ? foundPayType.name
                    : '';

                this.fetchPackages(payTypeName, () => {
                    this.bookAdmissionForm.patchValue({
                        packageModuleId: counselling.packageModuleId ? counselling.packageModuleId : null,
                    }, { emitEvent: false })
                });

                this.chargeCategoryId = chargeCategoryId;
                this.fetchBeds(() => {
                    const availableBed = this.beds.find(x => x.bedStatusName === 'Available');
                    if (availableBed) {
                        this.selectBed(availableBed);
                    }
                })

                this.fetchDepartments(providerId, () => {
                    const departmentId = this.departments.length ? this.departments[0].id : null;
                    this.bookAdmissionForm.patchValue({
                        departmentId: departmentId,
                    }, { emitEvent: false });
                });
            }

        })

        this.bookAdmissionForm.get("providerId").valueChanges.subscribe((id: number) => {
            //this.providerId = id;
            this.bookAdmissionForm.patchValue({
                departmentId: null
            });
            this.fetchDepartments(id);
        });
        this.bookAdmissionForm.get("caseTypeId").valueChanges.subscribe((id: number) => {
            const findPatient = this.caseTypes.find(m => m.id === id);
            if (findPatient.value == 'emergency') {
                this.showEmergency = true;
            }
            else {
                this.showEmergency = false;
            }
            if (findPatient.value == 'Surrogacy') {
                this.showSurrogacy = true;
            }
            else {
                this.showSurrogacy = false;
            }
        });
        //this.bookAdmissionForm.get("departmentId").valueChanges.subscribe((id: number) => {
        //    this.fetchProviders(id);
        //});

        this.bookAdmissionForm.get("patientId").valueChanges.subscribe((id: number) => {
            if (id) {
                this.findPatient(id)
            } else {
                this.patient = null;
            }
        });
        this.bookAdmissionForm.get("doctorUnitMasterId").valueChanges.subscribe((id: number) => {
            if (id) {
                this.selectedDoctorUnit = this.DoctorUnits.find(x => x.doctorUnitMasterId === id);
                this.bookAdmissionForm.patchValue({
                    providerId: this.selectedDoctorUnit.tagDoctor[0].providerId
                });
            }
            else {
                this.selectedDoctorUnit = null;
                this.bookAdmissionForm.patchValue({
                    providerId: null
                });
            }


        });

        if (!this.providerId === null) {
            this.bookAdmissionForm.get("providerId").setValue(this.providerId);
        }
    }
    private buildUpdateBookAdmissionForm(admissionItem: Admission) {
        if (admissionItem.admissionPayTypeId > 0) {
            const selectedPayType = this.admissionPayTypes.find(m => m.id === admissionItem.admissionPayTypeId);
            this.fetchPackages(selectedPayType.name);
        }
        let surrogacyDetailsPatch = {};
        if (admissionItem.surrogacyData != null) {
            this.surrogacyValues = admissionItem.surrogacyData;
            const surrogacyDetails = JSON.parse(this.surrogacyValues);
            surrogacyDetailsPatch = {
                geneticMotherName: surrogacyDetails.geneticMotherName,
                age: surrogacyDetails.age,
                geneticFatherName: surrogacyDetails.geneticFatherName,
                address: surrogacyDetails.addressfetc,
                phoneNo: surrogacyDetails.phoneNo,
                bloodGroup: surrogacyDetails.bloodGroup,
                rhType: surrogacyDetails.rhType,
                fromDate: surrogacyDetails.fromDate,
                toDate: surrogacyDetails.toDate
            }
        }
        else {
            surrogacyDetailsPatch = {
                geneticMotherName: null, age: null, geneticFatherName: null, address: null, phoneNo: null, bloodGroup: null, rhType: null, fromDate: null, toDate: null
            }
        }

        let bedData = {};
        if (admissionItem.bedAssociatedData != null) {
            this.bedAssoData = JSON.parse(admissionItem.bedAssociatedData);
            bedData = {
                diagnosis: this.bedAssoData.diagnosis,
                packageName: this.bedAssoData.packageName,
                approxCost: this.bedAssoData.approxCost,
                coConsultantdr: this.bedAssoData.coConsultantdr,
                criticalDr: this.bedAssoData.criticalDr,
                email: this.bedAssoData.email,
                patientAddress: this.bedAssoData.patientAddress,
                recommended: this.bedAssoData.recommended,
                relation: this.bedAssoData.relation,
                trustee: this.bedAssoData.trustee,
                trusteeRadiobtn: this.bedAssoData.trusteeRadiobtn,
                councelled: this.bedAssoData.councelled
            }
        }
        else {
            bedData = {
                packageName: [null], diagnosis: [null], approxCost: [null], email: [null], patientAddress: [null], trusteeRadiobtn: [null], trustee: [null], relation: [null], recommended: [null], criticalDr: [null], coConsultantdr: [null], councelled: [null]
            }
        }

        let NRIDataDetailsPatch = {};
        if (admissionItem.nriData != null) {
            this.nRIDataDetailsValues = admissionItem.nriData;
            const NRIDataDetails = JSON.parse(this.nRIDataDetailsValues);
            NRIDataDetailsPatch = {
                isNri: NRIDataDetails.isNri,
                memberIdcardNo: NRIDataDetails.memberIdcardNo,
                unit: NRIDataDetails.unit,
                policyNo: NRIDataDetails.policyNo,
                cardHolder: NRIDataDetails.cardHolder,
                serviceNo: NRIDataDetails.serviceNo,
                refDate: NRIDataDetails.refDate,
                rank: NRIDataDetails.rank,
                refSerialNo: NRIDataDetails.refSerialNo,
                insuranceCode: NRIDataDetails.insuranceCode,
                organisation: NRIDataDetails.organisation,
                insuranceCo: NRIDataDetails.insuranceCo,
                panCardNo: NRIDataDetails.panCardNo,
                passportNo: NRIDataDetails.passportNo,
                ppAddress: NRIDataDetails.ppAddress,
                phoneNo: NRIDataDetails.phoneNo,
                ppIssuePlace: NRIDataDetails.ppIssuePlace,
                afterDischarge: NRIDataDetails.afterDischarge,

            }

        } else {
            NRIDataDetailsPatch = {
                isNri: null, memberIdcardNo: null, unit: null, policyNo: null, cardHolder: null, serviceNo: null, refDate: null, rank: null, refSerialNo: null, insuranceCode: null, organisation: null, insuranceCo: null, panCardNo: null, passportNo: null, ppAddress: null, phoneNo: null, ppIssuePlace: null, afterDischarge: null,
            }
        }

        let emergencyDetailsPatch = {};
        if (admissionItem.emergencyInfo != null) {
            this.emergency = admissionItem.emergencyInfo;
            const emergencyDetails = JSON.parse(this.emergency);
            emergencyDetailsPatch = {
                emergencyContactNo: emergencyDetails.emergencyContactNo,
                emergencyTypeId: emergencyDetails.emergencyTypeId
            }

        }
        else {
            emergencyDetailsPatch = {
                emergencyContactNo: null,
                emergencyTypeId: null
            }
        }
        this.bookAdmissionForm.patchValue({
            doctorUnitMasterId: admissionItem.doctorUnitMasterId,
            admissionId: admissionItem.admissionId,
            admissionNo: admissionItem.admissionNo,
            providerId: admissionItem.providerId,
            patientId: admissionItem.patientId,
            patientFamilyId: admissionItem.patientFamilyId,
            departmentId: admissionItem.departmentId,
            //patientType: admissionItem.patientType,
            surgeryTypeId: admissionItem.surgeryTypeId,
            roomId: admissionItem.roomId,
            bedId: admissionItem.bedId,
            wardId: admissionItem.wardId,
            isMaternity: admissionItem.isMaternity,
            isDischarged: admissionItem.isDischarged,
            admissionDate: admissionItem.admissionDate + ".000",
            admissionTime: admissionItem.admissionTime,
            admissionTimeString: admissionItem.admissionTimeString,
            admissionNotes: admissionItem.admissionNotes,
            attendantName: admissionItem.attendantName,
            attendantContactNo: admissionItem.attendantContactNo,
            attendantRelationWithPatient: admissionItem.attendantRelationWithPatient,
            createdBy: admissionItem.createdBy,
            modifiedBy: this.page.userAccount.accountId,
            logFrom: this.page.userAccount.roleId,
            visitTypeId: admissionItem.visitTypeId,
            patientPriorityId: admissionItem.patientPriorityId,
            providerName: admissionItem.providerName,
            surrogacyData: surrogacyDetailsPatch,
            nriData: NRIDataDetailsPatch,
            bedAssociatedData: bedData,
            emergencyInfo: emergencyDetailsPatch,
            referralDoctorId: admissionItem.referralDoctorId,
            caseTypeId: admissionItem.caseTypeId,
            admissionPayTypeId: admissionItem.admissionPayTypeId,
            insuranceCompanyId: admissionItem.insuranceCompanyId,
            tpaId: admissionItem.tpaId,
            patientOrganization: admissionItem.patientOrganization,
            packageModuleId: admissionItem.packageModuleId,
            admissionPackageId: admissionItem.admissionPackageId,
            //breakfast: admissionItem.breakfast,
            //lunch: admissionItem.lunch,
            //dinner: admissionItem.dinner
        });

        const bedManagementInfo = new BedManagement;
        bedManagementInfo.wardId = admissionItem.wardId;
        bedManagementInfo.wardName = admissionItem.wardName;
        bedManagementInfo.roomId = admissionItem.roomId;
        bedManagementInfo.roomName = admissionItem.roomName;
        bedManagementInfo.bedId = admissionItem.bedId;
        bedManagementInfo.bedNumber = admissionItem.bedNumber;

        this.selectedBed = new BedManagement;
        this.selectedRoom = new BedManagement;
        this.selectedWard = new BedManagement;
        this.selectedBedManagement = new BedManagement;

        this.selectedBedManagement = bedManagementInfo;
        this.selectedBed = bedManagementInfo;
        this.selectedRoom = bedManagementInfo;
        this.selectedWard = bedManagementInfo;
    }
    handleChange(event) {
        this.isCouncelled = event;
    }
    get forms() {
        return {
            bookAdmission: this.bookAdmissionForm ? this.bookAdmissionForm.controls : {},
            bedRequestChange: this.raiseBedChangeRequestForm ? this.raiseBedChangeRequestForm.controls : {},
            doctorUnitChange: this.raiseDoctorUnitRequestForm ? this.raiseDoctorUnitRequestForm.controls : {},
        }
    }

    private fetch(ids: Array<number>) {
        this.httpService
            .post(ApiResources.getURI(ApiResources.serviceOrder.base, ApiResources.serviceOrder.fetchAdmission), { admissionIds: ids })
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loading = false))
            .subscribe(
                (response: any) => {
                    (response as Array<any>).forEach(item => {
                        const found = this.admissions.find(x => x.admissionId === item.admissionId);
                        //if (found.length > 1) {
                        //    this.checkLength = found.length;
                        //}
                        found.serviceOrder = item.count;
                    });
                },
            );
    }


    private fetchAdmissions() {
        const request = Object.assign(UtilHelper.clone(this.filters.options), UtilHelper.clone(this.pagination));
        request.locationId = this.page.userAccount.locationId;
        //if (this.resultsType === "today") {
        //    request["fromDate"] = moment().format("YYYY-MM-DD");
        //    request["toDate"] = moment().format("YYYY-MM-DD");
        //}
        if (this.urlPatientId && this.urlPatientId > 0) {
            request.patientId = this.urlPatientId;
            request.isDischarged = null;
        }

        if (this.page.userAccount.roleId === 3) {
            request.providerId = this.page.userAccount.referenceId;
        }

        this.httpService
            .post<Array<Admission>>(ApiResources.getURI(ApiResources.admissions.base, ApiResources.admissions.fetch), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loading = false))
            .subscribe(
                (response: Array<Admission>) => {
                    this.admissions = response;
                    this.fetchMedicationInfo(response.map(x => x.admissionId));
                    this.fetch(response.map(x => x.admissionId));
                    this.admissions.forEach((item: Admission) => {
                        //item["newPatientThumbnailUrl"] = item.patientThumbnailUrl ? this.safe(item.patientThumbnailUrl) : null;
                        //item["newproviderThumbnailUrl"] = item.providerThumbnailUrl ? this.safe(item.providerThumbnailUrl) : null;
                        this.admissions = response;
                        if (item.isDischarged) {
                            item.dischargeTimeString =
                                DateHelper.getTimeFromTicks(item.dischargeTime["value"]["ticks"]);
                            item.dischargeDate =
                                new Date(item.dischargeDate.toString().replace("T00:00:00", item.dischargeTimeString));
                        }

                        if (item.expectedDischargeDate) {
                            item.expectedDischargeDateView = this.datePipe.transform(new Date(item.expectedDischargeDate), 'yyyy-MM-dd');
                        }
                        UtilHelper.applyPagination(this.admissions, this.pagination);
                    });

                },
                () => {
                    this.admissions = [];
                }
            );
    }

    private fetchMedicationInfo(ids: Array<number>) {
        this.httpService
            .post(ApiResources.getURI(ApiResources.progressReport.base, ApiResources.progressReport.fetchMedicationInfo),
                { admissionIds: ids })
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.isLoadingMedicationInfo = false))
            .subscribe(
                (response?: GenericResponse) => {
                    if (response.data) {
                        (response.data as Array<MedicationInfo>).forEach(item => {
                            const found = this.admissions.find(x => x.admissionId === item.admissionId);
                            found.medicationInfo = item;
                        });
                    }

                },
                () => { }
            );
    }


    private findPatient(patientId: number) {

        this.patient = undefined;
        const findPatient = this.patients.find(m => m.id === patientId);
        this.httpService
            .post<Patient>(ApiResources.getURI(ApiResources.patients.base, ApiResources.patients.find), { encryptedPatientId: findPatient.encryptedId })
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loading = false))
            .subscribe(
                (response: Patient) => {
                    this.patient = response;
                    this.selectedPatient = response;
                    this.billNotificationService.get(patientId);
                    const dateOfBirth = DateHelper.toNgbDateStruct(String(this.patient.dateOfBirth));
                    if (dateOfBirth != null) {
                        const mdob = moment(String(this.patient.dateOfBirth), "YYYY-MM-DD");
                        const age = moment().diff(mdob, "months");
                        const yrs = (age / 12).toFixed(1);
                        this.yearsfordisplay = parseInt(yrs, 10);

                        const months = age % 12;
                        const days = moment().diff(mdob.add(yrs, 'years'), 'days', false);
                        this.yearsfordisplay = days;
                        this.yearsfordisplay = parseInt(yrs);
                        this.monthsfordisplay = months;
                        const date1 = moment(String(this.patient.dateOfBirth), "YYYY-MM-DD");
                        const monthsa = moment().diff(date1, 'months');
                        date1.add(monthsa, 'months');
                        const daysa = moment().diff(date1, 'days');
                        monthsa + ' ' + 'Month(s)' + ' ' + daysa + " Day(s)"
                        this.daysfordisplay = daysa;
                        this.patient.age = this.patient.dateOfBirth ? this.yearsfordisplay + 'Y ' + this.monthsfordisplay + 'M ' + this.daysfordisplay + 'D' : null;
                    }
                    if (this.fromOp === "fromAppointments") {
                        this.bookAdmissionForm.patchValue({
                            providerName: this.patient.providerName,
                            providerId: this.patient.providerId,
                            departmentId: this.patient.departmentId
                        })
                    }
                    if (this.bookAdmissionForm.value["admissionId"] === 0 && this.patient && this.patient.admissionId !== null && this.patient.isDischarged === false) {
                        this.bookAdmissionForm.controls.patientId.setErrors({ 'incorrect': true });
                        //this.notifyService.warning("This Patient already has admission & not discharged!");
                    }

                    this.bookAdmissionForm.patchValue({
                        breakfast: this.datePipe.transform(new Date(0, 0, 0, this.patient.breakfastTime.hour, this.patient.breakfastTime.minute), 'HH:mm'),
                        lunch: this.datePipe.transform(new Date(0, 0, 0, this.patient.lunchTime.hour, this.patient.lunchTime.minute), 'HH:mm'),
                        dinner: this.datePipe.transform(new Date(0, 0, 0, this.patient.dinnerTime.hour, this.patient.dinnerTime.minute), 'HH:mm')
                    })

                },
                //this.bookAdmissionForm.get("patientId").reset();
                () => {
                    this.patient = null;
                }
            );
    }

    private buildInsuranceForm(insurance?: PatientInsurance) {
        return this.formBuilder.group({
            patientInsuranceId: insurance && insurance.patientInsuranceId ? insurance.patientInsuranceId : 0,
            patientId: insurance ? insurance.patientId : 0,
            insuranceTypeId: [insurance ? insurance.insuranceTypeId : null, [Validators.required]],
            insuranceCompanyId: [insurance ? insurance.insuranceCompanyId : null, [Validators.required]],
            validity: [insurance ? insurance.validity : null, [Validators.required]],
            cardNo: [insurance ? insurance.cardNo : null, [Validators.required]],
            createdBy: this.page.userAccount.accountId
        });
    }

    private fetchInsurances() {
        this.loadingInsurances = true;
        this.resourceService.insuranceCompanies()
            .pipe(finalize(() => { this.loadingInsurances = false }))
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: Array<IResource>) => {
                this.insurances = response;
                if (this.insurances.length > 0 && this.locationChargeTemplates && this.locationChargeTemplates.length > 0) {
                    this.insurances = this.insurances.filter((obj2) =>
                        this.locationChargeTemplates.some((obj1) => obj1.optionalData === obj2.id)
                    );
                }

            });
    }
    private fetchChargeCategory() {
        this.loadingchargeCategory = true;
        this.resourceService.chargeCategory()
            .pipe(finalize(() => { this.loadingchargeCategory = false }))
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: Array<IResource>) => {
                this.chargeCategory = response;
            });
    }
    onChangeCharge(record: Array<IResource>) {
        const charge = this.bookAdmissionForm.get("chargeCategoryId").value;
        const selectedCharge = record.find(x => x.id == charge);
        console.log(selectedCharge);
        this.chargeCategoryId = charge
        if (charge != 0 || charge != undefined || charge == null) {
            if (!this.bookAdmissionForm.value) {
                return this.notifyService.warningToast("Please select Charge Template");
            }
            this.fetchBeds();
            // this.fetchRooms(null, charge);
        }
        else {
            this.fetchWards();
        }
    }

    onChangeChargeBilling(record: Array<IResource>) {
        const charge = this.bookAdmissionForm.get("chargeBillingCategoryId").value;
        const selectedCharge = record.find(x => x.id == charge);
        console.log(selectedCharge);
        const selectedChargeCategoryId = this.beds.find(x => x.chargeCategoryId == charge)
        this.chargeBillingCategoryId = charge
        this.selectedBed = selectedChargeCategoryId;
        this.selectedBedManagement = selectedChargeCategoryId;
        this.selectedBedManagement.wardId = selectedChargeCategoryId.wardId;
        this.selectedBedManagement.wardName = selectedChargeCategoryId.wardName;
        this.selectedBedManagement.roomId = selectedChargeCategoryId.roomId;
        this.selectedBedManagement.roomName = selectedChargeCategoryId.roomName;
        this.selectedBedManagement.roomRent = selectedChargeCategoryId.roomRent;
        this.bookAdmissionForm.patchValue({
            bedId: selectedChargeCategoryId.bedId
        });
    }

    wardsData() {
        this.fetchWards();
    }
    onChange(value: any, index: number) {
        const records = this.insuranceFormArray.getRawValue();
        const data = this.insuranceFormArray.controls[index];
        if (records.length > 1) {
            if ((records.filter(x => x.insuranceCompanyId === value).length) > 1) {
                data.patchValue({
                    insuranceCompanyId: null
                })
                this.message = "Given Insurance has already been selected";
                this.formArrayIndex = index;
            } else {

                this.message = null;
                this.formArrayIndex = null;
            }
        }
    }

    get insuranceFormArray() { return this.patientForm.controls["insurances"] as FormArray }

    buildInsurancesForm() {
        this.patientForm = this.formBuilder.group({
            insurances: this.formBuilder.array([])
        });
        this.onAddInsurance();
    }

    get insuranceForm() {
        return this.insuranceFormArray;
    }

    onAddInsurance() {
        const formArray = this.insuranceFormArray as FormArray;
        if (formArray.length <= 3) {
            /*const company = this.insurances.find(m => Number(m.optionalText) == Number(this.insuranceForm.get('insuranceCompanyId').value));*/
            const formItem = this.buildInsuranceForm({ insuranceTypeId: formArray.length + 1, patientId: this.selectedAdmission.patientId } as PatientInsurance);
            this.insuranceFormArray.push(formItem);
        }
    }

    onRemoveInsurance(index: number) {
        this.insuranceFormArray.removeAt(index);
    }

    //fetchPatientProviders(id: number) {
    //    this.loadingProviders = true;
    //    this.resourceService.patientAppointmentDoctorOnly(id)
    //        .pipe(finalize(() => { this.loadingProviders = false }))
    //        .pipe(takeUntil(this.page.unSubscribe))
    //        .subscribe((response: Array<IResource>) => {
    //            this.providers = response;
    //            this.checkDoctor();
    //        });
    //}

    //patchvalue() {
    //    if (this.patientProviders.length === 1) {
    //        this.bookAdmissionForm.patchValue({
    //            providerName: this.providers[0].value,
    //            providerId: this.providers[0].id
    //        });
    //    }
    //}

    //onProviderSelect(provider?: IResource) {
    //    if (provider) {
    //        this.bookAdmissionForm.patchValue({
    //            providerId: provider.id
    //        });
    //    } else {
    //        this.bookAdmissionForm.patchValue({
    //            providerId: null
    //        });
    //    }
    //}

    fetchInsuranceApprovals(admissionId: number) {
        this.loading = true;

        this.httpService.post(ApiResources.getURI(ApiResources.insuranceAdmission.base, ApiResources.insuranceAdmission.fetchInsuranceApprovals), { admissionId: admissionId, appointmentId: null })
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => { this.loading = false }))
            .subscribe((response: Array<InsuranceAdmission>) => {
                if (response != null) {
                    this.insuranceApprovals = response;
                } else {
                    this.insuranceApprovals = new Array<InsuranceAdmission>();
                }
            }, () => {
                this.notifyService.defaultErrorToast();
            });
    }

    onOpenInsuranceModel(template: TemplateRef<any>, admission: Admission) {
        this.tempTemplate = template;
        this.selectedAdmission = admission;
        this.buildInsuranceForm();
        this.fetchPatientInsurances(this.selectedAdmission.admissionId);
    }

    onOpen(template: TemplateRef<any>) {
        this.modalRef = this.modalService.open(template, {
            backdrop: "static",
            keyboard: false,
            centered: true,
            size: "lg",
            windowClass: "custom-modal effect-scale"
        });
    }

    getMinDate() {
        const date = this.filters.options.fromDate.split("-");
        const year = Number(date[0]);
        const month = Number(date[1]);
        const day = Number(date[2]);
        this.setMinDate = new NgbDate(year, month, day);
    }

    getMaxDate() {
        const date = this.filters.options.toDate.split("-");
        const year = Number(date[0]);
        const month = Number(date[1]);
        const day = Number(date[2]);
        this.setMaxDate = new NgbDate(year, month, day);
    }

    //private fetchFamilyMember(patientId: number) {
    //    const request = {
    //        patientId: patientId
    //    }

    //    this.loadingFamilyMember = true;
    //    this.httpService
    //        .post<Array<PatientFamily>>(ApiResources.getURI(ApiResources.patients.base, ApiResources.patients.fetchFamilyMembers), request)
    //        .pipe(takeUntil(this.page.unSubscribe))
    //        .pipe(finalize(() => { this.loadingFamilyMember = false }))
    //        .subscribe(
    //            (response: Array<PatientFamily>) => {
    //                this.familyMembers = response;
    //            },
    //            () => {
    //                this.familyMembers = new Array();
    //            }
    //        );
    //}

    //fetchProviders(departmentId?: number) {
    //    this.loadingProviders = true;
    //    this.resourceService.providers(departmentId)
    //        .pipe(finalize(() => { this.loadingProviders = false }))
    //        .pipe(takeUntil(this.page.unSubscribe))
    //        .subscribe((response: Array<IResource>) => {
    //            this.providers = response;
    //            this.providerId = this.providers && this.providers.length ? this.providers[0].id : null;
    //            this.fetchDepartments(this.providerId);
    //            this.bookAdmissionForm.patchValue({
    //                providerId: this.providerId
    //            });
    //        });
    //}


    //private fetchAdmissionProviders(departmentId?: number) {
    //    this.loadingProviders = true;
    //    this.resourceService.admissionProviders(departmentId)
    //        .pipe(finalize(() => { this.loadingProviders = false }))
    //        .pipe(takeUntil(this.page.unSubscribe))
    //        .subscribe((response: Array<IResource>) => {
    //            this.providers = response;
    //            this.providerId = this.providers && this.providers.length ? this.providers[0].id : null;
    //            this.fetchDepartments(this.providerId);
    //            //this.bookAdmissionForm.patchValue({
    //            //    providerId: this.providerId
    //            //})
    //        });
    //}
    //private getSettingsData() {
    //    this.loadingSettings = true;
    //    this.httpService.get<Array<Setting>>(ApiResources.getURI(ApiResources.setting.base, ApiResources.setting.fetch), { name: "Salucro" })
    //        .pipe(takeUntil(this.page.unSubscribe))
    //        .pipe(finalize(() => this.loadingSettings = false))
    //        .subscribe((response: Array<Setting>) => {
    //            if (response.length > 0) {
    //                this.isSalucro = response[0].active;
    //            }
    //        });
    //    this.fetchPayTypes();
    //}

    //private fetchPayTypes() {
    //    this.loadingPayTypes = true;
    //    let salucro = this.isSalucro ? true : false;
    //    this.resourceService.payType(salucro)
    //        .pipe(finalize(() => { this.loadingPayTypes = false }))
    //        .pipe(takeUntil(this.page.unSubscribe))
    //        .subscribe((response: Array<IResource>) => {
    //            this.payType = response;
    //        });
    //}

    private getSettingsAdmissionCancel() {
        this.loadingSettings = true;
        this.httpService.get<Array<Setting>>(ApiResources.getURI(ApiResources.setting.base, ApiResources.setting.fetch), { name: "Admission to cancel in minutes" })
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loadingSettings = false))
            .subscribe((response: Array<Setting>) => {

                if (response.length > 0) {
                    this.isAdmissionCancel = response[0].active;
                    this.admissionCancelMinutes = +response[0].value;
                }
            });
    }

    private getSettingsAdmissionEdit() {
        this.loadingSettings = true;
        this.httpService.get<Array<Setting>>(ApiResources.getURI(ApiResources.setting.base, ApiResources.setting.fetch), { name: "Admission to edit in minutes" })
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loadingSettings = false))
            .subscribe((response: Array<Setting>) => {

                if (response.length > 0) {
                    this.isAdmissionEdit = response[0].active;
                    this.admissionEditMinutes = +response[0].value;
                }
            });
    }

    private fetchDepartments(providerId?: number, callback?: Function) {
        this.loadingDepartments = true;
        this.resourceService.departments(providerId)
            .pipe(finalize(() => { this.loadingDepartments = false }))
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: Array<IResource>) => {
                this.departments = response;
                this.departmentId = this.departments && this.departments.length ? this.departments[0].id : null;
                callback && callback();
                //this.bookAdmissionForm.patchValue({
                //    departmentId: this.departmentId
                //})
            });
    }

    fetchPriorities = () => {
        this.httpService
            .post<GenericResponse>(ApiResources.getURI(ApiResources.admissions.base, ApiResources.admissions.fetchPriorities), {})
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loadingWards = false))
            .subscribe(
                (response: GenericResponse) => {
                    if (GenericStatus[GenericStatus.Success] === response.status) {
                        this.priorities = response.data as Array<Priority>;
                    } else {
                        this.notifyService.defaultError();
                    }
                },
                () => {
                    this.priorities = [];
                }
            );
    }

    fetchCounsellingCodes = () => {
        this.httpService
            .post<GenericResponse>(ApiResources.getURI(ApiResources.counselling.base, ApiResources.counselling.fetchBasics), { type: "IP" })
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loadingCounsellings = false))
            .subscribe(
                (response: GenericResponse) => {
                    if (GenericStatus[GenericStatus.Success] === response.status) {
                        if (response.data.length > 0) {
                            this.counsellingDetails = response.data as Array<ICounsellingDetails>;
                            this.counsellingFilter = response.data.map(x => x.counsellingNo);
                        }

                    } else {
                        this.notifyService.defaultError();
                    }
                },
                () => {
                    this.counsellingDetails = [];
                }
            );
    }

    fetchSurgeryTypes() {
        this.loadingSurgeryTypes = true;
        this.resourceService.surgeryTypes()
            .pipe(finalize(() => { this.loadingSurgeryTypes = false }))
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: Array<IResource>) => {
                this.surgeryTypes = response;
            });
    }

    fetchRelationShips() {
        this.loadingRelationShips = true;
        this.resourceService.relationships()
            .pipe(finalize(() => { this.loadingRelationShips = false }))
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: Array<IResource>) => {
                this.relationships = response;
            });
    }

    changeAdmissionFor(patientFamilyId?: number) {
        const selectedFamilyMember = this.familyMembers.find(m => m.patientFamilyId === patientFamilyId);
        this.patient.age = selectedFamilyMember.age;
        this.patient.gender = selectedFamilyMember.relativeGender;
        this.patient.relationWithPatient = selectedFamilyMember.relation;
    }

    onChangeResultsType(type: string) {
        this.resultsType = type;
        this.initPagination();
        this.fetchAdmissions();
    }

    private fetchProvidersFilter() {
        this.provider = this.providerInput.pipe(
            debounceTime(500),
            distinctUntilChanged(),
            switchMap((term: string) =>
                term && term.length >= 2
                    ? this.resourceService.provider(term).pipe(
                        tap(() => this.loadingProviders = true),
                        catchError(() => { return of([]) }),
                        finalize(() => this.loadingProviders = false)
                    )
                    : of([])
            )
        );
    }

    private fetchPatients() {
        this.loadingPatients = true;
        this.resourceService.patientsAll()
            .pipe(finalize(() => { this.loadingPatients = false }))
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: Array<IResource>) => {
                this.patients = response;
            });
    }
    //private fetchPatients() {
    //    this.patients = this.patientsInput.pipe(
    //        debounceTime(500),
    //        distinctUntilChanged(),
    //        switchMap((term: string) =>
    //            term && term.length >= 2
    //                ? this.resourceService.patients(term).pipe(
    //                    tap(() => this.loadingPatients = true),
    //                    catchError(() => { return of([]) }),
    //                    finalize(() => this.loadingPatients = false)
    //                )
    //                : of([])
    //        )
    //    );
    //    console.log(this.patients);
    //}
    fetchWards() {
        this.loadingWards = true;

        this.showWards = true;
        this.showRooms = false;
        this.showBeds = false;

        this.selectedWard = undefined;
        this.selectedRoom = undefined;
        this.selectedBed = undefined;

        this.httpService
            .post<Array<BedManagement>>(ApiResources.getURI(ApiResources.admissions.base, ApiResources.admissions.fetchWards), {})
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loadingWards = false))
            .subscribe(
                (response: Array<BedManagement>) => {
                    this.wards = response;
                },
                () => {
                    this.wards = [];
                }
            );
    }

    fetchRooms(wardId) {
        this.showRooms = true;
        this.showWards = false;
        this.loadingRooms = true;
        this.httpService
            .post<Array<BedManagement>>(ApiResources.getURI(ApiResources.admissions.base, ApiResources.admissions.fetchRooms), { wardId: wardId })
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loadingRooms = false))
            .subscribe(
                (response: Array<BedManagement>) => {
                    this.rooms = response;
                },
                () => {
                    this.rooms = [];
                }
            );
    }

    fetchBeds(callback?: Function) {
        if (!this.bookAdmissionForm.value.chargeModuleTemplateId) {
            return;
        }
        this.showBeds = true;
        this.loadingBeds = true;
        this.selectedBed = new BedManagement;
        const request = {
            chargeCategoryId: this.chargeCategoryId,
            bedStatusId: 1,
            chargeModuleTemplateId: this.bookAdmissionForm.value.chargeModuleTemplateId
        };
        this.httpService
            .post<Array<BedManagement>>(ApiResources.getURI(ApiResources.admissions.base, ApiResources.admissions.fetchBeds), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loadingBeds = false))
            .subscribe(
                (response: Array<BedManagement>) => {
                    this.beds = response;
                    callback && callback();
                },
                () => {
                    this.beds = [];
                }
            );
    }

    openWard(ward: BedManagement) {
        this.showWards = false;
        this.selectedWard = ward;

        this.showBeds = false;
        this.selectedBed = undefined;
        this.fetchRooms(ward.wardId);
        //this.showWards = false;
        //this.selectedWard = ward;

        //this.showBeds = false;
        //if (ward === undefined) {
        //    this.fetchWards();
        //    this.selectedWard = ward;
        //}
        //else {
        //    this.fetchRooms(ward.wardId);
        //}
        //this.selectedBed = undefined;
    }

    openRoom(room: BedManagement) {
        this.showRooms = false;
        this.selectedRoom = room;
        //this.fetchBeds(room.roomId);
    }

    bookBed(bed: BedManagement) {

        if (bed.bedStatusName === 'Available') {
            this.selectedBedManagement = new BedManagement();
            this.selectedBed = bed;
            this.selectedBedManagement = bed;
            this.selectedBedManagement.wardId = bed.wardId;
            this.selectedBedManagement.wardName = bed.wardName;
            this.selectedBedManagement.roomId = bed.roomId;
            this.selectedBedManagement.roomName = bed.roomName;
            this.selectedBedManagement.roomRent = bed.roomRent;
            this.bookAdmissionForm.patchValue({
                bedId: bed.bedId
            });
        }
    }

    selectBed(bed: BedManagement) {
        console.log(bed);
        this.selectedBed = bed;
        this.selectedBedManagement = bed;
        this.selectedBedManagement.wardId = bed.wardId;
        this.selectedBedManagement.wardName = bed.wardName;
        this.selectedBedManagement.roomId = bed.roomId;
        this.selectedBedManagement.roomName = bed.roomName;
        this.selectedBedManagement.roomRent = bed.roomRent;
        this.bookAdmissionForm.patchValue({
            bedId: bed.bedId
        });
    }

    onNextPage() {
        $("body,html").animate({ scrollTop: 0 });
        this.fetchAdmissions();
    }

    onApplyFilters() {
        this.filters.applied = UtilHelper.isFiltersApplied(this.filters.options);
        this.initPagination();
        this.resultsType = "all";
        this.loading = true;
        this.fetchAdmissions();

        this.onCloseFilters();
    }

    onResetFilters() {
        this.filters.init();

        this.loading = true;
        this.fetchAdmissions();
        this.onCloseFilters();
    }

    onShowFilters() {
        this.filters.options.dischargeDate = null;
        $("body").addClass("right-bar-enabled");
    }

    onCloseFilters() {
        $("body").removeClass("right-bar-enabled");
    }

    onEncounter(encryptedAdmissionId: string) {
        this.router.navigate(["/app/encounter", encryptedAdmissionId]);
    }

    onViewPatientProfile(encryptedPatientId: string) {
        this.router.navigateByUrl(`app/patient/${encryptedPatientId}`);
    }

    fetchVisitTypeIp = () => {
        this.httpService
            .post<GenericResponse>(ApiResources.getURI(ApiResources.providerLocations.base, ApiResources.providerLocations.fetchVisitTypeIp), {})
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.isVisitTypeloading = false))
            .subscribe(
                (response: GenericResponse) => {
                    this.visitors = response.data as Array<LookUpModel>;
                    // var findInPatient = this.visitors.find(x => x.name === 'IN PATIENT');
                    const findInPatient = this.visitors.find(m => m.name.toLowerCase().trim() === "In Patient".toLowerCase().trim());
                    //if (findInPatient) {
                    //    setTimeout(() => {
                    //        this.bookAdmissionForm.patchValue({ visitTypeId: findInPatient.id });
                    //    }, 1000);
                    //}
                    if (findInPatient != undefined) {
                        this.bookAdmissionForm.patchValue({
                            visitTypeId: findInPatient.id
                        });
                    }
                },
                () => {
                    this.visitors = new Array<LookUpModel>();
                }
            );
    }

    //onChangeProvider(event: IResource) {
    //    this.providerId = event.id;
    //    //this.fetchProviderLocations(true);
    //    this.fetchDepartments(this.providerId);
    //}
    private fetchDoctorUnits(locationId: number) {
        this.loadingDoctorUnits = true;
        const request = {
            locationId: locationId
        };
        this.httpService.post(ApiResources.getURI(ApiResources.doctorUnit.base, ApiResources.doctorUnit.fetch), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loadingDoctorUnits = false))
            .subscribe((response: Array<DoctorUnits>) => {
                this.DoctorUnits = response;
                (error: HttpErrorResponse) => {
                    const errorMessage = UtilHelper.handleError(error);
                    if (errorMessage) {
                        this.notifyService.warningToast(errorMessage);
                    } else {
                        this.notifyService.defaultError();
                    }
                }
            });

    }
    onOpenBookAdmissionModel(content: TemplateRef<any>, admissionItem?: Admission) {

        if (admissionItem && this.isAdmissionEdit) {
            const adjustedDatTime = new Date(new Date(admissionItem.admissionDate).getTime() + this.admissionEditMinutes * 60000);
            if (adjustedDatTime < new Date()) {
                return this.notifyService.warningToast('Cannot Modify Admission, you crossed beyond time limit');
            }

        }
        this.fetchVisitTypeIp();
        //this.fetchLocationChargeTemplates();
        this.fetchInsurances();
        this.fetchTPAOrinizations();
        this.selectedBedManagement = new BedManagement;
        this.fetchDoctorSpecialization(null, this.page.userAccount.locationId);
        this.fetchDepartments();
        this.fetchCaseType();
        //this.fetchEmergencyCaseTypes();
        this.fetchReferralDoctor();
        this.fetchChargeCategory();
        this.fetchPatients();
        this.fetchBeds();
        this.fetchCategories();
        //this.fetchAdmissionProviders(null);
        //this.fetchDepartments(null);
        if (this.fromOp === "fromAppointments") {

            //if (this.patient != null) {
            //    this.bookAdmissionForm.patchValue({
            //        providerName: this.patient.providerName,
            //        providerId: this.patient.providerId
            //    })
            //}
            //this.findPatient(this.pid);
            ////    this.fetchPatientProviders(this.pid);
            //this.bookAdmissionForm.patchValue({
            //    providerName: this.patient.providerName,
            //    providerId: this.patient.providerId
            //})
        }

        //this.fetchWards();

        if (admissionItem) {
            //this.findPatient(admissionItem.patientId);
            this.buildUpdateBookAdmissionForm(admissionItem);
        } else {
            this.buildBookAdmissionForm();
            this.fetchDepartments(null);
        }

        this.modalRef = this.modalService.open(content, {
            backdrop: "static",
            keyboard: false,
            centered: true,
            size: "lg",
            windowClass: "custom-modal effect-scale"
        });
    }

    onOpenViewAdmissionModel(content: TemplateRef<any>, admission: Admission) {
        this.selectedAdmission = admission;
        this.providerId = admission.providerId;

        this.modalRef = this.modalService.open(content, {
            backdrop: "static",
            keyboard: false,
            centered: true,
            windowClass: "custom-modal invoice-modal effect-scale"
        });
    }

    onOpenIndentModel(content: TemplateRef<any>, admission: Admission) {
        this.selectedAdmission = admission;

        this.modalRef = this.modalService.open(content, {
            backdrop: "static",
            keyboard: false,
            centered: false,
            size: "xxl",
            windowClass: "custom-modal extra-large-modal effect-scale"
        });
    }

    onGenerateBarCodeModel(content: TemplateRef<any>, admission: Admission) {
        this.selectedAdmission = admission;

        this.modalRef = this.modalService.open(content, {
            backdrop: "static",
            keyboard: false,
            centered: false,
            //size: "md",
            windowClass: "custom-modal effect-scale"
        });
    }



    private fetchAdmissionPayTypes() {
        this.loadingAdmissionPayTypes = true;
        this.resourceService.admissionPayTypes()
            .pipe(finalize(() => { this.loadingAdmissionPayTypes = false }))
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: Array<IResource>) => {
                this.admissionPayTypes = response;
            });
    }

    private fetchPackages(moduleType: string, callback?: Function): void {
        this.loadingPackages = true;
        this.resourceService.packageModules(this.page.userAccount.locationId, "IP", moduleType)
            .pipe(finalize(() => { this.loadingPackages = false }))
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: Array<IResource>) => {
                this.packages = response;
                callback && callback();
            });
    }

    private fetchPatientInsurances(admissionId: number) {
        this.resourceService.fetchPatientInsurances(admissionId, this.appointmentId)
            .pipe(finalize(() => { this.loadingCompanies = false }))
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: Array<IResource>) => {
                this.insuranceCompanies = response;
                if (this.insuranceCompanies.length == 0) {
                    this.fetchInsurances();
                    this.buildInsurancesForm();
                    this.tempTemplate = this.patientInsurancetemplate;
                } else {
                    this.tempTemplate = this.insurancetemplate;
                }
                this.onOpen(this.tempTemplate);
            });
    }

    onSubmit() {
        this.submitted = true;
        if (!this.patientForm.valid) {
            return;
        }

        const request = Object.assign(UtilHelper.clone(this.patientForm.getRawValue()));

        this.submitting = true;
        this.httpService.post(ApiResources.getURI(ApiResources.patientInsurance.base, ApiResources.patientInsurance.add), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => {
                this.submitting = false;
                this.submitted = false;
            }))
            .subscribe((response: string) => {
                this.notifyService.successToast(response);
                this.onCloseModal();
            }, (error: HttpErrorResponse) => {
                const errorMessage = UtilHelper.handleError(error);
                if (errorMessage) {
                    this.notifyService.warningToast(errorMessage);
                } else {
                    this.notifyService.defaultErrorToast();
                }
            });
    }

    onCloseModal() {
        try {
            this.modalRef.close();
            this.modalRef = undefined;

        } catch (e) {
            // ignored;
        }

        this.submitting = undefined;
        this.submitted = undefined;
        this.selectedAdmission = undefined;
        this.loadingSlots = undefined;
        this.admissionId = undefined;
        this.reason = null;
        this.showWards = false;
        this.loadingWards = false;
        this.wards = undefined;
        this.showRooms = false;
        this.loadingRooms = false;
        this.rooms = undefined;
        this.selectedWard = undefined;
        this.selectedRoom = undefined;
        this.selectedBedManagement = new BedManagement;
        this.finalAmount = 0;
        this.admissionNo = 0;
        this.umrNo = null;
        this.patient = undefined;
        this.departments = undefined;
        this.providers = undefined;
        this.selectedCounsellingId = undefined;
    }

    onBookAdmission() {
        this.submitted = true;
        this.bookAdmissionForm.controls.admissionDate.setErrors(null);
        //if (this.bookAdmissionForm.value["admissionId"] === 0 && this.patient && this.patient.admissionId !== null && this.patient.isDischarged === false) {
        //    this.bookAdmissionForm.controls.patientId.setErrors({ 'incorrect': true });
        //    this.notifyService.warning("This Patient already has admission & not discharged!");
        //}
        //this.bookAdmissionForm.controls.bedId.setErrors(null);
        if (!this.bookAdmissionForm.valid) {
            return;
        }
        if (this.files && this.files.length > 0) {
            if (!UtilHelper.isEmpty(this.bookAdmissionForm.get("documentName").value)) {
                this.notifyService.warning("Please enter document name");
                return;
            }
            if (this.bookAdmissionForm.get("documentType").value === null) {
                this.notifyService.warning("Please enter document type");
                return;
            }
        }
        const model = UtilHelper.clone(this.bookAdmissionForm.value);
        //if (model["chargeBillingCategoryId"] === null) {
        //    this.notifyService.warningToast("Please select Billing Charge Category")
        //}
        this.submitting = true;

        

        model["locationId"] = this.page.userAccount.locationId;
        model["createdBy"] = this.page.userAccount.accountId;
        model["breakfastStr"] = model.breakfast;
        model["lunchStr"] = model.lunch;
        model["dinnerStr"] = model.dinner;
        model["emergencyInfo"] = JSON.stringify(model.emergencyInfo);
        model["surrogacyData"] = JSON.stringify(model.surrogacyData);
        model["nriData"] = JSON.stringify(model.nriData);
        model["bedAssociatedData"] = JSON.stringify(model.bedAssociatedData);
        if (model["chargeBillingCategoryId"] != null) {
            model["chargeCategoryId"] = model["chargeBillingCategoryId"];
        }
        model.breakfast = null;
        model.lunch = null;
        model.dinner = null;
        // ReSharper disable once TsResolvedFromInaccessibleModule
        model.admissionDate = this.bookAdmissionForm.value.admissionDate.replace(":00.000", "");
        //model.isConvertedFromOp = this.appointmentNo;
        const time = this.bookAdmissionForm.value.admissionDate.split('T');
        model.admissionTimeString = time[1].toString();
        if (this.selectedBedManagement && this.selectedBedManagement.bedId) {
            model["bedId"] = this.selectedBedManagement.bedId;
        }
        if (this.isConvertedFromOPtoIp) {
            model["isConvertedFromOPtoIp"] = true;
        }
        const formData = UtilHelper.prepareFormData(UtilHelper.clone(model));
        const files = this.files;
        if (files) {
            const n = files.length;
            if (n > this.maxFiles) {
                files.splice(this.maxFiles, files.length);
            }

            if (this.selectedCounsellingId) {
                model["counsellingId"] = this.selectedCounsellingId;
            }

            files.forEach((file: File, index: number) => {
                formData.append(`File${index + 1}`, file, file.name);
            });
        }
        this.httpService
            .postFile(ApiResources.getURI(ApiResources.admissions.base, ApiResources.admissions.modify), formData)
            .pipe(finalize(() => { this.submitted = false; }))
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe(() => {
                this.fetchPatientFutureAppointment();
                this.onCloseModal();
                this.bookAdmissionForm.reset();
                this.notifyService.successToast("Admission has created successfully.");
                this.fetchAdmissions();
            }, (error: HttpErrorResponse) => {
                this.submitting = false;
                this.onCloseModal();
                this.bookAdmissionForm.reset();
                const errorMessage = UtilHelper.handleError(error);
                if (errorMessage) {
                    this.notifyService.warning(errorMessage);
                } else {
                    this.notifyService.defaultError();
                }
            });
    }

    onCancel = (item: Admission) => {

        if (item.cancelling) return;

        if (item && this.isAdmissionCancel) {
            const adjustedDatTime = new Date(new Date(item.admissionDate).getTime() + this.admissionCancelMinutes * 60000);
            if (adjustedDatTime < new Date()) {
                return this.notifyService.warningToast('Cannot Cancel Admission, you crossed beyond time limit');
            }

        }

        item.cancelling = true;
        this.notifyService.confirm("Do you really want to cancel this admission? This process cannot be undone.",
            () => {
                this.httpService
                    .post(ApiResources.getURI(ApiResources.admissions.base, ApiResources.admissions.cancel), {
                        id: item.admissionId, createdBy: this.page.userAccount.accountId, roleId: this.page.userAccount.roleId, roleName: this.page.userAccount.roleName, createdByName: this.page.userAccount.fullName
                    })
                    .pipe(finalize(() => { item.cancelling = false; }))
                    .pipe(takeUntil(this.page.unSubscribe))
                    .subscribe((response: GenericResponse) => {
                        if (response.status === GenericStatus[GenericStatus.Success]) {
                            this.fetchAdmissions();
                        } else {
                            this.notifyService.defaultError();
                        }
                    }, (error: HttpErrorResponse) => {
                        item.cancelling = false;
                        const errorMessage = UtilHelper.handleError(error);
                        if (errorMessage) {
                            this.notifyService.warning(errorMessage);
                        } else {
                            this.notifyService.defaultError();
                        }
                    });
            }, () => {
                item.cancelling = false;
            })
    }

    onOpenCancelModel(content: TemplateRef<any>, admissionId: number) {
        this.admissionId = admissionId;
        this.modalRef = this.modalService.open(content, {
            backdrop: "static",
            keyboard: false,
            centered: true,
            size: "lg",
            windowClass: "custom-modal slots-modal effect-scale"
        });
    }


    onCancelSubmit() {
        const admissionId = this.admissionId;
        this.onCancelAdmission(admissionId, this.reason);
    }

    onCancelAdmission(admissionId: number, cancelReason: string) {
        this.onCloseModal();
        const request = Object.assign(UtilHelper.clone({ admissionId: admissionId, modifiedBy: this.page.userAccount.accountId, reason: cancelReason, logFrom: this.page.userAccount.roleId }));
        this.notifyService.confirm("Do you really want to cancel this admission? This process can not be undone.", () => {
            this.modifying = true;
            this.modifyingContent = " cancelling the selected admission";

            this.httpService.put(ApiResources.getURI(ApiResources.admissions.base, ApiResources.admissions.cancel), request)
                .pipe(takeUntil(this.page.unSubscribe))
                .pipe(finalize(() => { this.modifying = false }))
                .subscribe(() => {

                    this.fetchAdmissions();
                });
        });


    }

    private fetchDoctorSpecialization(providerId?: string, locationId?: number) {
        this.loading = true;
        const request = {
            filter: providerId,
            locationId: locationId,

        }

        this.httpService
            .post<Array<ProviderSpecialization>>(ApiResources.getURI(ApiResources.appointments.base, ApiResources.appointments.fetchDoctorSpecialization), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loading = false))
            .subscribe(
                (response: Array<ProviderSpecialization>) => {
                    this.providerSpecialization = response;
                },
                () => {
                    this.providerSpecialization = new Array<ProviderSpecialization>();
                }
            );
    }

    onChangeProvider(p: DoctorUnits) {
        console.log(p);
        //this.filters.options.providerId = p.providerId;
    }
    private fetchCaseType() {
        this.loadingCaseTypes = true;
        this.resourceService.caseTypes()
            .pipe(finalize(() => { this.loadingCaseTypes = false }))
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: Array<IResource>) => {
                this.caseTypes = response;
            });
    }
    //private fetchEmergencyCaseTypes() {
    //    this.loadingEmergencyCaseTypes = true;
    //    this.resourceService.emergencyCaseTypes()
    //        .pipe(finalize(() => { this.loadingEmergencyCaseTypes = false }))
    //        .pipe(takeUntil(this.page.unSubscribe))
    //        .subscribe((response: Array<IResource>) => {
    //            this.emergencyCaseTypes = response;
    //        });
    //}



    ngOnInit() {
        this.appData.userAccount
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((userAccount: IUserAccount) => {
                if (userAccount) {
                    this.page.userAccount = userAccount;
                    this.fetchDoctorUnits(this.page.userAccount.locationId);
                    this.fetchPriorities();
                    this.fetchCounsellingCodes();
                    this.fetchRelationShips();
                    this.fetchSurgeryTypes();
                    this.fetchProvidersFilter();
                    this.fetchVisitTypeIp();
                    this.fetchPatients();
                    this.buildBookAdmissionForm();
                    this.getSettingsAdmissionCancel();
                    this.getSettingsAdmissionEdit();
                    this.route.params
                        .pipe(takeUntil(this.page.unSubscribe))
                        .subscribe((params: Params) => {
                            if (params["pid"] != 'bed' && params["pid"] != undefined) {
                                let patientId = params["pid"];
                                this.pid = patientId;
                                const FromOp = params["isOpToIp"];
                                this.fromOp = params["isOpToIp"];
                                this.isConvertedFromOPtoIp = FromOp === "fromAppointments";

                                if (patientId) {

                                    patientId = parseInt(patientId);
                                    this.onOpenBookAdmissionModel(this.templateBookAdmission, null);
                                    this.resourceService.patientsAll()
                                        .pipe(finalize(() => { this.loadingPatients = false }))
                                        .pipe(takeUntil(this.page.unSubscribe))
                                        .subscribe((response: Array<IResource>) => {
                                            this.patients = response;
                                            this.fetchAdmissions();
                                            this.findPatient(patientId);
                                            // this.fetchAdmissionProviders();
                                            (<FormControl>this.bookAdmissionForm.controls["patientId"]).setValue(patientId);
                                        });
                                }
                            }
                            else if (params["pid"] == 'bed') {
                                this.onOpenBookAdmissionModel(this.templateBookAdmission, null);
                                this.resourceService.patientsAll()
                                    .pipe(finalize(() => { this.loadingPatients = false }))
                                    .pipe(takeUntil(this.page.unSubscribe))
                                    .subscribe((response: Array<IResource>) => {
                                        this.patients = response;
                                        this.fetchAdmissions();
                                    });
                            }
                            else {
                                this.isPatientFilters = true;
                                const url = this.router.url;
                                this.routingValue = url.split("/")[url.split("/").length - 3];
                                const encryptedPatientId = url.split("/")[url.split("/").length - 2];
                                if (encryptedPatientId && encryptedPatientId != "admissions") {
                                    this.httpService
                                        .post<any>(ApiResources.getURI(ApiResources.application.base, ApiResources.application.decode), { json: encryptedPatientId })
                                        .pipe(takeUntil(this.page.unSubscribe))
                                        .subscribe(
                                            (response: any) => {
                                                this.urlPatientId = parseInt(response);
                                                if (this.urlPatientId && this.urlPatientId > 0) {
                                                    this.isPatientFilters = false;
                                                }
                                                this.fetchAdmissions();
                                            },
                                            () => { }
                                        );
                                } else {
                                    this.fetchAdmissions();
                                }
                            }
                        });
                } else {
                    this.page.userAccount = undefined;
                }
            });

        this.fetchAdmissionPayTypes();
    }

    onInternalMedicine(encryptedAppointmentId: string) {
        this.router.navigate(["/app/internal-medicine", encryptedAppointmentId, 'a']);
    }
    onObEncounter(encryptedAppointmentId: string) {
        this.router.navigate(["/app/ob-ip-encounter", encryptedAppointmentId, 'a']);
    }
    onGynEncounter(encryptedAppointmentId: string) {
        this.router.navigate(["/app/gyn-ip-encounter", encryptedAppointmentId, 'a']);
    }
    onDietEncounter(encryptedAppointmentId: string) {
        this.router.navigate(["/app/diet-plan-encounter", encryptedAppointmentId, 'a']);

    }
    onNeonatalDashboardEncounter(encryptedAppointmentId: string) {
        this.router.navigate(["/app/neonatal-ip-encounter", encryptedAppointmentId, 'a']);
    }
    onViewDocument(encryptedPatientId: string) {
        this.router.navigate(["/app/patient/", encryptedPatientId, 'documents']);
    }
    ngOnDestroy() {
        this.onCloseModal();
        this.onCloseFilters();
        this.page.unsubscribeAll();
    }


    fetchDoctorSpecializationHelper($event: any) {
        if ($event && $event.term && $event.term.length > 1) {
            //let locationId = this.bookAdmissionForm.get("locationId").value
            //let consultationTypeId = this.bookAdmissionForm.get("consultationTypeId").value
            this.fetchDoctorSpecialization($event.term, this.page.userAccount.locationId);
        } else {
            this.providerSpecialization = new Array<ProviderSpecialization>();
        }
    }

    openPopover = (p: any, item: Admission) => {
        p.open();
        item.editExpectedDischargeDate = false;
        this.currentPopover = p;
    }

    closePopover = () => {
        this.currentPopover.close()
    }

    editExpectedDischargeDate = (item: Admission) => {

        item.editExpectedDischargeDate = true;
    }

    onExpectedDischargeDateChange = ($event: any, item: Admission) => {

        item.editExpectedDischargeDate = true;
        this.eDate = $event.target.value;
        if (item.isUpdatingDischargeDate === true) {
            item.expectedDischargeDateView = this.datePipe.transform(new Date($event.target.value), 'yyyy-MM-dd');
        }
    }

    updateExpectedDischargeDate = (item: Admission) => {
        item.expectedDischargeDate = this.eDate;
        if (item.expectedDischargeDate == null) {
            this.notifyService.warning("you can't update without selecting date");
            return;
        }
        item.isUpdatingDischargeDate = true;
        this.httpService
            .post<any>(ApiResources.getURI(ApiResources.admissions.base, ApiResources.admissions.updateDischargeDate),
                {
                    id: item.admissionId,
                    date: item.expectedDischargeDate,
                    dischargedBy: this.page.userAccount.accountId
                })
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe(
                (response: number) => {
                    this.dischargeDate = response
                    item.isUpdatingDischargeDate = false;
                    item.editExpectedDischargeDate = false;
                    this.fetchAdmissions();
                },
                () => { }
            );

    }
    private fetchReferralDoctor() {
        this.loadingReferraldoctor = true;
        this.resourceService.referralDotor()
            .pipe(finalize(() => { this.loadingReferraldoctor = false }))
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: Array<IResource>) => {
                this.referraldoctors = response;
            });
    }
    fetchPatientFutureAppointment() {
        this.loadingfutureAppointment = true;
        const request = {};
        request["patientId"] = this.bookAdmissionForm.value["patientId"];
        request["admissionDate"] = this.bookAdmissionForm.value.admissionDate.replace(":00.000", "");
        const a = request["admissionDate"].split("T");
        const time = a[1];
        console.log(time);
        request["admissionTime"] = time;

        this.httpService
            .post(ApiResources.getURI(ApiResources.appointments.base, ApiResources.appointments.findPatientAppointmentDate), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loadingfutureAppointment = false))
            .subscribe(
                (response: Array<Appointment>) => {
                    this.patientFutureAppointments = response;
                    if (this.patientFutureAppointments.length > 0) {
                        this.onOpenAppointmentModel(this.templatePatientAppointment);
                    }
                },
                () => {
                    this.patientFutureAppointments = [];
                }
            );
    }
    onSelectPayType(record: Array<IResource>) {
        const payType = this.bookAdmissionForm.get("admissionPayTypeId").value
        const selectedPayType = record.find(x => x.id == payType);
        console.log(selectedPayType);
        const value = payType;
        if (value >= 1) {
            this.bookAdmissionForm.get("insuranceCompanyId").setValidators([Validators.required]);
            this.bookAdmissionForm.get("insuranceCompanyId").updateValueAndValidity();
            this.bookAdmissionForm.get("insuranceCompanyId").setValue(null);
            this.bookAdmissionForm.get("tpaId").setValue(null);
            this.bookAdmissionForm.get("patientOrganization").setValue(null);
        }

        if (!selectedPayType) {
            this.packages = [];
        } else {
            this.fetchPackages(selectedPayType.name);
            this.fetchLocationChargeTemplates(selectedPayType.id);
        }
    }
    onOpenAppointmentModel(content?: TemplateRef<any>) {
        this.modalRef = this.modalService.open(content, {
            backdrop: "static",
            keyboard: false,
            centered: true,
            size: "xl",
            windowClass: "custom-modal effect-scale"
        });
    }
    fetchPatientHelper($event: any) {

        if (UtilHelper.isEmpty($event)) {
            if (UtilHelper.isEmpty($event.term)) {
                const request = $event.term;
                this.onPatientSearch(request);
            } else {
                this.patients = new Array<IResource>();
            }
        } else {
            this.patients = new Array<IResource>();
        }
    }

    private onPatientSearch(request: string) {
        if (UtilHelper.isEmpty(request) && request.length > 2) {
            this.loadingPatients = true;
            this.resourceService.patients(request.trim())
                .pipe(finalize(() => { this.loadingPatients = false }))
                .pipe(takeUntil(this.page.unSubscribe))
                .subscribe((response: Array<IResource>) => {
                    this.patients = response;
                });
        } else {
            this.loadingPatients = false;
            this.patients = new Array<IResource>();
        }

    }
    navigateToReschedule(pid: string, value: string) {
        console.log(pid, value);
        this.router.navigateByUrl(`app/out-patients/${pid}/${value}`);

    }
    navigateToAdmissions(pid: string, value: string) {
        console.log(pid, value);
        this.router.navigateByUrl(`app/out-patients/${pid}/${value}`);

    }

    private fetchTPAOrinizations() {
        this.loadingTpas = true;
        this.resourceService.tpaCompanies()
            .pipe(finalize(() => { this.loadingTpas = false }))
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: Array<IResource>) => {
                this.tpa = response;
            });
    }

    onOpenRequestBedModel(template: TemplateRef<any>, admission: Admission) {
        if (admission.admissionBedChangeRequestId) {
            this.notifyService.warning("Request Raised Already");
        }
        else {
            this.selectedAdmission = admission;
            this.buildRaiseBedRequestForm();
            this.fetchChargeCategories();
            this.modalRef = this.modalService.open(template, {
                backdrop: "static",
                keyboard: false,
                centered: true,
                size: "lg",
                windowClass: "custom-modal slots-modal effect-scale"
            });
        }

    }

    private buildRaiseBedRequestForm() {
        this.raiseBedChangeRequestForm = this.formBuilder.group({
            admissionBedRequestId: 0,
            admissionId: this.selectedAdmission.admissionId,
            requestComments: [null, [Validators.required, WhiteSpaceValidator.isValid]],
            chargeCategories: [null, [Validators.required]],
            createdBy: this.page.userAccount.accountId,
            locationId: this.page.userAccount.locationId,
            admissionChangeRequestTypeId: 1,
            admissionTransferRequestId: 0,
        });

    }

    onSubmitBedChangeRequest() {
        this.submitted = true;
        if (this.raiseBedChangeRequestForm.invalid) {
            return;
        }
        const request = Object.assign(UtilHelper.clone(this.raiseBedChangeRequestForm.getRawValue()));
        if (request.chargeCategories) {
            request.chargeCategories = request.chargeCategories.join(",");
        }
        this.httpService
            .post(ApiResources.getURI(ApiResources.admissions.base, ApiResources.admissions.raiseBedChangeRequest), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loadingfutureAppointment = false))
            .subscribe(
                (response: number) => {
                    if (response > 1) {
                        this.onCloseModal();
                        this.notifyService.successToast("Request Raised Succesfull");
                        this.fetchAdmissions();
                    }
                    else {
                        switch (response) {
                            case -1:
                                this.notifyService.warningToast("Sorry Error Occured");
                                break;
                            case -2:
                                this.notifyService.warningToast("Request Already Raised For this Admissison");
                                break;
                        }

                        //this.notifyService.warningToast("Sorry Error Occured");
                    }
                },
                () => {
                    this.patientFutureAppointments = [];
                }
            );
    }

    private fetchChargeCategories() {
        this.resourceService.chargeCategory()
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: Array<IResource>) => {
                this.chargeCategories = response;
                console.log(this.chargeCategories);
            });
    }

    onGenerateBarcodeView(content: TemplateRef<any>, umrNo: string) {
        this.umrNo = umrNo;
        this.modalRef = this.modalService.open(content, {
            backdrop: "static",
            keyboard: false,
            centered: false,
            size: "sm",
            windowClass: "custom-modal effect-scale"
        });
    }
    onRedirectBabyRegistration(record: Admission, value: string) {
        this.router.navigate(['app/masters/baby-registration', record.patientId, value]);
    }
    onRedirectBirthCertificate(record: Admission, value: string) {
        this.router.navigate(['app/masters/birth-certificate', record.patientId, value]);
    }

    removePrintCss() {
        const head = document.getElementsByTagName('head')[0];
        const fileref = document.getElementById("BarcodePrint");
        if (fileref != null)
            head.removeChild(fileref);
        this.onCloseModal();
    }

    onOpenDoctorUnitRequest(template: TemplateRef<any>, admission: Admission) {
        this.selectedAdmission = admission;
        this.isShowTemplate = false;
        this.fetchrequests();
        setTimeout(() => {
            if (this.isShowTemplate) {
                this.notifyService.warning("Request Raised")
            }
            else {
                this.buildRaisedDotcorUnitRequest();
                this.modalRef = this.modalService.open(template, {
                    backdrop: "static",
                    keyboard: false,
                    centered: true,
                    size: "lg",
                    windowClass: "custom-modal slots-modal effect-scale"
                });
                this.fetchDoctorUnits(this.page.userAccount.locationId);
            }

        }, 50)

    }
    private buildRaisedDotcorUnitRequest() {
        this.raiseDoctorUnitRequestForm = this.formBuilder.group({
            admissionTransferRequestId: 0,
            admissionId: this.selectedAdmission.admissionId,
            requestComments: [null, [Validators.required, WhiteSpaceValidator.isValid]],
            doctorUnitMasterId: [null, [Validators.required]],
            createdBy: this.page.userAccount.accountId,
            locationId: this.page.userAccount.locationId,
            admissionChangeRequestTypeId: 2
        });

    }
    onOpenAttendentView(template: TemplateRef<any>, admission: Admission) {
        this.getLogoImage();
        this.selectedAdmission = admission
        this.modalRef = this.modalService.open(template, {
            backdrop: "static",
            keyboard: false,
            centered: true,
            size: "sm",
            windowClass: "custom-modal slots-modal effect-scale"
        });
    }
    getLogoImage = () => {
        this.loading = true;

        this.httpService
            .get<Array<Setting>>(ApiResources.getURI(ApiResources.setting.base, ApiResources.setting.fetch), { type: "Logo", active: true })
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => { this.loading = false }))
            .subscribe(
                (response: Array<Setting>) => {
                    if (response && response.length > 0) {
                        this.logoBasics = response[0];
                        if (UtilHelper.isEmpty(response[0].imageUrl)) {
                            response[0].imageUrl = `${ApiResources.getURI(ApiResources.resources.base, ApiResources.resources.getProfileImage)}?imagePath=${response[0].imageUrl}`;
                        }
                    }
                },
                () => {
                    this.logoBasics = new Setting();
                }
            );
    }

    onSubmitDoctorUnitChangeRequest(isType: boolean) {
        this.submitted = true;
        this.isDoctorUnit = isType;
        if (this.isDoctorUnit && this.raiseDoctorUnitRequestForm.invalid) {
            return;
        }
        else if (!this.isDoctorUnit && this.raiseBedChangeRequestForm.invalid) {
            return;
        }

        this.submitting = true;
        const request = this.isDoctorUnit ? { ...this.raiseDoctorUnitRequestForm.getRawValue(), } : { ...this.raiseBedChangeRequestForm.getRawValue(), };
        if (!this.isDoctorUnit) {
            request.chargeCategories = request.chargeCategories.join(",");
        }
        const url = ApiResources.getURI(ApiResources.admissions.base, ApiResources.admissions.addTransferRequest);
        this.httpService.post(url, request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.submitted = this.submitting = false))
            .subscribe(
                (response: number) => {
                    if (response > 0) {
                        this.notifyService.successToast(`Requested Successfully`);

                    }
                    else {
                        switch (response) {
                            case -1:
                                this.notifyService.warningToast(`Sorry Error Occured`);
                                break;
                            case -2:
                                this.notifyService.warningToast(`Request Already Raised For this Admissison`);
                                break;
                        }
                    }
                    this.onCloseModal();
                },
            );
    }

    onChangeDoctorUnit(value: any) {
        const id = value.doctorUnitMasterId;
        if (this.selectedAdmission.doctorUnitMasterId == id) {
            this.notifyService.warningToast("present you are having same doctor unit");
            this.raiseDoctorUnitRequestForm.patchValue({
                doctorUnitMasterId: 0
            })
        }

    }


    private fetchrequests() {
        this.loading = true;
        const request = {
            admissionId: this.selectedAdmission.admissionId,
            admissionChangeRequestTypeId: 2,
            active: true
        };
        this.httpService.post(ApiResources.getURI(ApiResources.admissions.base, ApiResources.admissions.fetchTransferRequest), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loading = false))
            .subscribe(
                (response: Array<AdmissionTransferRequest>) => {
                    if (response.length > 0) {
                        this.isShowTemplate = true;
                    }
                },
            );
    }

    private fetchLocationChargeTemplates(admissionPayTypeId: number) {
        this.loadingLocationChargeTemplates = true;
        this.resourceService.locationChargeTemplate(admissionPayTypeId)
            .pipe(finalize(() => { this.loadingLocationChargeTemplates = false }))
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: Array<IResource>) => {
                this.locationChargeTemplates = response;
            });
    }

    onChangeChargeTemplate(selectedChargeTemplate: IResource) {
        this.bookAdmissionForm.get('insuranceCompanyId').setValue(selectedChargeTemplate.optionalData);
        this.bookAdmissionForm.get('tpaId').setValue(selectedChargeTemplate.optionalId1);
        this.fetchBeds();
    }
}