import { Component, OnDestroy, OnInit, TemplateRef} from "@angular/core";
import { ActivatedRoute, Params } from "@angular/router";
import { takeUntil, finalize } from "rxjs/operators";
import { Location } from '@angular/common';
import { IUserAccount, Page, GenericResponse, GenericStatus } from "@shared/models";
import { AppData, HttpService, NotifyService, FinalBillService } from "@shared/services";
import { ApiResources } from "@shared/helpers";
import { IReceiptTypeModel} from "../../models/receipt-type.model";
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
import { FinalBillBasicModel } from "../../models/final-bill-basic.model";
import { NgbModal, NgbModalRef } from "@ng-bootstrap/ng-bootstrap";
import { IAdmissionModel } from "../../models/admission.model";
import { GatepassModel } from "../../models/gatepass.model";

enum EditMode {
    New = 1,
    Discharged = 2
}

@Component({
    templateUrl: "./provisional-gate-pass.html",
    styleUrls: ['../../services.css']
})

export class ProvisionalGatePassPage implements OnInit, OnDestroy {

    editMode = EditMode;
    page: Page;

    loading: boolean;

    record: GatepassModel;
    admission: IAdmissionModel;

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

    receiptTypes: Array<IReceiptTypeModel>;
    gatePassForm: FormGroup;

    finalBillBasics: FinalBillBasicModel;

    mode: EditMode;
    today = new Date();
    modalRef: NgbModalRef;   
    maxDischargeDate: string;

    constructor(
        private readonly httpService: HttpService,
        private readonly route: ActivatedRoute,
        private readonly finalBillService: FinalBillService,
        private readonly appData: AppData,
        private readonly formBuilder: FormBuilder,
        private readonly notifyService: NotifyService,
        private readonly modalService: NgbModal,
        private readonly location: Location      
    ) {
        this.mode = EditMode.New;
        this.record = {} as GatepassModel;       
        this.finalBillBasics = new FinalBillBasicModel();      
        this.loading = true;
        this.page = new Page();
        this.buildForm();
    }

    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";
                            this.getFinalBillBasics(() => {
                                this.admissionFetch();
                                this.fetch();
                                this.getFinalBillBasics();
                            });
                        });                   
                   
                } else {
                    this.page.userAccount = undefined;
                }               
            });
    }

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

    get form() {
        return this.gatePassForm.controls;
    }

    private buildForm(model?: GatepassModel) {
        function adjust(val) {
            if (val > 9) {
                return val.toString();
            } else {
                return '0' + val.toString();
            }
        }

        var today = new Date();
        var date = today.getFullYear() + '-' + adjust(today.getMonth() + 1) + '-' + adjust(today.getDate());
        var time = adjust(today.getHours()) + ":" + adjust(today.getMinutes());
          this.maxDischargeDate = `${date}T${time}`;
        
        
        this.gatePassForm = this.formBuilder.group({
            
            remark: [model ? model.remark : null],          
            validUpto: [model ? model.validUpto : null, [Validators.required]],

        });
    }

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

    onCloseModal() {
        try {
            this.modalRef.close();
            this.modalRef = undefined;
        } catch (e) {
            // ignored;
        }
        this.submitting = undefined;
        this.submitted = undefined;
    }
   
    fetch = () => {
        const data = {          
            id: this.admissionId,
           // GatePassTypeName
            typeId:1
        };
        this.httpService
            .post<GenericResponse>(ApiResources.getURI(ApiResources.gatePass.base, ApiResources.gatePass.gatePassfetch),
                data)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loading = false))
            .subscribe(
                (response: GenericResponse) => {
                    if (response.status === GenericStatus[GenericStatus.Success]) {
                        this.mode = EditMode.Discharged;
                        const record = response.data as GatepassModel;
                        
                        this.buildForm(record);
                        this.record = record;
                    } else if (response.status === GenericStatus[GenericStatus.Error]) {
                        this.mode = EditMode.Discharged;
                        this.notifyService.defaultError();
                    } else {
                        this.mode = EditMode.New;
                    }
                },
                () => {
                    this.record = null;
                }
            );

    }

    admissionFetch = () => {
        this.httpService
            .post<GenericResponse>(ApiResources.getURI(ApiResources.serviceOrder.base, ApiResources.serviceOrder.getAdmissionBasic),
                { id: this.admissionId, isAdmission: this.isAdmission })
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loading = false))
            .subscribe(
                (response: GenericResponse) => {
                    if (response.status === GenericStatus[GenericStatus.Success]) {
                        this.admission = response.data as IAdmissionModel;                       
                    }
                },
                () => {
                    this.admission = null;
                }
            );
    }

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

    insert = () => {
        this.submitted = true;
        if (!this.gatePassForm.valid) {
            return;
        }

        this.submitting = true;
        const data = {
            ...this.gatePassForm.value,
            admissionId: parseInt(this.admissionId),
            roleId: this.page.userAccount.roleId,
            typeId: 1
        };
       
        data["createdBy"] = this.page.userAccount.accountId;       
        data["fullName"] = this.page.userAccount.fullName;

        this.httpService
            .post<GenericResponse>(ApiResources.getURI(ApiResources.gatePass.base, ApiResources.gatePass.gatePassinsert), data)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.submitting = false))
            .subscribe(
                (response: GenericResponse) => {
                    if (response.status === GenericStatus[GenericStatus.Success]) {
                        this.notifyService.success("Patient Gate pass  has been Generated successfully");
                        this.mode = EditMode.Discharged;                        
                        this.fetch();
                        this.finalBillService.set(true);
                    } else {
                        if (response.message) {
                            this.notifyService.info(response.message);
                        } else {
                            this.notifyService.defaultError();
                        }
                    }
                },
                () => {
                    this.notifyService.defaultError();
                }
            );
    }

    onSubmit = () => {

        if (this.record.gatePassId) {
            this.update();
        } else {
            this.insert();
        }
    }

    onEdit = () => {
        this.mode = EditMode.New;
    }

    onCancel = () => {
        this.mode = EditMode.Discharged;
    }

    update = () => {
        this.submitted = true;
        if (!this.gatePassForm.valid) {
            return;
        }

        this.submitting = true;
        const data = {
            ...this.gatePassForm.value,
            id: this.record.gatePassId.toString()          
        };

       
        data["modifiedBy"] = this.page.userAccount.accountId;
        data["roleId"] = this.page.userAccount.roleId;
        data["fullName"] = this.page.userAccount.fullName;

        this.httpService
            .post<GenericResponse>(ApiResources.getURI(ApiResources.gatePass.base, ApiResources.gatePass.gatePassupdate), data)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.submitting = false))
            .subscribe(
                (response: GenericResponse) => {
                    if (response.status === GenericStatus[GenericStatus.Success]) {
                        this.notifyService.success("Patient Gate Pass details has been Updated successfully");
                        this.mode = EditMode.Discharged;
                        this.fetch();
                    } else {
                        if (response.message) {
                            this.notifyService.info(response.message);
                        } else {
                            this.notifyService.defaultError();
                        }
                    }
                },
                () => {
                    this.receiptTypes = new Array<IReceiptTypeModel>();
                }
            );
    }

    ngOnDestroy() {
        this.page.unSubscribe.next();
        this.page.unSubscribe.complete();
    }
}