import { Component, OnDestroy, OnInit, TemplateRef } from "@angular/core";
import { ActivatedRoute, Params, UrlTree } from "@angular/router";
import { takeUntil, finalize, debounceTime, distinctUntilChanged, switchMap, tap, catchError } from "rxjs/operators";
import { NgbModal, NgbModalRef } from "@ng-bootstrap/ng-bootstrap";
import { Location } from '@angular/common';

import { IUserAccount, Page, GenericResponse, GenericStatus, Pagination, IResource } from "@shared/models";
import { AppData, HttpService, NotifyService, ResourceService } from "@shared/services";
import { ApiResources, UtilHelper, LinqHelper } from "../../../../../shared/helpers";

import { IChargeModel } from "../../models/charge.model";
import { RepeatType } from "../../models/repeat-type.model";
import { IPharmacyIndentModel } from "../../models/pharmacy-indent.model";
import { FinalBillBasicModel } from "../../models/final-bill-basic.model";
import { FormGroup, FormBuilder, FormArray, FormControl } from "@angular/forms";
import { Subscription, Subject, Observable, of } from "rxjs";
import { AutomaticType } from "../../models/automatic-type.model";
import { IFilterModel } from "../../../masters/pages/charge-management/models/filter.model";
import { IAdmissionPackageModuleModel } from "../../models/admission-package.model";
import { ChargeType } from "../../../../../shared/enums";
import { ICanComponentDeactivate } from "../../../../../shared/guards";
import { Admission, LabHeaders, InsuranceAdmission } from "../../../../../shared/entities";
import { ILabServicesModel } from "../../models/lab-services.model";
import { NewLabServicesModel } from "../../models/new-lab-services.model";
import { NewServicesModel } from "../../models/new-services.model";
import { PackageModuleModel, PackageModuleDetailModel } from "../../../masters/pages/package-modules/models";
import { SurgeryModel } from "../../../operation-theater/models";
import { ISurgeryChargeModel } from "../../models/surgery-charge.model";
import { IScanChargeModel } from "../../models/scan-charge.model";
import { DiscountType } from "../../models/discount-type.model";

class ServiceOrder {
    generalRecords: Array<IChargeModel>;
    generalTotal: number;
    pharmacyIndentRecords: Array<IPharmacyIndentModel>;
    pharmacyIndentTotal: number;
    packageRecords: Array<IAdmissionPackageModuleModel>;
    packageTotal: number;
    labServicesRecords: Array<NewLabServicesModel>;
    labServicesTotal: number;
    surgeryServicesRecords: Array<ISurgeryChargeModel>;
    surgeryServicesTotal: number;
    scanServicesRecords: Array<IScanChargeModel>;
    scanServicesTotal: number;
}

enum EditMode {
    New = 1,
    Edit = 2
}

enum InitialType {
    Individual = 1,
    Package = 2
}

class TrackBy {
    resource(item: IResource) {
        return item.id;
    }
    package(_: number, item: PackageModuleModel): number {
        return item.packageModuleId;
    }
}

class FilterOption {
    term: string = null;
    chargeCategoryId: number;
}

interface IBasicCounselling {
    counsellingId: number;
    patientId: number;
    packageModuleId: number;
    counsellingNo: string;
}

class Filter {
    options: FilterOption;
    applied: boolean;
    constructor() {
        this.init();
    }
    init() {
        this.options = new FilterOption();
        this.applied = undefined;
    }
}

@Component({
    templateUrl: "./orders.html",
    styleUrls: ['../../services.css']
})
export class OrdersPage implements OnInit, OnDestroy, ICanComponentDeactivate {
    page: Page;
    editMode = EditMode;
    repeatType = RepeatType;
    automaticType = AutomaticType;
    discountTypeEnum = DiscountType;
    initialType = InitialType;
    chargeType = ChargeType;
    trackBy: TrackBy;
    loading: boolean;
    isChargesLoading: boolean;
    serviceOrder: ServiceOrder;
    originalServiceOrder: ServiceOrder;
    chargeRecords: Array<NewServicesModel>;
    surgeryRecords: Array<ISurgeryChargeModel>;

    scanRecords: Array<IScanChargeModel>;

    loadingPackages: boolean;
    packages: Array<PackageModuleModel>;
    packagesPagination: Pagination;
    selectedPackage: PackageModuleModel;
    deletedPackages: Array<number>;

    submitting: boolean;
    submitted: boolean;
    admissionId: string;
    isAdmission: boolean;

    filters: Filter;
    finalBillBasics: FinalBillBasicModel;

    departments: Array<IFilterModel>;
    chargeGroups: Array<IFilterModel>;
    charges: Array<IFilterModel>;


    departmentsOriginal: Array<IFilterModel>;
    chargeGroupsOriginal: Array<IFilterModel>;
    chargesOriginal: Array<IFilterModel>;

    discountForm: FormGroup;
    chargeFilterForm: FormGroup;
    returnProductsForm: FormGroup;
    deletedCharges: Array<number>;
    deletedLabServices: Array<number>;
    deletedLabBookingHeaderIds: Array<number>;
    addedIndexes: Array<number>;
    deletedPharmacy: Array<number>;
    noOfDays: number;
    bedCost: number;
    doctorCost: number;
    covidCost: number;

    isFirstTime: boolean;
    labBookingHeaderId: number;
    loadingHeader: boolean;
    headers: Array<ILabServicesModel>;
    selectedLabs: Array<NewLabServicesModel>;
    loadingBookingHeaders: boolean;
    labs: Array<NewLabServicesModel>;
    pagination: Pagination;

    mode: EditMode;
    modalRef: NgbModalRef;
    modalViewRef: NgbModalRef;
    modalDoctorRef: NgbModalRef;
    anotherModalRef: NgbModalRef;

    admission: Admission;
    selectAllSubscription: Subscription;
    departmentSubscription: Subscription;
    chargeGroupSubscription: Subscription;
    chargeSubscription: Subscription;

    providerInput = new Subject<string>();
    loadingProviders: boolean;
    provider: Observable<Array<IResource>>;
    temporaryChargeSelectedIndex: number;
    selectedLabBookingDetail: NewLabServicesModel;
    isPrintLogo: boolean;
    insuranceAdmission: InsuranceAdmission;
    buttonEnable: boolean = false;
    checkLength: any;
    loadingLab: boolean;
    roomChargeCategoryId: number;
    moduleTypeName: string;
    showLabReport: boolean;
    roomChargeCategoryName: string;
    loadingChargeCategory: boolean;
    chargeCategory: IResource;

    packageDetails: Object;
    quantityUpdate: boolean = false;
    previousPackages: Array<IAdmissionPackageModuleModel>;
    loadingOt: boolean;
    ot: SurgeryModel[];

    deletedSurgeryServices: Array<number>;
    selectedOt: SurgeryModel[];

    loadingScan: boolean;
    scan: IScanChargeModel[];

    deletedScanServices: Array<number>;
    selectedScan: IScanChargeModel[];
    chargesFilter: Array<string>;
    labsFilter: Array<string>;
    counsellings: Array<IBasicCounselling>;
    applyCounselling: boolean;
    constructor(
        private readonly httpService: HttpService,
        private readonly route: ActivatedRoute,
        private readonly appData: AppData,
        private readonly modalService: NgbModal,
        private readonly formBuilder: FormBuilder,
        private readonly notifyService: NotifyService,
        private readonly resourceService: ResourceService,
        private readonly location: Location,
    ) {
        UtilHelper.addOrRemoveLogoStyle(false, () => {
            this.isPrintLogo = false;
        })
        this.trackBy = new TrackBy();
        this.chargeRecords = new Array<NewServicesModel>();
        this.surgeryRecords = new Array<ISurgeryChargeModel>();
        this.scanRecords = new Array<IScanChargeModel>();

        this.packageDetails = new Object();

        this.packages = new Array<PackageModuleModel>();
        this.initPackagesPagination();

        this.labs = new Array<NewLabServicesModel>();
        this.ot = new Array<SurgeryModel>();
        this.scan = new Array<IScanChargeModel>();
        this.filters = new Filter();
        this.initPagination();
        this.departments = new Array<IFilterModel>();
        this.chargeGroups = new Array<IFilterModel>();
        this.charges = new Array<IFilterModel>();
        this.chargesFilter = new Array<string>();
        this.labsFilter = new Array<string>();
        this.counsellings = new Array<IBasicCounselling>();

        this.departmentsOriginal = new Array<IFilterModel>();
        this.chargeGroupsOriginal = new Array<IFilterModel>();
        this.chargesOriginal = new Array<IFilterModel>();

        this.finalBillBasics = new FinalBillBasicModel();
        this.deletedCharges = new Array<number>();
        this.deletedSurgeryServices = new Array<number>();
        this.deletedScanServices = new Array<number>();
        this.deletedLabServices = new Array<number>();
        this.deletedLabBookingHeaderIds = new Array<number>();
        this.addedIndexes = new Array<number>();
        this.deletedPharmacy = new Array<number>();
        this.deletedPackages = new Array<number>();
        this.mode = EditMode.New;
        this.serviceOrder = new ServiceOrder();
        this.serviceOrder.generalRecords = new Array<IChargeModel>();
        this.serviceOrder.surgeryServicesRecords = new Array<ISurgeryChargeModel>();
        this.serviceOrder.pharmacyIndentRecords = new Array<IPharmacyIndentModel>();
        this.serviceOrder.packageRecords = new Array<IAdmissionPackageModuleModel>();
        this.serviceOrder.labServicesRecords = new Array<NewLabServicesModel>();
        this.serviceOrder.scanServicesRecords = new Array<IScanChargeModel>();

        this.originalServiceOrder = new ServiceOrder();
        this.originalServiceOrder.generalRecords = new Array<IChargeModel>();
        this.originalServiceOrder.surgeryServicesRecords = new Array<ISurgeryChargeModel>();
        this.originalServiceOrder.pharmacyIndentRecords = new Array<IPharmacyIndentModel>();
        this.originalServiceOrder.packageRecords = new Array<IAdmissionPackageModuleModel>();
        this.originalServiceOrder.labServicesRecords = new Array<NewLabServicesModel>();
        this.originalServiceOrder.scanServicesRecords = new Array<IScanChargeModel>();

        this.previousPackages = new Array<IAdmissionPackageModuleModel>();

        this.selectedLabs = new Array<NewLabServicesModel>();
        this.loading = true;
        this.page = new Page();
        this.buildDiscountForm();
        this.buildFilterForm();
        this.buildReturnProductsForm();
        this.selectedLabBookingDetail = new NewLabServicesModel();
        this.showLabReport = false;
    }

    canDeactivate = (): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree => {
        return Observable.create((a) => {
            if (this.finalBillBasics.finalAmount === 0 &&
                (this.deletedCharges.length || this.deletedLabServices.length || this.deletedPackages.length || this.addedIndexes.length)) {
                this.notifyService.confirm("Do you want to save the changes? before leaving the page.",
                    () => {
                        this.onSubmit((status: boolean) => {
                            status && a.next(true);
                            !status && a.next(false);
                        });
                    }, () => {
                        a.next(true);
                    });

            } else {
                a.next(true);
            }
        });
    }

    private initPagination() {
        this.pagination = new Pagination();
        this.pagination.pageIndex = 1;
        this.pagination.pageSize = 8;
    }

    onChangePrintType(type: boolean) {
        UtilHelper.addOrRemoveLogoStyle(type, () => {
            this.isPrintLogo = type;
        })
    }

    private findAdmission(content: TemplateRef<any>, admissionId: number) {
        this.admission = undefined;
        this.httpService
            .get<Admission>(ApiResources.getURI(ApiResources.admissions.base, ApiResources.admissions.find), { admissionId: admissionId })
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loading = false))
            .subscribe(
                (response: Admission) => {
                    this.admission = response;

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

    onOpenIndentModel(content: TemplateRef<any>) {
        var admissionId = parseInt(this.admissionId);
        if (!this.isAdmission)
            return;
        this.findAdmission(content, admissionId);
    }

    onOpenReturnIndentModel(content: TemplateRef<any>) {
        this.serviceOrder.pharmacyIndentRecords.forEach(item => {
            item.returnQty = null;
        })

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

    onOpenLabs(content: TemplateRef<any>) {

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

        this.initPagination();
        this.filters.init();
        this.fetchLabs();
    }

    private fetchLabs() {
        this.loadingLab = true;
        const request = UtilHelper.clone(this.filters.options);
        if (this.chargeCategory != null && this.chargeCategory != undefined) {
            request["chargeCategoryId"] = this.chargeCategory.id;
        }
        else {
            request["chargeCategoryId"] = this.roomChargeCategoryId;
        }

        this.httpService.post(ApiResources.getURI(ApiResources.labs.base, ApiResources.labs.fetchLabWithCharges), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loadingLab = false))
            .subscribe(
                (response: Array<NewLabServicesModel>) => {
                    this.labs = new Array<NewLabServicesModel>();
                    var res = response;
                    res.forEach((row) => {
                        if (row.charges.length > 0)
                            this.labs.push(row)
                    });
                    this.labsFilter = this.labs.map(x => x.testName).slice();
                },
                () => {
                    this.labs = new Array<NewLabServicesModel>();
                }
            );
    }
    private fetchLabHeaders() {
        this.loadingHeader = true;
        const request = UtilHelper.clone(this.filters.options);
        this.httpService
            .post(ApiResources.getURI(ApiResources.laboratory.base, ApiResources.laboratory.fetchLab), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loadingHeader = false))
            .subscribe((response: Array<ILabServicesModel>) => {
                this.headers = response;
                if (this.serviceOrder.labServicesRecords.length > 0) {
                    this.serviceOrder.labServicesRecords.forEach((existing) => {
                        const lab = this.headers.filter((item) => { return item.labHeaderId === existing.labMainDetailId });
                        if (lab.length > 0) {
                            lab[0].isSelected = true;
                        }
                    });
                }

                UtilHelper.applyPagination(this.headers, this.pagination);
            }, () => {
                this.notifyService.error("Error occured in fetching lab.");
            });
    }

    onLabNextPage() {
        this.fetchLabHeaders();
    }

    onLabSearch() {
        this.filters.applied = UtilHelper.isFiltersApplied(this.filters.options);
        this.initPagination();
        this.fetchLabs();
    }

    onLabSearchReset() {
        this.filters.init();
        this.initPagination();
        this.fetchLabs();
    }

    onCloseReturnProductsModal() {
        try {
            this.modalRef.close();
            this.modalRef = undefined;
        } catch (e) {
        }
        this.returnPharmacyProductsForm.clear();
    }

    onLabSelect(lab?: NewLabServicesModel) {
        this.selectedLabs = new Array<NewLabServicesModel>();
        lab.selected = true;
        this.selectedLabs.push(lab);
        this.onAddLabServices();
    }

    onLabRemove(lab?: LabHeaders) {
        let index = 0;
        lab.isSelected = false;
        index = this.selectedLabs.findIndex(item => item.labMainDetailId === lab.labHeaderId);
        console.log(index);
    }

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

    ngOnInit() {
        this.appData.userAccount
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((userAccount: IUserAccount) => {
                if (userAccount) {
                    this.page.userAccount = userAccount;
                    this.route.parent.paramMap
                        .subscribe((params: Params) => {
                            this.admissionId = params["params"]["id"];
                            this.isAdmission = params["params"]["type"] === "a";

                            // Check if any previous appointments exists with package included and final bill not generated
                            // if yes we'll redirect to that appointment untill final bill is generated
                            // discussed on 26th Sept 2023 - V
                            this.fetchPreviousPackages(() => {
                                if (!this.isAdmission) {
                                    this.fetchDefaultChargeCategory();
                                }
                                this.fetchProviders();
                                this.fetchCounsellings();
                                this.addInitial(InitialType.Individual);
                                this.getFinalBillBasics(() => {
                                    if (this.finalBillBasics.finalAmount !== 0) {
                                        this.fetch();
                                    } else {
                                        this.checkIsFirstTime((status) => {
                                            if (status) {
                                                this.loading = false;
                                            } else {
                                                this.automatic(false, () => {
                                                    this.fetch();
                                                });
                                            }
                                        });
                                    }
                                });
                                this.getInsurance();
                            });
                        });
                } else {
                    this.page.userAccount = undefined;
                }
            });
    }

    applyCounsellingFc = (model: IBasicCounselling) => {
        this.applyCounselling = true;
        var data = {
            id: model.counsellingId.toString(),
            admissionId: +this.admissionId,
            isAdmission: this.isAdmission,
            createdBy: this.page.userAccount.accountId
        };
        this.httpService
            .post(ApiResources.getURI(ApiResources.serviceOrder.base, ApiResources.serviceOrder.applyCounsellings), data)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.applyCounselling = false))
            .subscribe((response: GenericResponse) => {
                if(response.status === GenericStatus[GenericStatus.Success]) {
                    this.counsellings = response.data as Array<IBasicCounselling>;
                    this.fetchCounsellings();
                    this.fetch();
                } else {
                    this.notifyService.defaultError();
                }
            });

    }

    onOpenSpecialDoctorModel(content: TemplateRef<any>) {
        this.modalDoctorRef = this.modalService.open(content, {
            backdrop: "static",
            keyboard: false,
            centered: true,
            size: "sm",
            windowClass: "custom-modal effect-scale"
        });
    }
    private fetchDefaultChargeCategory() {
        this.loadingChargeCategory = true;
        this.resourceService.defaultChargeCategory()
            .pipe(finalize(() => { this.loadingChargeCategory = false }))
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: any) => {
                this.chargeCategory = response;
                if (this.chargeCategory != null && this.chargeCategory != undefined) {
                    this.roomChargeCategoryId = this.chargeCategory.id;
                    this.roomChargeCategoryName = this.chargeCategory.value;
                }
            });
    }

    onCloseSpecialDoctorModal() {
        try {
            this.modalDoctorRef.close();
            this.modalDoctorRef = undefined;
        } catch (e) {
        }

        this.selectedPackage = null;
    }

    addInitial = (initialType: InitialType) => {
        if (initialType === InitialType.Individual) {
            this.isFirstTime = false;
            this.loading = true;
            this.automatic(true, () => {
                this.fetch();
            });
        }
    }

    ngOnDestroy() {
        this.page.unSubscribe.next();
        this.page.unSubscribe.complete();
        this.selectAllSubscription.unsubscribe();
        this.departmentSubscription.unsubscribe();
        this.chargeGroupSubscription.unsubscribe();
        this.chargeSubscription.unsubscribe();
    }

    onBack = () => {
        this.location.back();
    }

    private buildReturnProductsForm = () => {
        this.returnProductsForm = this.formBuilder.group({
            returnProducts: this.formBuilder.array([])
        });
    }

    get returnPharmacyProductsForm() {
        return this.returnProductsForm.get("returnProducts") as FormArray;
    }

    get formSelected() { return this.chargeFilterForm.get("selected") as FormArray; };

    private buildDiscountForm() {
        this.discountForm = this.formBuilder.group({
            services: this.formBuilder.array([]),
            labs: this.formBuilder.array([]),
        });
    }

    private buildFilterForm() {
        this.chargeFilterForm = this.formBuilder.group({
            department: [null],
            chargeGroup: [null],
            charge: [null],
            selectAll: [false],
            selected: this.formBuilder.array([])
        });

        this.selectAllSubscription = this.chargeFilterForm.get("selectAll").valueChanges.subscribe((value: boolean) => {
            const formArrayValues = this.formSelected.value as Array<any>;
            if (this.chargeRecords.length) {
                const shownChargeIds = this.chargeRecords.map(x => x.chargeId);
                formArrayValues.forEach(item => {
                    if (shownChargeIds.find(x => x === item.chargeId)) {
                        item.status = value;
                    }
                });

                this.chargeFilterForm.patchValue({
                    selected: formArrayValues
                });
            }
            const formArrayValues1 = this.formSelected.value as Array<any>;
            var data = formArrayValues1.filter(m => m.status === true);
            if (data.length > 0) {
                this.checkLength = data.length
                this.buttonEnable = true;
            }
            else {
                this.buttonEnable = false;
            }
        });

        this.departmentSubscription = this.chargeFilterForm.get("department").valueChanges.subscribe((value: string | null) => {
            this.onFilterDepartment(value);
        });

        this.chargeGroupSubscription = this.chargeFilterForm.get("chargeGroup").valueChanges.subscribe((value: string | null) => {
            this.onFilterChargeGroup(value);
        });

        this.chargeSubscription = this.chargeFilterForm.get("charge").valueChanges.subscribe((_: string | null) => {
            this.chargeFilter();
            // this.onFilterCharge(value);
        });
    }

    onFilterDepartment = (record: string) => {
        this.chargeGroups = LinqHelper.cloneDeepArray<IFilterModel>(this.chargeGroupsOriginal.filter(x => !record ? true : x.departmentName.indexOf(record) !== -1).filter(LinqHelper.uniqueOnlyBy));
        this.charges = LinqHelper.cloneDeepArray<IFilterModel>(this.chargesOriginal.filter(x => !record ? true : x.departmentName.indexOf(record) !== -1).filter(LinqHelper.uniqueOnlyBy));
    }

    onFilterChargeGroup = (record: string) => {
        this.charges = LinqHelper.cloneDeepArray<IFilterModel>(this.chargesOriginal.filter(x => !record ? true : x.chargeGroupName.indexOf(record) !== -1).filter(LinqHelper.uniqueOnlyBy));
        this.departments = LinqHelper.cloneDeepArray<IFilterModel>(this.departmentsOriginal.filter(x => !record ? true : x.chargeGroupName.indexOf(record) !== -1).filter(LinqHelper.uniqueOnlyBy));
    }

    onFilterCharge = (record: string) => {
        this.chargeGroups = LinqHelper.cloneDeepArray<IFilterModel>(this.chargeGroupsOriginal.filter(x => !record ? true : x.chargeName.indexOf(record) !== -1).filter(LinqHelper.uniqueOnlyBy));
        this.departments = LinqHelper.cloneDeepArray<IFilterModel>(this.departmentsOriginal.filter(x => !record ? true : x.chargeName.indexOf(record) !== -1).filter(LinqHelper.uniqueOnlyBy));
    }

    uniqueOnly = (value, index, self) => {
        return self.indexOf(value) === index;
    }

    onChargeSelected = () => {
        const formArrayValues = this.formSelected.value as Array<any>;
        var unique = formArrayValues.map(x => x.status).filter(this.uniqueOnly);

        var data = formArrayValues.filter(m => m.status === true);
        if (data.length > 0) {
            this.checkLength = data.length
            this.buttonEnable = true;
        }
        else {
            this.buttonEnable = false;
            this.chargeFilterForm.patchValue({
                selectAll: unique.length === 1 ? unique[0] : false
            });
        }
        const compressed = JSON.stringify(formArrayValues);

        this.chargeFilterForm.patchValue({
            selected: JSON.parse(compressed)
        });
    }

    onSelectSpecialDoctor = (index: number, templateSelectSpecialDoctor: TemplateRef<any>) => {
        if (this.chargeRecords[index].chargeTypeId === ChargeType.Special) {
            this.temporaryChargeSelectedIndex = index;
            this.onOpenSpecialDoctorModel(templateSelectSpecialDoctor);
        }
    }

    onSpecialDoctorSelected = ($event: any) => {
        this.chargeRecords[this.temporaryChargeSelectedIndex].chargeTypeMainName = $event.value;
        this.chargeRecords[this.temporaryChargeSelectedIndex].chargeTypeMainId = $event.id;
        this.chargeRecords[this.temporaryChargeSelectedIndex].cost = $event.cost || 0;
    }

    removeCharge = (index: number) => {

        if (this.serviceOrder.generalRecords[index].serviceOrderId) {
            this.deletedCharges.push(this.serviceOrder.generalRecords[index].serviceOrderId);
            this.serviceOrder.generalRecords[index].active = false;
        }

        if (!this.serviceOrder.generalRecords[index].serviceOrderId) {
            this.serviceOrder.generalRecords.splice(index, 1);
            this.addedIndexes = this.addedIndexes.filter(x => x !== index);
            (this.discountForm.get("services") as FormArray).removeAt(index);
        }

        this.serviceOrder.generalTotal = this.serviceOrder.generalRecords.filter(x => x.active).map((x, index) => {
            x.totalCost = x.cost * x.unit;
            this.onDiscount(index, 'S', false);
            return x.totalCost;
        }).reduce((a, b) => a + b, 0);
    }

    removeLabService = (index: number) => {
        if (this.serviceOrder.labServicesRecords[index].labServicesId) {
            this.deletedLabServices.push(this.serviceOrder.labServicesRecords[index].labServicesId);
            this.serviceOrder.labServicesRecords[index].active = false;
            if (this.serviceOrder.labServicesRecords[index].newLabBookingHeaderId)
                this.deletedLabBookingHeaderIds.push(this.serviceOrder.labServicesRecords[index].newLabBookingHeaderId);
        }
        //if (this.serviceOrder.labServicesRecords[index].admissionPackageId == 0) {
        if (!this.serviceOrder.labServicesRecords[index].labServicesId) {
            this.serviceOrder.labServicesRecords.splice(index, 1);
            this.addedIndexes = this.addedIndexes.filter(x => x !== index);
        }

        this.serviceOrder.labServicesTotal = this.serviceOrder.labServicesRecords.filter(x => x.active).map((x, index) => {
            x.totalCost = x.cost * x.unit;
            this.onDiscount(index, 'L', false);
            return x.totalCost;
        }).reduce((a, b) => a + b, 0);
    }

    removePharmacy = (index: number) => {

        if (this.serviceOrder.pharmacyIndentRecords[index].pharmacyIssueDetailId) {
            this.deletedPharmacy.push(this.serviceOrder.pharmacyIndentRecords[index].pharmacyIssueDetailId);
        }

        this.serviceOrder.pharmacyIndentRecords.splice(index, 1);
        this.serviceOrder.pharmacyIndentTotal = this.serviceOrder.pharmacyIndentRecords.filter(x => x.showAmount).map(x => (x.cost * x.unit) - x.discountAmount)
            .reduce((a, b) => a + b, 0);
    }

    onOpenModel(content: TemplateRef<any>, initialType: InitialType) {
        if (this.finalBillBasics.finalAmount !== 0) {
            this.notifyService.infoToast("Service orders can not be added once the final bill is generated, please cancel the Final Bill and try again.");
            return;
        }

        if (initialType === InitialType.Individual) {
            this.resetAutocomplete();
            this.formSelected.clear();
            this.chargeFilterForm.patchValue({
                selectAll: false
            });
            this.isChargesLoading = true;
            this.openModalHelper(content);
            setTimeout(() => {
                if (!this.departmentsOriginal.length) {
                    this.fetchMasters(() => {
                        this.fetchServicesCharges();
                    });
                } else {
                    this.fetchServicesCharges();
                }
            });
        } else {
            this.modalRef = this.modalService.open(content, {
                backdrop: "static",
                keyboard: false,
                centered: true,
                size: "xl",
                windowClass: "custom-modal effect-scale"
            });
            this.loadingPackages = true;
            setTimeout(() => {
                this.initPackagesPagination();
                this.fetchPackages();
            });
        }
    }

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

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

        this.initPagination();
        this.initPackagesPagination();
        this.submitting = undefined;
        this.submitted = undefined;
        this.clearChargeFilter();
    }

    resetAutocomplete = () => {
        this.departments = LinqHelper.cloneDeepArray<IFilterModel>(this.departmentsOriginal.filter(LinqHelper.uniqueOnlyBy));
        this.chargeGroups = LinqHelper.cloneDeepArray<IFilterModel>(this.chargeGroupsOriginal.filter(LinqHelper.uniqueOnlyBy));
        this.charges = LinqHelper.cloneDeepArray<IFilterModel>(this.chargesOriginal.filter(LinqHelper.uniqueOnlyBy));
    }

    clearChargeFilter = () => {
        this.chargeFilterForm.patchValue({
            department: null,
            chargeGroup: null,
            charge: null,
        });

        this.isChargesLoading = true;
        this.formSelected.clear();
        setTimeout(() => {
            this.fetchServicesCharges();
        });
    }

    chargeFilter = () => {
        this.isChargesLoading = true;
        this.formSelected.clear();
        setTimeout(() => {
            this.fetchServicesCharges();
        });
    }

    getFinalBillBasics = (callback?: Function) => {
        this.httpService
            .post<GenericResponse>(ApiResources.getURI(ApiResources.finalBill.base, ApiResources.finalBill.getBasics), { id: this.admissionId, isAdmission: this.isAdmission })
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.isChargesLoading = false))
            .subscribe(
                (response: GenericResponse) => {
                    this.finalBillBasics = response.data as FinalBillBasicModel;
                    callback && callback();
                },
                () => {
                    this.finalBillBasics = new FinalBillBasicModel();
                    callback && callback();
                }
            );
    }

    cloneDeepArray = (data: Array<any>) => {
        const newData = data.map(x => ({ ...x }));
        return newData;
    }

    fetchMasters = (callback?: Function) => {
        this.httpService
            .post<GenericResponse>(ApiResources.getURI(ApiResources.chargeManagement.base, ApiResources.chargeManagement.masters), {})
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loading = false))
            .subscribe(
                (response: GenericResponse) => {
                    const data = response.data as Array<IChargeModel>;
                    this.departmentsOriginal = data.map((x) => ({ chargeGroupName: x.chargeGroupName, chargeName: x.chargeName, id: x.departmentId, name: x.departmentName })) as Array<IFilterModel>;
                    this.departments = LinqHelper.cloneDeepArray<IFilterModel>(this.departmentsOriginal.filter(LinqHelper.uniqueOnlyBy));

                    this.chargeGroupsOriginal = data.map((x) => ({ departmentId: x.departmentId, departmentName: x.departmentName, chargeName: x.chargeName, id: x.chargeGroupId, name: x.chargeGroupName })) as Array<IFilterModel>;
                    this.chargeGroups = LinqHelper.cloneDeepArray<IFilterModel>(this.chargeGroupsOriginal.filter(LinqHelper.uniqueOnlyBy));

                    this.chargesOriginal = data.map((x) => ({ departmentName: x.departmentName, chargeGroupId: x.chargeGroupId, chargeGroupName: x.chargeGroupName, id: x.chargeId, name: x.chargeName })) as Array<IFilterModel>;
                    this.charges = LinqHelper.cloneDeepArray<IFilterModel>(this.chargesOriginal.filter(LinqHelper.uniqueOnlyBy));

                    callback && callback();
                },
                () => {
                    callback && callback();
                }
            );
    }

    onNextPage = () => {
        if ((this.formSelected.value as Array<any>).filter(x => x.status).length) {
            this.notifyService.confirm("Do you want to add selected services before leaving this page?",
                () => {
                    this.onAddCharges(false);
                    this.formSelected.clear();
                    this.fetchServicesCharges();
                }, () => {
                    this.formSelected.clear();
                    this.fetchServicesCharges();
                });
        } else {
            this.formSelected.clear();
            this.fetchServicesCharges();
        }
    }

    fetchCharges = () => {
        const data = {
            ...this.chargeFilterForm.value,
            pageIndex: this.pagination.pageIndex,
            pageSize: this.pagination.pageSize
        }
        this.httpService
            .post<GenericResponse>(ApiResources.getURI(ApiResources.chargeManagement.base, ApiResources.chargeManagement.fetch), data)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.isChargesLoading = false))
            .subscribe(
                (response: GenericResponse) => {
                    const data = response.data as Array<NewServicesModel>;
                    data.forEach(item => {

                        this.formSelected.push(
                            this.formBuilder.group({
                                chargeId: [item.chargeId],
                                status: [false],
                                unit: [item.repeatTypeId === RepeatType.Day ? this.noOfDays : 1]
                            }));

                        if (!this.isAdmission) {
                            item.cost = item.opCost;
                        }

                        if (item.automaticTypeId === AutomaticType.BedCharges) {
                            item.cost = this.bedCost;
                        }

                        if (item.automaticTypeId === AutomaticType.DoctorCharges) {
                            item.cost = this.doctorCost;
                        }

                        if (item.chargeTypeId === ChargeType.Covid) {
                            item.cost = this.covidCost;
                        }
                    });

                    this.chargeRecords = data;
                    UtilHelper.applyPagination(this.chargeRecords, this.pagination);
                },
                () => {
                    this.chargeRecords = new Array<NewServicesModel>();
                }
            );
    }

    fetchServicesCharges = () => {
        const data = {
            ...this.chargeFilterForm.value
        }
        if (this.chargeCategory != null && this.chargeCategory != undefined) {
            data["chargeCategoryId"] = this.chargeCategory.id;
        }
        else {
            data["chargeCategoryId"] = this.roomChargeCategoryId;
        }
        this.httpService
            .post<GenericResponse>(ApiResources.getURI(ApiResources.chargeManagement.base, ApiResources.chargeManagement.fetchWithCharges), data)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.isChargesLoading = false))
            .subscribe(
                (response: any) => {
                    var res1 = response as Array<NewServicesModel>;
                    var res2 = new Array<NewServicesModel>();
                    res1.forEach((item) => {
                        if (item.charges.length > 0) {
                            res2.push(item);
                        }
                    });
                    this.chargeRecords = new Array<NewServicesModel>();
                    this.chargeRecords = res2;
                    const data = this.chargeRecords as Array<NewServicesModel>;
                    this.departmentsOriginal = data.map((x) => ({ chargeGroupName: x.chargeGroupName, chargeName: x.chargeName, id: x.departmentId, name: x.departmentName })) as Array<IFilterModel>;
                    this.departments = LinqHelper.cloneDeepArray<IFilterModel>(this.departmentsOriginal.filter(LinqHelper.uniqueOnlyBy));

                    this.chargeGroupsOriginal = data.map((x) => ({ departmentId: x.departmentId, departmentName: x.departmentName, chargeName: x.chargeName, id: x.chargeGroupId, name: x.chargeGroupName })) as Array<IFilterModel>;
                    this.chargeGroups = LinqHelper.cloneDeepArray<IFilterModel>(this.chargeGroupsOriginal.filter(LinqHelper.uniqueOnlyBy));

                    this.chargesOriginal = data.map((x) => ({ departmentName: x.departmentName, chargeGroupId: x.chargeGroupId, chargeGroupName: x.chargeGroupName, id: x.chargeId, name: x.chargeName })) as Array<IFilterModel>;
                    this.charges = LinqHelper.cloneDeepArray<IFilterModel>(this.chargesOriginal.filter(LinqHelper.uniqueOnlyBy));
                    this.chargesFilter = this.chargesOriginal.map(x => x.name).slice();
                    data.forEach(item => {
                        this.formSelected.push(
                            this.formBuilder.group({
                                chargeId: [item.chargeId],
                                status: [false],
                                unit: [item.repeatTypeId === RepeatType.Day ? this.noOfDays : 1]
                            }));

                        if (!this.isAdmission) {
                            item.cost = item.opCost;
                        }

                        if (item.automaticTypeId === AutomaticType.BedCharges) {
                            item.cost = this.bedCost;
                        }

                        if (item.automaticTypeId === AutomaticType.DoctorCharges) {
                            item.cost = this.doctorCost;
                        }

                        if (item.chargeTypeId === ChargeType.Covid) {
                            item.cost = this.covidCost;
                        }
                    });

                    this.chargeRecords = data;
                    UtilHelper.applyPagination(this.chargeRecords, this.pagination);
                },
                () => {
                    this.chargeRecords = new Array<NewServicesModel>();
                }
            );
    }

    resetHelper = () => {
        this.deletedCharges = new Array<number>();
        this.deletedLabServices = new Array<number>();
        this.deletedLabBookingHeaderIds = new Array<number>();
        this.deletedPharmacy = new Array<number>();
        this.deletedPackages = new Array<number>();
        this.fetch();
        this.quantityUpdate = false;
    }

    automatic = (byPass: boolean = false, callback?: Function) => {
        var data = {
            id: this.admissionId,
            isAdmission: this.isAdmission,
            createdBy: this.page.userAccount.accountId,
            byPass: byPass
        };
        this.httpService
            .post(ApiResources.getURI(ApiResources.serviceOrder.base, ApiResources.serviceOrder.automatic), data)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loading = false))
            .subscribe(() => {
                callback();
            }, () => {
                callback();
            });
    }

    fetchCounsellings = () => {
        var data = {
            id: this.admissionId,
            isAdmission: this.isAdmission,
        };
        this.httpService
            .post(ApiResources.getURI(ApiResources.serviceOrder.base, ApiResources.serviceOrder.fetchCounsellings), data)
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: GenericResponse) => {
                if(response.status === GenericStatus[GenericStatus.Success]) {
                    this.counsellings = response.data as Array<IBasicCounselling>;
                }
            });
    }

    checkIsFirstTime = (callback?: Function) => {
        var data = {
            id: this.admissionId,
            isAdmission: this.isAdmission
        };
        this.httpService
            .post<GenericResponse>(ApiResources.getURI(ApiResources.serviceOrder.base, ApiResources.serviceOrder.isFirst), data)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loading = false))
            .subscribe((response: GenericResponse) => {
                if (response.status === GenericStatus[GenericStatus.Success]) {
                    callback && callback(true);
                } else {
                    callback && callback(false);
                }
            }, () => {
                callback && callback(false);
            });
    }

    fetchPreviousPackages = (callback?: Function) => {
        var data = {
            id: this.admissionId,
            isAdmission: this.isAdmission
        };
        this.httpService
            .post<GenericResponse>(ApiResources.getURI(ApiResources.serviceOrder.base, ApiResources.serviceOrder.getPreviousPackages), data)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loading = false))
            .subscribe((response: GenericResponse) => {
                this.previousPackages = response.data;
                callback && callback();
            }, () => {
                callback && callback();
            });
    }

    attachTypeValue = (index: number, category: string) => {
        switch(category) {
            case 'S':
                let form = (this.discountForm.get("services") as FormArray).at(index);
                let serviceOrder = this.serviceOrder.generalRecords[index];
                serviceOrder.discountType = form.value.discountType as DiscountType;
                serviceOrder.totalCost = serviceOrder.unit * serviceOrder.cost;
                serviceOrder.discount = null;
                serviceOrder.discountPercentage = null;
                serviceOrder.discountAmount = null;
                form.patchValue({
                    discount: null
                });
                break;
            case 'L':
                let _form = (this.discountForm.get("labs") as FormArray).at(index);
                let labOrder = this.serviceOrder.labServicesRecords[index];
                labOrder.discountType = _form.value.discountType as DiscountType;
                labOrder.totalCost = labOrder.unit * labOrder.cost;
                labOrder.discount = null;
                labOrder.discountPercentage = null;
                labOrder.discountAmount = null;
                _form.patchValue({
                    discount: null
                });
                break;
        }
        this.onDiscount(index, category);
    }

    attachDiscountValue = (index: number, category: string) => {
        switch(category) {
            case 'S':
                let form = (this.discountForm.get("services") as FormArray).at(index);
                let serviceOrder = this.serviceOrder.generalRecords[index];
                if(form.value.discountType as DiscountType === DiscountType.Percentage) {
                    serviceOrder.discountPercentage = form.value.discount;
                    if(form.value.discount >= 0 && form.value.discount <= 100) {
                        serviceOrder.discountPercentage = form.value.discount;
                    } else {
                        this.notifyService.warning("Discount % must be greater than 0 and less than or equal to 100%", () => {
                            serviceOrder.totalCost = serviceOrder.unit * serviceOrder.cost;
                            form.patchValue({
                                discount: null
                            });
                        });
                    }
                }
                if(form.value.discountType as DiscountType === DiscountType.Number) {
                    if(form.value.discount >= 0 && form.value.discount <= (serviceOrder.unit * serviceOrder.cost)) {
                        serviceOrder.discountAmount = form.value.discount;
                    } else {
                        this.notifyService.warning("Discount amount must be greater than 0 and less than or equal to " + (serviceOrder.unit * serviceOrder.cost), () => {
                            serviceOrder.totalCost = serviceOrder.unit * serviceOrder.cost;
                            form.patchValue({
                                discount: null
                            });
                        });
                    }
                }
                break;
            case 'L':
                let _form = (this.discountForm.get("labs") as FormArray).at(index);
                let labOrder = this.serviceOrder.labServicesRecords[index];
                if(_form.value.discountType as DiscountType === DiscountType.Percentage) {
                    if(_form.value.discount >= 0 && _form.value.discount <= 100) {
                        labOrder.discountPercentage = _form.value.discount;
                    } else {
                        this.notifyService.warning("Discount % must be greater than 0 and less than or equal to 100%", () => {
                            labOrder.totalCost = labOrder.unit * labOrder.cost;
                            _form.patchValue({
                                discount: null
                            });
                        });
                    }
                }
                if(_form.value.discountType as DiscountType === DiscountType.Number) {
                    if(_form.value.discount >= 0 && _form.value.discount <= (labOrder.unit * labOrder.cost)) {
                        labOrder.discountAmount = _form.value.discount;
                    } else {
                        this.notifyService.warning("Discount amount must be greater than 0 and less than or equal to " + (labOrder.unit * labOrder.cost), () => {
                            labOrder.totalCost = labOrder.unit * labOrder.cost;
                            _form.patchValue({
                                discount: null
                            });
                        });
                    }
                }
                break;
        }
        this.onDiscount(index, category);
    }

    onDiscount = (index:number, category: string, isCalculateTotals: boolean = true) => {
        switch(category) {
            case 'S':
                let serviceOrder = this.serviceOrder.generalRecords[index];
                serviceOrder.discount = 0;
                if(serviceOrder.totalCost && serviceOrder.discountType && (serviceOrder.discountAmount || serviceOrder.discountPercentage)) {
                    serviceOrder.discount = serviceOrder.discountType === DiscountType.Number 
                        ? (serviceOrder.discountAmount || 0)
                        : serviceOrder.totalCost * ((serviceOrder.discountPercentage || 0) * 0.01);

                    serviceOrder.totalCost = serviceOrder.totalCost >= serviceOrder.discount 
                        ? serviceOrder.totalCost - serviceOrder.discount 
                        : 0;
                }
                break;
            case 'L':
                let labsOrder = this.serviceOrder.labServicesRecords[index];
                labsOrder.discount = 0;
                if(labsOrder.totalCost && labsOrder.discountType && (labsOrder.discountAmount || labsOrder.discountPercentage)) {
                    labsOrder.discount = labsOrder.discountType === DiscountType.Number 
                        ? (labsOrder.discountAmount || 0)
                        : labsOrder.totalCost * ((labsOrder.discountPercentage || 0) * 0.01);

                        labsOrder.totalCost = labsOrder.totalCost >= labsOrder.discount 
                            ? labsOrder.totalCost - labsOrder.discount 
                            : 0;
                }
                break;
        }
        if(isCalculateTotals) {
            this.calculateTotals();
        }
    }

    fetch = () => {
        this.httpService
            .post<GenericResponse>(ApiResources.getURI(ApiResources.serviceOrder.base, ApiResources.serviceOrder.fetch), { id: this.admissionId, isAdmission: this.isAdmission, activeOnly: false, isDischarged: true, active: true })
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loading = false))
            .subscribe(
                (response: GenericResponse) => {
                    if(response.status === GenericStatus[GenericStatus.Success]) {
                        if (response && response.data) {
                            this.noOfDays = response.data["noOfDays"] ? response.data["noOfDays"] as number : undefined;
                            this.bedCost = response.data["bedCost"] ? response.data["bedCost"] as number : undefined;
                            this.doctorCost = response.data["doctorCost"] ? response.data["doctorCost"] as number : undefined;
                            this.covidCost = response.data["covidCost"] ? response.data["covidCost"] as number : undefined;
                            this.moduleTypeName = response.data["moduleTypeName"];
                            this.roomChargeCategoryId = response.data["roomChargeCategoryId"] ? response.data["roomChargeCategoryId"] as number : undefined;
                            this.roomChargeCategoryName = response.data["chargeCategoryName"];
                            if (!this.chargeCategory) {
                                this.chargeCategory = { id: this.roomChargeCategoryId, value: this.roomChargeCategoryName } as IResource;
                            }
                            
                            let servicesForm = this.discountForm.get("services") as FormArray;
                            servicesForm.clear();

                            // General Records
                            const generalRecords = response.data["generalRecords"] ? response.data["generalRecords"] as Array<any> : new Array();
                            if (generalRecords.length > 0) {
                                const generalSubRecords = new Array<IChargeModel>();
                                generalRecords.forEach((item, index) => {
                                    let discountType = item.discountType === "A" 
                                        ? DiscountType.Number : item.discountType === "P" ? DiscountType.Percentage : null;
                                    servicesForm.push(this.formBuilder.group({
                                        index: new FormControl(index),
                                        id: new FormControl(item.serviceOrderId),
                                        discountType: new FormControl({value: discountType, disabled: true}),
                                        discount: new FormControl({value: item.discount || null, disabled: true})
                                    }))
                                    generalSubRecords.push({
                                        serviceOrderId: item.serviceOrderId,
                                        chargeId: item.chargeId,
                                        cost: item.cost,
                                        chargeName: item.chargeName,
                                        modulesMasterId: item.modulesMasterId,
                                        chargeGroupName: item.chargeGroupName,
                                        departmentName: item.departmentName,
                                        unit: item.unit,
                                        totalCost: item.cost * item.unit,
                                        status: true,
                                        repeatTypeId: item.repeatTypeId,
                                        automaticTypeId: item.automaticTypeId,
                                        active: item.active,
                                        createdDate: item.createdDate,
                                        modifiedDate: item.modifiedDate,
                                        createdByName: item.createdByName,
                                        modifiedByName: item.modifiedByName,
                                        isMain: item.isMain,
                                        chargeTypeMainId: item.chargeTypeMainId,
                                        chargeTypeMainName: item.chargeTypeMainName,
                                        chargeTypeId: item.chargeTypeId,
                                        showAmount: true,
                                        isInPackage: item.admissionPackageId > 0,
                                        admissionPackageId: item.admissionPackageId,
                                        packageModuleDetailId: item.packageModuleDetailId,
                                        usedCost: item.usedCost,
                                        usedQuantity: item.usedQuantity,
                                        discountType: item.discountType === 'A' ? DiscountType.Number : item.discountType === 'P' ? DiscountType.Percentage: null,
                                        discountAmount: item.discountAmount,
                                        discountPercentage: item.discountPercentage,
                                        discount: item.discount
                                    } as IChargeModel);
                                });
    
                                this.serviceOrder.generalRecords = generalSubRecords;
                                this.originalServiceOrder.generalRecords = LinqHelper.cloneDeep(generalSubRecords);
                                this.serviceOrder.generalTotal = generalSubRecords.filter(x => x.active).map((x, index) => {
                                    x.totalCost = x.cost * x.unit;
                                    this.onDiscount(index, 'S');
                                    return x.totalCost;
                                }).reduce((a, b) => a + b, 0);
    
                                this.mode = EditMode.Edit;
                            } else {
                                this.serviceOrder.generalRecords = new Array<IChargeModel>();
                                this.serviceOrder.generalTotal = 0;
                            }

                            let labsForm = this.discountForm.get("labs") as FormArray;
                            labsForm.clear();
    
                            // Lab Services Records
                            const labServices = response.data["labServices"] ? response.data["labServices"] as Array<any> : new Array();
                            if (labServices.length > 0) {
                                const labServicesSubRecords = new Array<NewLabServicesModel>();
                                labServices.forEach((item, index) => {
                                    let discountType = item.discountType === "A" 
                                        ? DiscountType.Number : item.discountType === "P" ? DiscountType.Percentage : null;
                                    labsForm.push(this.formBuilder.group({
                                        index: new FormControl(index),
                                        id: new FormControl(item.labServicesId),
                                        discountType: new FormControl({value: discountType, disabled: true}),
                                        discount: new FormControl({value: item.discount || null, disabled: true})
                                    }))
                                    labServicesSubRecords.push({
                                        labServicesId: item.labServicesId,
                                        labMainDetailId: item.labMainDetailId,
                                        cost: item.cost,
                                        modulesMasterId: item.modulesMasterId,
                                        testName: item.testName,
                                        testCode: item.testCode,
                                        unit: item.unit,
                                        totalCost: item.cost * item.unit,
                                        status: true,
                                        repeatTypeId: item.repeatTypeId,
                                        automaticTypeId: item.automaticTypeId,
                                        active: item.active,
                                        createdDate: item.createdDate,
                                        modifiedDate: item.modifiedDate,
                                        createdByName: item.createdByName,
                                        modifiedByName: item.modifiedByName,
                                        isMain: item.isMain,
                                        showAmount: true,
                                        newLabBookingHeaderId: item.newLabBookingHeaderId,
                                        newLabBookingDetailId: item.newLabBookingDetailId,
                                        labStatus: item.labStatus,
                                        isReportGenerated: item.isReportGenerated,
                                        isSampleCollected: item.isSampleCollected,
                                        reportDate: item.reportDate,
                                        admissionPackageId: item.admissionPackageId,
                                        packageModuleDetailId: item.packageModuleDetailId,
                                        usedCost: item.usedCost,
                                        usedQuantity: item.usedQuantity,
                                        discountType: item.discountType === 'A' ? DiscountType.Number : item.discountType === 'P' ? DiscountType.Percentage: null,
                                        discountAmount: item.discountAmount,
                                        discountPercentage: item.discountPercentage,
                                        discount: item.discount
                                    } as unknown as NewLabServicesModel);
                                });
    
                                this.serviceOrder.labServicesRecords = labServicesSubRecords;
                                this.originalServiceOrder.labServicesRecords = LinqHelper.cloneDeep(labServicesSubRecords);
                                this.serviceOrder.labServicesTotal = labServicesSubRecords.filter(x => x.active).map((x, index) => {
                                    x.totalCost = x.cost * x.unit;
                                    this.onDiscount(index, 'L');
                                    return x.totalCost;
                                }).reduce((a, b) => a + b, 0);
    
                                this.mode = EditMode.Edit;
                            } else {
                                this.serviceOrder.labServicesRecords = new Array<NewLabServicesModel>();
                                this.serviceOrder.labServicesTotal = 0;
                            }
    
                            // Pharmacy Indent Records
                            const pharmacyIndentRecords = response.data["pharmacyIndentRecords"] ? response.data["pharmacyIndentRecords"] as Array<any> : new Array();
                            if (pharmacyIndentRecords.length > 0) {
                                const pharmacySubRecords = new Array<IPharmacyIndentModel>();
                                pharmacyIndentRecords.forEach(item => {
                                    pharmacySubRecords.push({
                                        pharmacyIssueDetailId: item.pharmacyIssueDetailId,
                                        cost: item.cost,
                                        unit: item.unit,
                                        categoryName: item.categoryName,
                                        departmentName: item.departmentName,
                                        productId: item.productId,
                                        productName: item.productName,
                                        totalCost: item.cost * item.unit,
                                        discountAmount: (item.cost * item.unit) * item.discountPercentage / 100,
                                        discountPercentage: item.discountPercentage,
                                        status: true,
                                        active: true,
                                        createdDate: item.createdDate,
                                        modifiedDate: item.modifiedDate,
                                        createdByName: item.createdByName,
                                        modifiedByName: item.modifiedByName,
                                        showAmount: true
                                    } as IPharmacyIndentModel);
                                });
    
                                this.serviceOrder.pharmacyIndentRecords = pharmacySubRecords;
                                this.originalServiceOrder.pharmacyIndentRecords = pharmacySubRecords;
                                this.serviceOrder.pharmacyIndentTotal = pharmacySubRecords.filter(x => x.showAmount).map(x => (x.cost * x.unit) - x.discountAmount)
                                    .reduce((a, b) => a + b, 0);
    
                            } else {
                                this.serviceOrder.pharmacyIndentRecords = new Array<IPharmacyIndentModel>();
                                this.serviceOrder.pharmacyIndentTotal = 0;
                            }

                            //Operation Theater
                            const surgeryServiceRecords = response.data["surgeryServiceRecords"] ? response.data["surgeryServiceRecords"] as Array<any> : new Array();
                            if (surgeryServiceRecords.length > 0) {
                                const surgeryServiceSubRecords = new Array<ISurgeryChargeModel>();
                                surgeryServiceRecords.forEach(item => {
                                    surgeryServiceSubRecords.push({
                                        surgeryServiceId: item.surgeryServiceId,
                                        chargeId: item.chargeId,
                                        cost: item.cost,
                                        chargeName: item.chargeName,
                                        modulesMasterId: item.modulesMasterId,
                                        chargeGroupName: item.chargeGroupName,
                                        departmentName: item.departmentName,
                                        unit: item.unit,
                                        totalCost: item.cost * item.unit,
                                        status: true,
                                        repeatTypeId: item.repeatTypeId,
                                        automaticTypeId: item.automaticTypeId,
                                        active: item.active,
                                        createdDate: item.createdDate,
                                        modifiedDate: item.modifiedDate,
                                        createdByName: item.createdByName,
                                        modifiedByName: item.modifiedByName,
                                        isMain: item.isMain,
                                        chargeTypeMainId: item.chargeTypeMainId,
                                        chargeTypeMainName: item.chargeTypeMainName,
                                        chargeTypeId: item.chargeTypeId,
                                        showAmount: true,
                                        isInPackage: item.admissionPackageId > 0,
                                        admissionPackageId: item.admissionPackageId,
                                        packageModuleDetailId: item.packageModuleDetailId,
                                        usedCost: item.usedCost,
                                        usedQuantity: item.usedQuantity,
                                        chargeCategoryName: item.chargeCategoryName,
                                        chargeCategoryId: item.chargeCategoryId,
                                        surgeryId: item.surgeryId,
                                        name: item.name
                                    } as ISurgeryChargeModel);
                                });
    
                                this.serviceOrder.surgeryServicesRecords = surgeryServiceSubRecords;
                                this.originalServiceOrder.surgeryServicesRecords = LinqHelper.cloneDeep(surgeryServiceSubRecords);
                                this.serviceOrder.surgeryServicesTotal = surgeryServiceSubRecords.filter(x => x.active).map(x => x.cost * x.unit).reduce((a, b) => a + b, 0);
    
                                this.mode = EditMode.Edit;
                            } else {
                                this.serviceOrder.surgeryServicesRecords = new Array<ISurgeryChargeModel>();
                                this.serviceOrder.surgeryServicesTotal = 0;
                            }
    
                            //Scan Services
                            const scanServiceRecords = response.data["scanServiceRecords"] ? response.data["scanServiceRecords"] as Array<any> : new Array();
                            if (scanServiceRecords.length > 0) {
                                const scanServiceSubRecords = new Array<IScanChargeModel>();
                                scanServiceRecords.forEach(item => {
                                    scanServiceSubRecords.push({
                                        scanServiceId: item.scanServiceId,
                                        chargeId: item.chargeId,
                                        cost: item.cost,
                                        chargeName: item.chargeName,
                                        modulesMasterId: item.modulesMasterId,
                                        chargeGroupName: item.chargeGroupName,
                                        departmentName: item.departmentName,
                                        unit: item.unit,
                                        totalCost: item.cost * item.unit,
                                        status: true,
                                        repeatTypeId: item.repeatTypeId,
                                        automaticTypeId: item.automaticTypeId,
                                        active: item.active,
                                        createdDate: item.createdDate,
                                        modifiedDate: item.modifiedDate,
                                        createdByName: item.createdByName,
                                        modifiedByName: item.modifiedByName,
                                        isMain: item.isMain,
                                        chargeTypeMainId: item.chargeTypeMainId,
                                        chargeTypeMainName: item.chargeTypeMainName,
                                        chargeTypeId: item.chargeTypeId,
                                        showAmount: true,
                                        isInPackage: item.admissionPackageId > 0,
                                        admissionPackageId: item.admissionPackageId,
                                        packageModuleDetailId: item.packageModuleDetailId,
                                        usedCost: item.usedCost,
                                        usedQuantity: item.usedQuantity,
                                        chargeCategoryName: item.chargeCategoryName,
                                        chargeCategoryId: item.chargeCategoryId,
                                        scanTestMasterId: item.scanTestMasterId,
                                        scanTestName: item.scanTestName
                                    } as IScanChargeModel);
                                });
    
                                this.serviceOrder.scanServicesRecords = scanServiceSubRecords;
                                this.originalServiceOrder.scanServicesRecords = LinqHelper.cloneDeep(scanServiceSubRecords);
                                this.serviceOrder.scanServicesTotal = scanServiceSubRecords.filter(x => x.active).map(x => x.cost * x.unit).reduce((a, b) => a + b, 0);
    
                                this.mode = EditMode.Edit;
                            } else {
                                this.serviceOrder.scanServicesRecords = new Array<IScanChargeModel>();
                                this.serviceOrder.scanServicesTotal = 0;
                            }

                            // Package Records
                            const packageRecords = response.data["packageRecords"] ? response.data["packageRecords"] as Array<IAdmissionPackageModuleModel> : new Array<IAdmissionPackageModuleModel>();
                            if (this.previousPackages.length) {
                                for (let item of this.previousPackages) {
                                    if (!packageRecords.find(x => x.packageModuleId === item.packageModuleId)) {
                                        packageRecords.push(LinqHelper.cloneDeep(item));
                                    }
                                }
                            }
                            if (packageRecords.length) {
                                this.serviceOrder.packageRecords = packageRecords;
                                for (var pk of packageRecords.filter(x => x.active)) {
                                    this.getPackageDetails(pk.packageModuleId);
                                }
                                this.serviceOrder.packageTotal = packageRecords.filter(x => x.active).map(x => (x.total)).reduce((a, b) => a + b, 0);
                                this.mode = EditMode.Edit;
                            } else {
                                this.serviceOrder.packageRecords = new Array<IAdmissionPackageModuleModel>();
                                this.serviceOrder.packageTotal = 0;
                            }
                        }
                    } else {
                        this.notifyService.defaultError();
                    }
                },
                () => {
                    this.serviceOrder.generalRecords = new Array<IChargeModel>();
                    this.serviceOrder.generalTotal = 0;
                    this.serviceOrder.pharmacyIndentRecords = new Array<IPharmacyIndentModel>();
                    this.serviceOrder.pharmacyIndentTotal = 0;
                    this.serviceOrder.packageRecords = new Array<IAdmissionPackageModuleModel>();
                    this.serviceOrder.packageTotal = 0;
                    this.serviceOrder.labServicesRecords = new Array<NewLabServicesModel>();
                    this.serviceOrder.labServicesTotal = 0;
                    this.serviceOrder.surgeryServicesRecords = new Array<ISurgeryChargeModel>();
                    this.serviceOrder.surgeryServicesTotal = 0;
                    this.serviceOrder.scanServicesRecords = new Array<IScanChargeModel>();
                    this.serviceOrder.scanServicesTotal = 0;
                }
            );
    }

    onViewLabReport(content: TemplateRef<any>, item: NewLabServicesModel) {
        this.selectedLabBookingDetail = item;
        this.showLabReport = true;
        this.onOpenLabReportModel(content, "xl");
    }

    onOpenLabReportModel(content: TemplateRef<any>, size: string) {
        this.modalRef = this.modalService.open(content, {
            backdrop: "static",
            keyboard: false,
            centered: false,
            size: size,
            windowClass: "custom-modal effect-scale"
        });
    }
    onCloseExtraPopup() {
        this.showLabReport = false;
        this.selectedLabBookingDetail = new NewLabServicesModel();
        try {
            this.modalRef.close();
            this.modalRef = undefined;

        } catch (e) {
        }
    }
    onCloseLabReportModal() {
        try {
            this.modalRef.close();
            this.modalRef = undefined;
            this.selectedLabBookingDetail = new NewLabServicesModel();
        } catch (e) {
        }
        UtilHelper.addOrRemoveLogoStyle(false, () => {
            this.isPrintLogo = false;
        })
    }

    calculateTotals = () => {
        //this.serviceOrder.packageTotal = this.serviceOrder.packageRecords.map(x => x.total).reduce((a, b) => a + b, 0);
        this.serviceOrder.generalTotal = this.serviceOrder.generalRecords.filter(x => x.active && x.showAmount).map((x, index) => {
            x.totalCost = x.cost * x.unit;
            this.onDiscount(index, 'S', false);
            return x.totalCost; 
        }).reduce((a, b) => a + b, 0);
        this.serviceOrder.labServicesTotal = this.serviceOrder.labServicesRecords.filter(x => x.active && x.showAmount).map((x, index) => {
            x.totalCost = x.cost * x.unit;
            this.onDiscount(index, 'L', false);
            return x.totalCost;
        }).reduce((a, b) => a + b, 0);
        this.serviceOrder.pharmacyIndentTotal = this.serviceOrder.pharmacyIndentRecords.filter(x => x.showAmount).map(x => (x.cost * x.unit) - x.discountAmount).reduce((a, b) => a + b, 0);
        this.serviceOrder.surgeryServicesTotal = this.serviceOrder.surgeryServicesRecords.filter(x => x.active && x.showAmount).map(x => x.cost * x.unit).reduce((a, b) => a + b, 0);
        this.serviceOrder.scanServicesTotal = this.serviceOrder.scanServicesRecords.filter(x => x.active && x.showAmount).map(x => x.cost * x.unit).reduce((a, b) => a + b, 0);
    }

    onAddCharges = (isCloseModal: boolean = true) => {
        (this.formSelected.value as Array<any>).filter(x => x.status).forEach(item => {
            const exists = this.serviceOrder.generalRecords.find(x => x.chargeId === item.chargeId && x.active);

            if (exists && exists.active) {
                this.notifyService.confirm(`${exists.chargeName} already exists, do you want to add again?`,
                    () => {
                        // exists.unit += 1;
                        // this.calculateTotals();
                        // this.checkGeneralRecordInPackage(exists);
                        // this.quantityUpdate = true;
                        this.onAddChargesHelper(item);
                    });
            } else {
                this.onAddChargesHelper(item);
            }
        });

        if (isCloseModal) {
            this.onCloseModal();
        }
    }

    onAddChargesHelper = (item: any) => {
        const record = Object.assign({}, this.chargeRecords.find(x => x.chargeId === item.chargeId));
        record.unit = item.unit || 1;
        record.cost = record.charges[0].amount;
        record.createdByName = this.page.userAccount.fullName;
        record.createdDate = new Date();
        record.active = true;
        record.showAmount = true;

        let servicesForm = this.discountForm.get("services") as FormArray;
        servicesForm.push(this.formBuilder.group({
            index: new FormControl(this.serviceOrder.generalRecords.length),
            id: new FormControl(record.serviceOrderId),
            discountType: new FormControl({value: null, disabled: !record.cost}),
            discount: new FormControl({value: null, disabled: !record.cost})
        }))
        this.serviceOrder.generalRecords.push(record as any);
        this.addedIndexes.push(this.serviceOrder.generalRecords.length - 1);
        this.calculateTotals();
        this.checkGeneralRecordInPackage(this.serviceOrder.generalRecords[this.serviceOrder.generalRecords.length - 1]);
    }

    onAddLabServices = (isCloseModal: boolean = true) => {
        this.selectedLabs.forEach(item => {
            item.cost = item.charges[0].amount;
            const exists = this.serviceOrder.labServicesRecords.find(x => x.labMainDetailId === item.labMainDetailId && x.active === true);
            if (exists && exists.active) {
                exists.charges = item.charges
                this.notifyService.confirm(`${exists.testName} already exists, do you want to add again?`,
                    () => {
                        // exists.unit += 1;
                        // this.calculateTotals();
                        // this.checkLabRecordInPackage(exists);
                        // this.quantityUpdate = true;
                        this.onAddLabServicesHelper(item);
                    });
            } else {
                this.onAddLabServicesHelper(item);
            }
        });

        if (isCloseModal) {
            this.onCloseModal();
        }
    }

    onAddLabServicesHelper = (item: NewLabServicesModel) => {
        const record = Object.assign({}, this.labs.find(x => x.labMainDetailId === item.labMainDetailId));
        record.unit = 1;
        record.showAmount = true;
        record.createdByName = this.page.userAccount.fullName;
        record.createdDate = new Date();
        record.active = true;
        let labsForm = this.discountForm.get("labs") as FormArray;
        labsForm.push(this.formBuilder.group({
            index: new FormControl(this.serviceOrder.labServicesRecords.length),
            id: new FormControl(record.labServicesId),
            discountType: new FormControl(null),
            discount: new FormControl(null)
        }))
        this.serviceOrder.labServicesRecords.push(record);
        this.addedIndexes.push(this.serviceOrder.labServicesRecords.length - 1);
        this.calculateTotals();
        this.checkLabRecordInPackage(this.serviceOrder.labServicesRecords[this.serviceOrder.labServicesRecords.length - 1]);
    }

    insertHelper = (callback?: Function) => {
        this.submitting = true;

        var data = {
            id: this.admissionId,
            isAdmission: this.isAdmission,
            createdBy: this.page.userAccount.accountId,
            labServices: [],
            records: [],
            packages: [],
            roleId: this.page.userAccount.roleId,
            roleName: this.page.userAccount.roleName,
            fullName: this.page.userAccount.fullName,
            receiptSaving: false,
            surgeryServices: [],
            scanServices: []
        }

        this.serviceOrder.generalRecords.forEach(item => {
            data.records.push(
                {
                    chargeId: item.chargeId,
                    unit: item.unit,
                    cost: item.cost,
                    chargeTypeMainId: item.chargeTypeId ? item.chargeTypeMainId : null,
                    chargeTypeId: item.chargeTypeId,
                    notes: null,
                    admissionPackageId: item.admissionPackageId,
                    packageModuleDetailId: item.packageModuleDetailId,
                    usedQuantity: item.usedQuantity,
                    usedCost: item.usedCost,
                    discountType: item.discountType === DiscountType.Number ? 'A' : item.discountType === DiscountType.Percentage ? 'P' : null,
                    discountAmount: +(item.discountAmount || 0),
                    discountPercentage: +(item.discountPercentage || 0),
                    discount: +(item.discount || 0)
                });
        });

        this.serviceOrder.labServicesRecords.forEach(item => {
            data.labServices.push(
                {
                    chargeCategoryId: this.roomChargeCategoryId,
                    labMainDetailId: item.labMainDetailId,
                    unit: item.unit,
                    cost: item.cost,
                    notes: null,
                    admissionPackageId: item.admissionPackageId,
                    packageModuleDetailId: item.packageModuleDetailId,
                    usedQuantity: item.usedQuantity,
                    usedCost: item.usedCost,
                    discountType: item.discountType === DiscountType.Number ? 'A' : item.discountType === DiscountType.Percentage ? 'P' : null,
                    discountAmount: +(item.discountAmount || 0),
                    discountPercentage: +(item.discountPercentage || 0),
                    discount: +(item.discount || 0)
                });
        });

        this.serviceOrder.packageRecords.forEach(item => {
            data.packages.push(item.packageModuleId);
        });

        this.serviceOrder.surgeryServicesRecords.forEach(item => {
            data.surgeryServices.push({
                surgeryId: item.surgeryId ? item.surgeryId : null,
                chargeId: item.chargeId,
                unit: item.unit,
                cost: item.cost,
                chargeTypeMainId: item.chargeTypeId ? item.chargeTypeMainId : null,
                chargeTypeId: item.chargeTypeId,
                notes: null,
                admissionPackageId: item.admissionPackageId,
                packageModuleDetailId: item.packageModuleDetailId,
                usedQuantity: item.usedQuantity,
                usedCost: item.usedCost,
                chargeCategoryId: this.chargeCategory != null && this.chargeCategory != undefined ? this.chargeCategory.id : this.roomChargeCategoryId
            });
        });

        this.serviceOrder.scanServicesRecords.forEach(item => {
            data.scanServices.push({
                scanTestMasterId: item.scanTestMasterId ? item.scanTestMasterId : null,
                chargeId: item.chargeId,
                unit: item.unit,
                cost: item.cost,
                chargeTypeMainId: item.chargeTypeId ? item.chargeTypeMainId : null,
                chargeTypeId: item.chargeTypeId,
                notes: null,
                admissionPackageId: item.admissionPackageId,
                packageModuleDetailId: item.packageModuleDetailId,
                usedQuantity: item.usedQuantity,
                usedCost: item.usedCost,
                chargeCategoryId: this.chargeCategory != null && this.chargeCategory != undefined ? this.chargeCategory.id : this.roomChargeCategoryId
            });
        });

        this.httpService
            .post<GenericResponse>(ApiResources.getURI(ApiResources.serviceOrder.base, ApiResources.serviceOrder.insert), data)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.submitting = false))
            .subscribe(
                (response: GenericResponse) => {
                    if (response.status === GenericStatus[GenericStatus.Success]) {
                        if (!callback || callback == undefined) {
                            this.notifyService.successToast("Service Order has been Saved successfully");
                            this.deletedCharges = new Array<number>();
                            this.deletedLabServices = new Array<number>();
                            this.deletedLabBookingHeaderIds = new Array<number>();
                            this.addedIndexes = new Array<number>();
                            this.deletedPharmacy = new Array<number>();
                            this.deletedPackages = new Array<number>();
                            this.mode = EditMode.Edit;
                            this.fetch();
                        } else {
                            callback && callback(true);
                        }
                    } else {
                        callback && callback(false);
                        if (response.message) {
                            this.notifyService.infoToast(response.message);
                        } else {
                            this.notifyService.defaultError();
                        }
                    }
                },
                () => {
                    callback && callback(false);
                    this.notifyService.defaultError();
                    this.chargeRecords = new Array<NewServicesModel>();

                }
            );
    }

    getInsurance() {
        this.httpService.post(ApiResources.getURI(ApiResources.insuranceAdmission.base, ApiResources.insuranceAdmission.getInsuranceApprovals), { admissionId: Number(this.admissionId) })
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => { this.loading = false }))
            .subscribe((response: InsuranceAdmission) => {
                if (response != undefined && response !== null) {
                    this.insuranceAdmission = new InsuranceAdmission();
                    this.insuranceAdmission = response;
                }
            });
    }

    onClaimInsurance(packageTotal: number, generalTotal: number, pharmacyIndentTotal: number, labServicesTotal: number) {

        const tempPackageTotal = packageTotal || 0;
        const tempGeneralTotal = generalTotal || 0;
        const tempPharmacyIndentTotal = pharmacyIndentTotal || 0
        const tempLabServicesTotal = labServicesTotal || 0;
        const total = tempPackageTotal + tempGeneralTotal + tempPharmacyIndentTotal + tempLabServicesTotal;
        if (this.insuranceAdmission.expectedAmount <= total) {
            var value = total - this.insuranceAdmission.expectedAmount;
        }
        if (this.insuranceAdmission.expectedAmount > total) {
            var value = this.insuranceAdmission.expectedAmount - total;
            console.log(value);
        }
    }

    onCancelClaimInsurance(packageTotal: number, generalTotal: number, pharmacyIndentTotal: number, labServicesTotal: number) {
        const tempPackageTotal = packageTotal || 0;
        const tempGeneralTotal = generalTotal || 0;
        const tempPharmacyIndentTotal = pharmacyIndentTotal || 0
        const tempLabServicesTotal = labServicesTotal || 0;
        const total = tempPackageTotal + tempGeneralTotal + tempPharmacyIndentTotal + tempLabServicesTotal;
        console.log(total);
    }

    updateHelper = (callback?: Function) => {
        this.submitting = true;

        var data = {
            id: this.admissionId,
            createdBy: this.page.userAccount.accountId,
            labServices: [],
            records: [],
            packages: [],
            roleId: this.page.userAccount.roleId,
            fullName: this.page.userAccount.fullName,
            surgeryServices: [],
            scanServices: []
        }

        let unitChangedGeneralRecords = [];
        this.serviceOrder.generalRecords.filter(x => x.active).forEach(item => {
            let found = this.originalServiceOrder.generalRecords.find(x => x.serviceOrderId === item.serviceOrderId);
            let isUnitChanged = found && found.unit !== item.unit;
            if (isUnitChanged) {
                unitChangedGeneralRecords.push(item.serviceOrderId);
            }
            // commented this code due to issues || found.totalCost !== item.totalCost
            if (!item.serviceOrderId || isUnitChanged) {
                data.records.push(
                    {
                        serviceOrderId: (found && found.serviceOrderId) || null,
                        chargeId: item.chargeId,
                        unit: item.unit,
                        cost: item.cost,
                        chargeTypeMainId: item.chargeTypeId ? item.chargeTypeMainId : null,
                        chargeTypeId: item.chargeTypeId,
                        notes: null,
                        admissionPackageId: item.admissionPackageId,
                        packageModuleDetailId: item.packageModuleDetailId,
                        usedQuantity: item.usedQuantity,
                        usedCost: item.usedCost,
                        discountType: item.discountType === DiscountType.Number ? 'A' : item.discountType === DiscountType.Percentage ? 'P' : null,
                        discountAmount: +(item.discountAmount || 0),
                        discountPercentage: +(item.discountPercentage || 0),
                        discount: +(item.discount || 0)
                    });
            }
        });

        let unitChangedLabRecords = [];
        this.serviceOrder.labServicesRecords.filter(x => x.active).forEach(item => {
            let found = this.originalServiceOrder.labServicesRecords.find(x => x.labServicesId === item.labServicesId);
            let isUnitChanged = found && found.unit !== item.unit
            if (isUnitChanged) {
                unitChangedLabRecords.push(item.labServicesId);
            }
            if ((!item.labServicesId && item.active) || isUnitChanged) {
                data.labServices.push(
                    {
                        labServicesId: (found && found.labServicesId) || null,
                        chargeCategoryId: this.roomChargeCategoryId,
                        labMainDetailId: item.labMainDetailId,
                        unit: item.unit,
                        cost: item.cost,
                        notes: null,
                        admissionPackageId: item.admissionPackageId,
                        packageModuleDetailId: item.packageModuleDetailId,
                        usedQuantity: item.usedQuantity,
                        usedCost: item.usedCost,
                        discountType: item.discountType === DiscountType.Number ? 'A' : item.discountType === DiscountType.Percentage ? 'P' : null,
                        discountAmount: +(item.discountAmount || 0),
                        discountPercentage: +(item.discountPercentage || 0),
                        discount: +(item.discount || 0)
                    });
            }
        });

        this.serviceOrder.packageRecords.forEach(item => {
            if (!item.admissionPackageId) {
                data.packages.push(item.packageModuleId);
            }
        });

        let unitChangedSurgeryServiceRecords = [];
        this.serviceOrder.surgeryServicesRecords.forEach(item => {
            let found = this.originalServiceOrder.surgeryServicesRecords.find(x => x.surgeryServiceId === item.surgeryServiceId);
            let isUnitChanged = found && found.unit !== item.unit;
            if (isUnitChanged) {
                unitChangedSurgeryServiceRecords.push(item.surgeryServiceId);
            }
            if (!item.surgeryServiceId || isUnitChanged) {
                data.surgeryServices.push(
                    {
                        surgeryServiceId: (found && found.surgeryServiceId) || null,
                        surgeryId: item.surgeryId,
                        chargeId: item.chargeId,
                        unit: item.unit,
                        cost: item.cost,
                        chargeTypeMainId: item.chargeTypeId ? item.chargeTypeMainId : null,
                        chargeTypeId: item.chargeTypeId,
                        chargeCategoryId: this.chargeCategory != null && this.chargeCategory != undefined ? this.chargeCategory.id : this.roomChargeCategoryId,
                        notes: null,
                        admissionPackageId: item.admissionPackageId,
                        packageModuleDetailId: item.packageModuleDetailId,
                        usedQuantity: item.usedQuantity,
                        usedCost: item.usedCost
                    });
            }
        });

        let unitChangedScanServiceRecords = [];
        this.serviceOrder.scanServicesRecords.forEach(item => {
            let found = this.originalServiceOrder.scanServicesRecords.find(x => x.scanServiceId === item.scanServiceId);
            let isUnitChanged = found && found.unit !== item.unit;
            if (isUnitChanged) {
                unitChangedScanServiceRecords.push(item.scanServiceId);
            }
            if (!item.scanServiceId || isUnitChanged) {
                data.scanServices.push(
                    {
                        scanServiceId: (found && found.scanServiceId) || null,
                        scanTestMasterId: item.scanTestMasterId,
                        chargeId: item.chargeId,
                        unit: item.unit,
                        cost: item.cost,
                        chargeTypeMainId: item.chargeTypeId ? item.chargeTypeMainId : null,
                        chargeTypeId: item.chargeTypeId,
                        chargeCategoryId: this.chargeCategory != null && this.chargeCategory != undefined ? this.chargeCategory.id : this.roomChargeCategoryId,
                        notes: null,
                        admissionPackageId: item.admissionPackageId,
                        packageModuleDetailId: item.packageModuleDetailId,
                        usedQuantity: item.usedQuantity,
                        usedCost: item.usedCost
                    });
            }
        });

        const finalData = {
            modifiedBy: this.page.userAccount.accountId,
            newRecords: data,
            deletedRecords: [...this.deletedCharges, ...unitChangedGeneralRecords],
            deletedLabServices: [...this.deletedLabServices.filter(m => m !== null), ...unitChangedLabRecords],
            deletedLabBookingHeaderIds: this.deletedLabBookingHeaderIds,
            deletedPackages: this.deletedPackages,
            isAdmission: this.isAdmission,
            chargeCategoryId: this.roomChargeCategoryId,
            receiptSaving: false,
            deletedSurgeryServices: [...this.deletedSurgeryServices, ...unitChangedSurgeryServiceRecords],
            deletedScanServices: [...this.deletedScanServices, ...unitChangedScanServiceRecords]
        }

        this.httpService
            .post<GenericResponse>(ApiResources.getURI(ApiResources.serviceOrder.base, ApiResources.serviceOrder.update),
                finalData)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.submitting = false))
            .subscribe(
                (response: GenericResponse) => {
                    if (response.status === GenericStatus[GenericStatus.Success]) {
                        if (!callback) {
                            this.notifyService.successToast("Service Order has been updated successfully");
                            this.deletedCharges = new Array<number>();
                            this.deletedLabServices = new Array<number>();
                            this.deletedLabBookingHeaderIds = new Array<number>();
                            this.addedIndexes = new Array<number>();
                            this.deletedPharmacy = new Array<number>();
                            this.deletedPackages = new Array<number>();
                            this.deletedSurgeryServices = new Array<number>();
                            this.deletedScanServices = new Array<number>();
                            this.mode = EditMode.Edit;
                            this.fetch();
                            this.quantityUpdate = false;
                        } else {
                            callback && callback(true);
                        }
                    } else {
                        callback && callback(false);
                        if (response.message) {
                            this.notifyService.infoToast(response.message);
                        } else {
                            this.notifyService.defaultError();
                        }
                    }
                },
                () => {
                    callback && callback(false);
                    this.notifyService.defaultError();
                    this.chargeRecords = new Array<NewServicesModel>();
                }
            );
    }

    onSubmit = (callback?: Function) => {
        if (this.mode === EditMode.New) {
            this.insertHelper(callback);
        } else {
            this.updateHelper(callback);
        }
    }
    focusOnInput(checkboxFocus: any) {
        checkboxFocus.style.border = "1px solid #3283f6";
    }
    focusOnInputout(onFocusInputout: any) {
        onFocusInputout.style.border = "1px solid #dee2e6";
    }

    // Packages

    onPackagesNextPage(): void {
        this.fetchPackages();
    }

    onAddPackage(item: PackageModuleModel): void {
        const exists = this.serviceOrder.packageRecords.filter(m => m.active).find(x => x.packageModuleId === item.packageModuleId);
        if (exists) {
            this.notifyService.infoToast(`${exists.packageName} already exists, same package can not be added again.`);
        } else {
            var data = {
                admissionPackageId: 0,
                packageModuleId: item.packageModuleId,
                packageName: item.packageName,
                moduleTypeId: item.moduleTypeId,
                moduleTypeName: item.moduleTypeName,
                quantity: item.quantity,
                freeQuantity: item.freeQuantity,
                expiresIn: item.expiresIn,
                total: item.totalAfterDiscount,
                active: true,
                createdByName: this.page.userAccount.fullName,
                createdDate: new Date()
            } as IAdmissionPackageModuleModel;
            this.serviceOrder.packageRecords.push(data);
            this.addedIndexes.push(this.serviceOrder.packageRecords.length - 1);
            this.getPackageDetails(item.packageModuleId, () => {
                this.onPackageAddedCheckItems();
            });
            this.notifyService.successToast("Package Added Successfully");
            this.serviceOrder.packageTotal = this.serviceOrder.packageRecords.filter(x => x.active).map(x => x.total).reduce((a, b) => a + b, 0);
            this.onCloseModal();
        }
    }

    getPackageDetails = (packageId: number, callback?: Function) => {
        // commented to always fetch latest from server
        //if (!this.packageDetails[packageId]) {
            this.httpService
                .post(ApiResources.getURI(ApiResources.packageModule.base, ApiResources.packageModule.fetchPackageDetails),
                    { id: packageId.toString(), subId: this.admissionId.toString(), isAdmission: this.isAdmission })
                .pipe(takeUntil(this.page.unSubscribe))
                .subscribe((response: Array<PackageModuleDetailModel>) => {
                    this.packageDetails[packageId] = response;
                    callback && callback();
                }, (error) => {
                    console.error(error);
                });
        //} else {
        //    callback && callback();
        //}
    }

    // call this when package removed
    onPackageRemovedCheckItems = () => {
        // Check General Services
        this.serviceOrder.generalRecords.forEach((g, i) => {
            this.packageItemUnassignHelper(g, 'G', i);
        });

        // Check Labs
        this.serviceOrder.labServicesRecords.forEach((l, i) => {
            this.packageItemUnassignHelper(l, 'L', i);
        });

        // Check Scans
        // TODO

        this.calculateTotals();

    }

    onPackageAddedCheckItems = () => {
        for (var pk of this.serviceOrder.packageRecords) {
            var packageDetails = this.packageDetails[pk.packageModuleId] as Array<PackageModuleDetailModel>;
            if (!packageDetails) continue;

            // Check General Services
            this.serviceOrder.generalRecords.filter(x => x.active).forEach((g, i) => {
                this.checkGeneralRecordInPackage(g, packageDetails, i);
            });

            // Check Labs
            this.serviceOrder.labServicesRecords.filter(x => x.active).forEach((l, i) => {
                this.checkLabRecordInPackage(l, packageDetails, i);
            });

            // Check Scans
            // TODO
        }

        this.calculateTotals();
    }

    checkGeneralRecordInPackage = (g: IChargeModel, packageDetails?: Array<PackageModuleDetailModel>, index?: number) => {
        if (!this.packageDetails || !Object.keys(this.packageDetails).length) return;

        if (!packageDetails) {
            packageDetails = this.packageDetails[Object.keys(this.packageDetails)[0]] as Array<PackageModuleDetailModel>;
        }
        let found = packageDetails.find(y => y.modulesMasterId == g.modulesMasterId && y.referenceId == g.chargeId);
        if (found) {
            if (g.usedQuantity) {
                this.packageItemUnassignHelper(g, 'G', index);
            }
            this.packageItemAssignHelper(found, g);
        }

        this.calculateTotals();
    }

    checkLabRecordInPackage = (l: NewLabServicesModel, packageDetails?: Array<PackageModuleDetailModel>, index?: number) => {
        if (!this.packageDetails || !Object.keys(this.packageDetails).length) return;

        if (!packageDetails) {
            packageDetails = this.packageDetails[Object.keys(this.packageDetails)[0]] as Array<PackageModuleDetailModel>;
        }
        let found = packageDetails.find(y =>
            y.modulesMasterId == (l.charges && l.charges.length && l.charges[0].modulesMasterId ? l.charges[0].modulesMasterId : l.modulesMasterId)
            && y.referenceId == l.labMainDetailId);
        if (found) {
            if (l.usedQuantity) {
                this.packageItemUnassignHelper(l, 'L', index);
            }
            this.packageItemAssignHelper(found, l);
        }

        this.calculateTotals();
    }

    packageItemUnassignHelper = (source: IChargeModel | NewLabServicesModel, sourceCode: string, index?: number) => {
        if(source.unit === 0 && (source.usedQuantity || 0)) {
            if(sourceCode === 'G' && index !== undefined) {
                this.removeCharge(index);
            } else if(sourceCode === 'L' && index !== undefined) {
                this.removeLabService(index);
            }
        }
        source.unit += (source.usedQuantity || 0);
        source.cost = source.cost || (source.usedCost || 0);
        source.usedQuantity = 0;
        source.usedCost = 0;
        source.admissionPackageId = null;
        source.packageModuleDetailId = null;
    }

    packageItemAssignHelper = (source: PackageModuleDetailModel, destination: IChargeModel | NewLabServicesModel) => {
        let remaningQty = source.quantity - destination.unit;
        if (remaningQty >= 0) {
            destination.usedQuantity = destination.unit;
            destination.usedCost = destination.cost;
            destination.cost = 0;
            destination.unit = 0;
        } else {
            let leftOverQty = remaningQty * -1;
            destination.usedQuantity = destination.unit - leftOverQty;
            destination.usedCost = destination.cost;
            destination.unit = leftOverQty;
        }
        destination.admissionPackageId = source.packageModuleId;
        destination.packageModuleDetailId = source.packageModuleDetailId;
        source.quantity = source.quantity - 1;
    }

    onRemovePackage(index: number): void {
        if (this.serviceOrder.packageRecords[index].admissionPackageId) {
            this.deletedPackages.push(this.serviceOrder.packageRecords[index].admissionPackageId);
            this.serviceOrder.packageRecords[index].active = false;
            this.isFirstTime = false;
            this.finalBillBasics.finalAmount = 0;
        }
        else {
            this.serviceOrder.packageRecords.splice(index, 1);
            this.addedIndexes = this.addedIndexes.filter(x => x !== index);
        }

        //if (this.serviceOrder.packageRecords[index].active === false) {
        //    this.serviceOrder.packageRecords.splice(index, 1);
        //    this.addedIndexes = this.addedIndexes.filter(x => x !== index);
        //}

        this.serviceOrder.packageTotal = this.serviceOrder.packageRecords.filter(x => x.active).map(x => x.total).reduce((a, b) => a + b, 0);
        this.onPackageRemovedCheckItems();
    }

    onViewPackage(content: TemplateRef<any>, model: PackageModuleModel): void {
        this.selectedPackage = model;
        this.modalViewRef = this.modalService.open(content, { size: "lg", windowClass: "custom-modal" });
    }

    onCloseViewPackageModal(): void {
        try {
            this.modalViewRef.close();
            this.modalViewRef = undefined;
        } catch (e) {
        }

        this.selectedPackage = undefined;
    }

    private fetchPackages(): void {
        this.loadingPackages = true;

        let chargeCategoryId;
        if (this.chargeCategory && this.chargeCategory.id)
            chargeCategoryId = this.chargeCategory.id;
        else
            chargeCategoryId = this.roomChargeCategoryId;

        const requestBody = Object.assign({ packageType: this.isAdmission ? "IP" : "OP", chargeCategoryId: chargeCategoryId, moduleType: this.moduleTypeName }, this.packagesPagination);
        this.httpService
            .post(ApiResources.getURI(ApiResources.packageModule.base, ApiResources.packageModule.fetch), requestBody)
            .pipe(
                finalize(() => { this.loadingPackages = false }),
                takeUntil(this.page.unSubscribe)
            )
            .subscribe({
                next: (response: Array<PackageModuleModel>) => {
                    this.packages = response;
                    UtilHelper.applyPagination(this.packages, this.packagesPagination);
                },
                error: error => {
                    this.page.markError();
                    const errorMessage = UtilHelper.handleError(error);
                    if (errorMessage)
                        this.notifyService.error(errorMessage);
                    else
                        this.notifyService.defaultError();
                }
            });
    }

    private initPackagesPagination() {
        this.packagesPagination = new Pagination();
        this.packagesPagination.pageIndex = 1;
        this.packagesPagination.pageSize = 10;
    }

    private fetchOt() {
        this.loadingOt = true;
        const request = UtilHelper.clone(this.filters.options);
        if (this.chargeCategory != null && this.chargeCategory != undefined) {
            request["chargeCategoryId"] = this.chargeCategory.id;
        }
        else {
            request["chargeCategoryId"] = this.roomChargeCategoryId;
        }

        this.httpService.post(ApiResources.getURI(ApiResources.operationTheater.base, ApiResources.operationTheater.fetchOtWithCharges), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loadingOt = false))
            .subscribe(
                (response: Array<SurgeryModel>) => {
                    this.ot = new Array<SurgeryModel>();
                    var res = response;
                    res.forEach((row) => {
                        if (row.charges.length > 0)
                            this.ot.push(row)
                    })
                },
                () => {
                    this.ot = new Array<SurgeryModel>();
                }
            );
    }

    onOpenOt(content: TemplateRef<any>) {

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

        this.initPagination();
        this.filters.init();
        this.fetchOt();
    }

    onOtSearch() {
        this.filters.applied = UtilHelper.isFiltersApplied(this.filters.options);
        this.initPagination();
        this.fetchOt();
    }

    onOtSearchReset() {
        this.filters.init();
        this.initPagination();
        this.fetchOt();
    }

    removeOtService = (index: number) => {
        if (this.serviceOrder.surgeryServicesRecords[index].surgeryServiceId) {
            this.deletedSurgeryServices.push(this.serviceOrder.surgeryServicesRecords[index].surgeryServiceId);
            this.serviceOrder.surgeryServicesRecords[index].active = false;
            if (this.serviceOrder.surgeryServicesRecords[index].surgeryServiceId)
                this.deletedSurgeryServices.push(this.serviceOrder.surgeryServicesRecords[index].surgeryServiceId);
        }
        //if (this.serviceOrder.labServicesRecords[index].admissionPackageId == 0) {
        if (!this.serviceOrder.surgeryServicesRecords[index].surgeryServiceId) {
            this.serviceOrder.surgeryServicesRecords.splice(index, 1);
            this.addedIndexes = this.addedIndexes.filter(x => x !== index);
        }

        this.serviceOrder.surgeryServicesTotal = this.serviceOrder.surgeryServicesRecords.filter(x => x.active).map(x => x.cost * x.unit).reduce((a, b) => a + b, 0);
    }


    onOtSelect(ot?: SurgeryModel) {
        this.selectedOt = new Array<SurgeryModel>();
        ot.selected = true;
        this.selectedOt.push(ot);
        this.onAddSurgeryServices();
    }

    onAddSurgeryServices = (isCloseModal: boolean = true) => {
        this.selectedOt.forEach(item => {
            item.cost = item.charges[0].amount;
            const exists = this.serviceOrder.surgeryServicesRecords.find(x => x.surgeryId === item.surgeryId && x.active === true);
            if (exists && exists.active) {
                exists.charges = item.charges
                const surgeryService = this.selectedOt.find(m => m.surgeryId === exists.surgeryId);
                this.notifyService.confirm(`${surgeryService.name} already exists, do you want to add again?`,
                    () => {
                        // exists.unit += 1;
                        // this.calculateTotals();
                        // this.checkLabRecordInPackage(exists);
                        // this.quantityUpdate = true;
                        this.onAddOtServicesHelper(item);
                    });
            } else {
                this.onAddOtServicesHelper(item);
            }
        });

        if (isCloseModal) {
            this.onCloseModal();
        }
    }

    onAddOtServicesHelper = (item: SurgeryModel) => {
        const record = Object.assign({}, this.ot.find(x => x.surgeryId === item.surgeryId));
        record.unit = 1;

        record.showAmount = true;
        record.createdByName = this.page.userAccount.fullName;
        record.createdDate = new Date();
        record.active = true;
        this.serviceOrder.surgeryServicesRecords.push(record);
        this.addedIndexes.push(this.serviceOrder.surgeryServicesRecords.length - 1);
        this.calculateTotals();
        //this.checkLabRecordInPackage(this.serviceOrder.otServicesRecords[this.serviceOrder.otServicesRecords.length - 1]);
    }

    onOtRemove(ot?: SurgeryModel) {
        let index = 0;
        ot.isSelected = false;
        index = this.selectedOt.findIndex(item => item.surgeryId === ot.surgeryId);
        console.log(index);
    }

    onOpenScan(content: TemplateRef<any>) {

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

        this.initPagination();
        this.filters.init();
        this.fetchScan();
    }


    private fetchScan() {
        this.loadingScan = true;
        const request = UtilHelper.clone(this.filters.options);
        if (this.chargeCategory != null && this.chargeCategory != undefined) {
            request["chargeCategoryId"] = this.chargeCategory.id;
        }
        else {
            request["chargeCategoryId"] = this.roomChargeCategoryId;
        }

        this.httpService.post(ApiResources.getURI(ApiResources.scanTest.base, ApiResources.scanTest.fetchScanWithCharges), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loadingScan = false))
            .subscribe(
                (response: Array<IScanChargeModel>) => {
                    this.scan = new Array<IScanChargeModel>();
                    var res = response;
                    res.forEach((row) => {
                        if (row.charges.length > 0)
                            this.scan.push(row)
                    })
                },
                () => {
                    this.scan = new Array<IScanChargeModel>();
                }
            );
    }

    onScanSearch() {
        this.filters.applied = UtilHelper.isFiltersApplied(this.filters.options);
        this.initPagination();
        this.fetchScan();
    }

    onScanSearchReset() {
        this.filters.init();
        this.initPagination();
        this.fetchScan();
    }

    removeScanService = (index: number) => {
        if (this.serviceOrder.scanServicesRecords[index].scanServiceId) {
            this.deletedScanServices.push(this.serviceOrder.scanServicesRecords[index].scanServiceId);
            this.serviceOrder.scanServicesRecords[index].active = false;
            if (this.serviceOrder.scanServicesRecords[index].scanServiceId)
                this.deletedScanServices.push(this.serviceOrder.scanServicesRecords[index].scanServiceId);
        }
        //if (this.serviceOrder.labServicesRecords[index].admissionPackageId == 0) {
        if (!this.serviceOrder.scanServicesRecords[index].scanServiceId) {
            this.serviceOrder.scanServicesRecords.splice(index, 1);
            this.addedIndexes = this.addedIndexes.filter(x => x !== index);
        }

        this.serviceOrder.scanServicesTotal = this.serviceOrder.scanServicesRecords.filter(x => x.active).map(x => x.cost * x.unit).reduce((a, b) => a + b, 0);
    }

    onScanSelect(scan?: IScanChargeModel) {
        this.selectedScan = new Array<IScanChargeModel>();
        scan.selected = true;
        this.selectedScan.push(scan);
        this.onAddScanServices();
    }

    onAddScanServices = (isCloseModal: boolean = true) => {
        this.selectedScan.forEach(item => {
            item.cost = item.charges[0].amount;
            const exists = this.serviceOrder.scanServicesRecords.find(x => x.scanTestMasterId === item.scanTestMasterId && x.active === true);
            if (exists && exists.active) {
                exists.charges = item.charges
                const scanService = this.selectedScan.find(m => m.scanTestMasterId === exists.scanTestMasterId);
                this.notifyService.confirm(`${scanService.scanTestName} already exists, do you want to add again?`,
                    () => {
                        // exists.unit += 1;
                        // this.calculateTotals();
                        // this.checkLabRecordInPackage(exists);
                        // this.quantityUpdate = true;
                        this.onAddScanServicesHelper(item);
                    });
            } else {
                this.onAddScanServicesHelper(item);
            }
        });

        if (isCloseModal) {
            this.onCloseModal();
        }
    }

    onAddScanServicesHelper = (item: IScanChargeModel) => {
        const record = Object.assign({}, this.scan.find(x => x.scanTestMasterId === item.scanTestMasterId));
        record.unit = 1;

        record.showAmount = true;
        record.createdByName = this.page.userAccount.fullName;
        record.createdDate = new Date();
        record.active = true;
        this.serviceOrder.scanServicesRecords.push(record);
        this.addedIndexes.push(this.serviceOrder.scanServicesRecords.length - 1);
        this.calculateTotals();
        //this.checkLabRecordInPackage(this.serviceOrder.otServicesRecords[this.serviceOrder.otServicesRecords.length - 1]);
    }

    onScanRemove(scan?: IScanChargeModel) {
        let index = 0;
        scan.isSelected = false;
        index = this.selectedScan.findIndex(item => item.scanTestMasterId === scan.scanTestMasterId);
        console.log(index);
    }

}
