<div id="prescriptions-{{$patient->id}}" v-cloak>
    <div class="d-flex align-items-baseline mb-3">
        <div class="font-weight-bold text-secondary font-size-14 m-0">ERx &amp; Orders</div>
        @if($patient->mcp)
            @if(!request()->input('erx_category') || request()->input('erx_category') === 'DRUG')
                <span class="mx-2 text-secondary on-hover-opaque">|</span>
                <a href="#" v-on:click.prevent="newERx('DRUG')">+ Drug</a>
            @endif
            @if(!request()->input('erx_category') || request()->input('erx_category') === 'LAB')
                <span class="mx-2 text-secondary on-hover-opaque">|</span>
                <a href="#" v-on:click.prevent="newERx('LAB')">+ Lab</a>
            @endif
            @if(!request()->input('erx_category') || request()->input('erx_category') === 'IMAGING')
                <span class="mx-2 text-secondary on-hover-opaque">|</span>
                <a href="#" v-on:click.prevent="newERx('IMAGING')">+ Imaging</a>
            @endif
            @if(!request()->input('erx_category') || request()->input('erx_category') === 'REFERRAL')
                <span class="mx-2 text-secondary on-hover-opaque">|</span>
                <a href="#" v-on:click.prevent="newERx('REFERRAL')">+ Referral</a>
            @endif
            @if(!request()->input('erx_category') || request()->input('erx_category') === 'OTHER')
                <span class="mx-2 text-secondary on-hover-opaque">|</span>
                <a href="#" v-on:click.prevent="newERx('OTHER')">+ Other</a>
            @endif
        @else
            <span class="ml-3 text-warning-mellow">MCP not set on the patient</span>
        @endif
        <div class="ml-5 width-200px">
            <select class="form-control form-control-sm" v-model="includeCancelled">
                <option value="">Exclude Cancelled</option>
                <option value="include-cancelled">Include Cancelled</option>
            </select>
        </div>
    </div>
    <div class="d-flex align-items-start bg-white">
        <div :class="currentPrescription ? 'max-width-300px' : 'flex-grow-1'">
            <table class="table table-striped table-sm table-bordered mb-0">
                <thead class="bg-light">
                <tr>
                    <th class="border-0 text-secondary width-150px">Created</th>
                    <th class="border-0 text-secondary" :class="currentPrescription ? 'width-200px' : ''">Clinical</th>
                    <th v-if="!currentPrescription" class="border-0 text-secondary">Prescriber</th>
                    <th v-if="!currentPrescription" class="border-0 text-secondary">Status</th>
                    <th v-if="!currentPrescription" class="border-0 text-secondary">Sign</th>
                    <th v-if="!currentPrescription" class="border-0 text-secondary">Client Status</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="(prescription, index) in prescriptions"
                    v-if="includeCancelled === 'include-cancelled' || prescription.pro_declared_status !== 'CANCELLED'"
                    :class="currentPrescription && currentPrescription.id === prescription.id ? 'bg-aliceblue' : ''">
                    <td class="width-150px" :class="currentPrescription && currentPrescription.id === prescription.id ? 'row-selection-highlight' : ''">
                        <div :class="prescription.pro_declared_status === 'CANCELLED' ? 'on-hover-opaque' : ''">
                            <a href="#" v-on:click.prevent="setCurrentPrescription(prescription, '');"
                               class="text-nowrap"
                               :class="currentPrescription && currentPrescription.id === prescription.id ? 'font-weight-bold' : ''">
                                @{{prescription.created_at_friendly_short}}
                                |
                                <b class="text-sm">@{{prescription.erx_category}}</b>
                            </a>
                            <div v-if="currentPrescription" class="text-sm">@{{prescription.hcpProDisplayName}}</div>
                            @if(@$note)
                                <div v-if="prescription.note_id === {{$note->id}}" class="text-sm text-info text-nowrap">* From this note</div>
                            @endif
                        </div>
                        <div v-if="currentPrescription && prescription.pro_declared_status === 'CANCELLED'" class="text-sm text-secondary font-weight-bold mt-1 text-sm d-flex align-items-baseline">
                            <i class="fa fa-ban mr-1 text-sm"></i>
                            CANCELLED
                        </div>
                    </td>
                    <td>
                        <div class="d-flex align-items-baseline">
                            {{--
                            <a v-if="!prescription.has_hcp_pro_signed" class="mr-2" href="#" v-on:click.prevent="editClinicalDetails(prescription)"><i class="fa fa-edit on-hover-opaque"></i></a>
                            <span v-else class="mr-2" title="Cannot edit. Prescription already signed."><i class="fa fa-edit on-hover-opaque text-secondary"></i></span>
                            --}}
                            <div v-if="prescription.clinical_detail_json" class="d-inline-flex align-items-baseline" :class="prescription.pro_declared_status === 'CANCELLED' ? 'on-hover-opaque' : ''">
                                <div class="" v-if="prescription.erx_category === 'DRUG'">
                                    <div class="d-flex align-items-baseline mb-1" v-for="drug in prescription.clinical_detail_json.items">
                                        <span class="mr-2">@{{drug.medication ?? '-'}}</span>
                                    </div>
                                </div>
                                <div v-if="prescription.erx_category === 'LAB' || prescription.erx_category === 'IMAGING'">
                                    <div class="px-2 py-1 mb-1 border bg-light"  v-for="item in prescription.clinical_detail_json.items">
                                        <div class="d-flex align-items-baseline mb-1">
                                            <span class="text-secondary mr-2">Tests:</span>
                                            <span class="flex-grow-1">
                                            <b v-for="test in item.tests" class="mr-2">@{{ test.desc }}</b>
                                        </span>
                                        </div>
                                        <div class="d-flex align-items-baseline">
                                            <span class="text-secondary mr-2">ICDs:</span>
                                            <span class="flex-grow-1">
                                            <b v-for="icd in item.icds" class="mr-2">@{{ icd.code }}</b>
                                        </span>
                                        </div>
                                    </div>
                                </div>
                                <div class="d-flex align-items-baseline" v-if="prescription.erx_category === 'REFERRAL'">
                                    <b class="mr-2">@{{prescription.clinical_detail_json.to ?? '-'}}</b>
                                    <span class="text-secondary mr-1">@{{prescription.clinical_detail_json.memo ?? '-'}}</span>
                                </div>
                                <div class="d-flex align-items-baseline" v-if="prescription.erx_category === 'OTHER'">
                                    <b class="mr-2">@{{prescription.clinical_detail_json.title ?? '-'}}</b>
                                    <span class="text-secondary mr-1">@{{prescription.clinical_detail_json.memo ?? '-'}}</span>
                                </div>
                            </div>
                            <div v-else>-</div>
                        </div>
                    </td>
                    <td v-if="!currentPrescription">
                        <div :class="prescription.pro_declared_status === 'CANCELLED' ? 'on-hover-opaque' : ''">
                            @{{ prescription.hcpProDisplayName }}
                        </div>
                    </td>
                    <td v-if="!currentPrescription">
                        <div :class="prescription.pro_declared_status === 'CANCELLED' ? 'on-hover-opaque' : ''">
                            @{{ sanitizeStatus(prescription.pro_declared_status) }}
                        </div>
                    </td>
                    <td v-if="!currentPrescription">
                        <div :class="prescription.pro_declared_status === 'CANCELLED' ? 'on-hover-opaque' : ''">
                            <div v-if="prescription.has_hcp_pro_signed" class="d-inline-flex align-items-baseline">
                                <i class="text-secondary fa fa-check mr-1"></i>
                                <span class="text-secondary">Signed</span>
                            </div>
                            <div v-else>
                                -
                            </div>
                        </div>
                    </td>
                    <td v-if="!currentPrescription">
                        <div :class="prescription.pro_declared_status === 'CANCELLED' ? 'on-hover-opaque' : ''">
                            @{{ sanitizeStatus(prescription.client_declared_status) }}
                        </div>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
        <div v-if="currentPrescription" class="border-top border-right border-bottom align-self-stretch p-3 flex-grow-1 min-width-50">
            <div class="d-flex align-items-baseline">
                <h3 class="font-size-16 m-0 d-flex align-items-baseline">
                    <i v-if="currentPrescription.has_hcp_pro_signed" title="Signed" class="fa fa-check text-success mr-2"></i>
                    <b class="mr-1 font-size-16">@{{ currentPrescription.erx_category }} ERx <span class="ml-2">@{{ currentPrescription.created_at_friendly }}</span></b>
                    @if(@$note)
                        <div v-if="currentPrescription.note_id === {{$note->id}}" class="text-info mt-1 font-weight-bold text-nowrap ml-2">* From this note</div>
                    @endif
                </h3>
                <div v-if="currentPrescription.pro_declared_status == 'CANCELLED'" class="ml-3 bg-danger font-weight-bold text-sm px-2 py-1 rounded text-white">
                    <i class="fa fa-ban"></i>
                    CANCELLED
                </div>
                <a class="ml-auto" href="#" v-on:click.prevent="setCurrentPrescription(null);">
                    <i class="fa fa-times-circle on-hover-opaque"></i>
                </a>
            </div>
            <hr class="my-3">
            <div class="d-flex align-items-baseline" v-if="currentPrescription.erx_category !== 'DRUG'">
                <span class="min-width-140px text-secondary text-sm">Clinical</span>
                <div class="d-inline-flex align-items-baseline flex-grow-1">
                    <a v-if="!currentPrescription.has_hcp_pro_signed" class="mr-2" href="#" v-on:click.prevent="editClinicalDetails(currentPrescription)"><i class="fa fa-edit on-hover-opaque"></i></a>
                    <span v-else class="mr-2" title="Cannot edit. Prescription already signed."><i class="fa fa-edit on-hover-opaque text-secondary"></i></span>
                    <div v-if="currentPrescription.clinical_detail_json" class="d-inline-flex align-items-baseline flex-grow-1">
                        <div class="" v-if="currentPrescription.erx_category === 'DRUG'">
                            <div class="d-flex align-items-baseline mb-1" v-for="drug in currentPrescription.clinical_detail_json.items">
                                <b class="mr-2">@{{drug.medication ?? '-'}}</b>
                            </div>
                        </div>
                        <div v-if="currentPrescription.erx_category === 'LAB' || currentPrescription.erx_category === 'IMAGING'" class="flex-grow-1">
                            <div class="border bg-light mb-1 px-2 py-1 flex-grow-1" v-for="item in currentPrescription.clinical_detail_json.items">
                                <div class="d-flex align-items-baseline mb-1">
                                    <span class="text-secondary mr-2">Tests:</span>
                                    <span class="flex-grow-1">
                                        <b v-for="test in item.tests" class="mr-2">@{{ test.desc }}</b>
                                    </span>
                                </div>
                                <div class="d-flex align-items-baseline">
                                    <span class="text-secondary mr-2">ICDs:</span>
                                    <span class="flex-grow-1">
                                        <b v-for="icd in item.icds" class="mr-2">@{{ icd.code }}</b>
                                    </span>
                                </div>
                            </div>
                        </div>
                        <div class="d-flex align-items-baseline" v-if="currentPrescription.erx_category === 'REFERRAL'">
                            <b class="mr-2">@{{currentPrescription.clinical_detail_json.to ?? '-'}}</b>
                            <span class="text-secondary mr-1">@{{currentPrescription.clinical_detail_json.memo ?? '-'}}</span>
                        </div>
                        <div class="d-flex align-items-baseline" v-if="currentPrescription.erx_category === 'OTHER'">
                            <b class="mr-2">@{{currentPrescription.clinical_detail_json.title ?? '-'}}</b>
                            <span class="text-secondary mr-1">@{{currentPrescription.clinical_detail_json.memo ?? '-'}}</span>
                        </div>
                    </div>
                    <div v-else>-</div>
                </div>
            </div>
            <div class="d-flex align-items-baseline" v-if="currentPrescription.erx_category === 'DRUG'">
                <div class="flex-grow-1">

                    <div v-if="currentPrescription.clinical_detail_json">
                        <div class="d-flex align-items-baseline mb-1" v-for="drug in currentPrescription.clinical_detail_json.items">
                            <a v-if="!currentPrescription.has_hcp_pro_signed" class="mr-2" href="#"
                               v-on:click.prevent="removeDrugFromERx(drug.medication)">
                                <i class="fa fa-trash-alt text-danger on-hover-opaque"></i>
                            </a>
                            <div>
                                <div class="d-flex align-items-baseline">
                                    <b class="mr-2">@{{drug.medication ?? '-'}}</b>
                                </div>
                                <div v-if="drug.instructions" class="d-inline-flex align-items-baseline text-secondary font-italic mr-2">
                                    <span class="text-secondary">Instructions: @{{ drug.instructions }}</span>
                                </div>
                                <div class="d-flex align-items-baseline">
                                    <span class="text-secondary">Dispense:</span>
                                    <span class="ml-1 mr-2">@{{ drug.dispense ? drug.dispense : '-' }}</span>
                                    <span class="text-secondary ml-2">Refills:</span>
                                    <span class="ml-1">@{{ drug.refills ? drug.refills : '-' }}</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    @if(@$note)
                    <div class="d-flex align-items-center" v-if="!currentPrescription.has_hcp_pro_signed">
                        <a href="#" class="d-block mb-1 mr-2" v-on:click.prevent="setAddMode('existing')">+ Existing</a>
                        <a href="#" class="d-block mb-1" v-on:click.prevent="setAddMode('new')">+ New</a>
                    </div>
                    @endif
                </div>
            </div>

            @if(@$note)
            <div v-if="currentPrescription && currentPrescription.erx_category === 'DRUG'">
            <div v-if="addDrugToErxMode === 'existing'" class="border border-info p-2 bg-aliceblue mb-2 rounded">
                <div class="d-flex align-items-baseline mb-2">
                    <label for="" class="text-secondary font-weight-bold m-0">Add From Existing Medications</label>
                    <a href="#" v-on:click.prevent="setAddMode('')" class="ml-auto">Close</a>
                </div>
                <table class="m-0 table table-sm border bg-white table-hover table-bordered">
                    <tr class="bg-light">
                        <th class="align-bottom text-secondary">Medication</th>
                        <!--<th class="align-bottom">Instructions</th>
                        <th class="align-bottom">Dispense</th>
                        <th class="align-bottom">Refills</th>-->
                        <th class="align-bottom text-secondary">Instructions/Dispense/Refills</th>
                        <th class="align-bottom">&nbsp;</th>
                    </tr>
                    <tr v-for="drug in existingDrugs" v-if="notAlreadyAdded(drug.data.name)">
                        <td class="width-200px">@{{ drug.data.name }}</td>
                        <td>
                            <div class="d-flex align-items-center mb-1">
                                <span class="text-sm min-width-80px">Instructions</span>
                                <input type="text" class="form-control form-control-sm min-width-unset shadow-none flex-grow-1" v-model="drug.data.instructions">
                            </div>
                            <div class="row mb-1">
                                <div class="col-6 pr-0">
                                    <div class="d-flex align-items-center">
                                        <span class="text-sm min-width-80px">Dispense</span>
                                        <input type="text" class="form-control form-control-sm min-width-unset shadow-none" v-model="drug.data.dispense">
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="d-flex align-items-center">
                                        <span class="text-sm">Refills</span>
                                        <input type="text" class="form-control form-control-sm min-width-unset shadow-none ml-2" v-model="drug.data.refills">
                                    </div>
                                </div>
                            </div>

                        </td>
                        <!--<td class="bg-white py-0 px-0">
                            <input type="text" class="form-control form-control-sm min-width-unset rounded-0 border-0 shadow-none" v-model="drug.data.instructions">
                        </td>
                        <td class="width-70px bg-white py-0 px-0">
                            <input type="text" class="form-control form-control-sm min-width-unset rounded-0 border-0 shadow-none" v-model="drug.data.dispense">
                        </td>
                        <td class="width-70px bg-white py-0 pl-0">
                            <input type="text" class="form-control form-control-sm min-width-unset rounded-0 border-0 shadow-none" v-model="drug.data.refills">
                        </td>-->
                        <td class="width-70px text-right">
                            <a href="#" v-on:click.prevent="addExistingDrugToERx(drug.uid)" class="text-nowrap">Add to eRx</a>
                        </td>
                    </tr>
                </table>
            </div>

            <div v-if="addDrugToErxMode === 'new'" class="border border-info p-2 bg-aliceblue mb-2 rounded">
                <form action="/api/visitPoint/addTopLevel" class="mcp-theme-1 w-100" id="frm-add-medication-and-add-to-erx">
                    <input type="hidden" name="noteUid" value="{{@$note ? $note->uid : $patient->coreNote->uid}}">
                    <input type="hidden" name="category" value="MEDICATION">
                    <input type="hidden" name="data">

                    <input type="hidden" data-name="medId">
                    <input type="hidden" data-name="routedMedId">
                    <input type="hidden" data-name="routedDosageFormMedId">
                    <input type="hidden" data-name="gcnSeqno">

                    <input type="hidden" name="additionReasonCategory" value="DURING_VISIT">
                    <input type="hidden" name="isRemoved" value="0">
                    <input type="hidden" name="removalReasonCategory">
                    <input type="hidden" name="isRemovedDueToEntryError" value="0">

                    <div class="d-flex align-items-baseline mb-2">
                        <label for="" class="text-secondary font-weight-bold m-0">Add New Medication</label>
                        <a href="#" v-on:click.prevent="setAddMode('')" class="ml-auto">Close</a>
                    </div>

                    <div class="row mb-2">
                        <div class="col-12">
                            <label class="text-sm text-secondary mb-0">Name</label>
                            <input type="text" data-name="name" class="form-control form-control-sm min-width-unset"
                                   stag-suggest="" stag-suggest-bottom-left=""
                                   stag-suggest-ep="/fdb-med-suggest-v2/json" required="">
                            <div class="stag-suggestions-container position-relative">
                                <div class="suggestions-outer stag-suggestions position-absolute d-none"></div>
                            </div>
                        </div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-12">
                            <label class="text-sm text-secondary mb-0">Instructions</label>
                            <input type="text" data-name="instructions"
                                   class="form-control form-control-sm min-width-unset">
                        </div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-4 pr-0">
                            <label class="text-sm text-secondary mb-0">Dispense</label>
                            <input type="text" class="form-control form-control-sm min-width-unset" name="dispense" autocomplete="off">
                        </div>
                        <div class="col-4 pr-0">
                            <label class="text-sm text-secondary mb-0">Refills</label>
                            <input type="text" class="form-control form-control-sm min-width-unset" name="refills" autocomplete="off">
                        </div>
                    </div>

                    <div class="d-flex align-items-center">
                        <button type="submit" class="btn btn-sm btn-primary mr-2 my-1">Save &amp; Add to eRx</button>
                    </div>
                </form>
            </div>
            </div>
            @endif

            <hr class="my-3">
            <div class="pb-2 d-flex align-items-center">
                <span v-if="currentPrescription.erx_category === 'DRUG'" class="min-width-140px text-secondary text-sm">Pharmacy</span>
                <span v-else-if="currentPrescription.erx_category === 'LAB'" class="min-width-140px text-secondary text-sm">Lab</span>
                <span v-else-if="currentPrescription.erx_category === 'IMAGING'" class="min-width-140px text-secondary text-sm">Lab</span>
                <span v-else class="min-width-140px text-secondary text-sm">Logistics</span>
                <div class="d-inline-flex align-items-baseline flex-grow-1">
                    <a class="mr-2" href="#" v-on:click.prevent="editLogisticsDetails(currentPrescription)"><i class="fa fa-edit on-hover-opaque"></i></a>
                    <div v-if="currentPrescription.logistics_detail_json" class="d-flex align-items-baseline">
                        <div class="d-flex align-items-baseline">
                            <b class="mr-2">@{{currentPrescription.logistics_detail_json.facilityName ?? '-'}}</b>
                            <span class="text-secondary mr-1">@{{currentPrescription.logistics_detail_json.facilityCity ?? '-'}}</span>
                            <span class="text-secondary mr-1">@{{currentPrescription.logistics_detail_json.facilityState ?? '-'}}</span>
                        </div>
                    </div>
                    <div v-else>-</div>
                </div>
            </div>
            <div class="pb-2 d-flex align-items-center">
                <span class="min-width-140px text-secondary text-sm">Prescribed By</span>
                <div class="d-inline-flex align-items-baseline flex-grow-1">
                    <a v-if="!currentPrescription.has_hcp_pro_signed" class="mr-2" href="#" v-on:click.prevent="editHcpPro(currentPrescription)"><i class="fa fa-edit on-hover-opaque"></i></a>
                    <span v-else class="mr-2" title="Cannot edit. Prescription already signed."><i class="fa fa-edit on-hover-opaque text-secondary"></i></span>
                    <div>@{{currentPrescription.hcpProDisplayName}}</div>
                </div>
            </div>
            <!--<div class="pb-2 d-flex align-items-center">
                <span class="min-width-140px text-secondary text-sm">Sign</span>
                <div v-if="currentPrescription.has_hcp_pro_signed" class="d-inline-flex align-items-baseline">
                    <i class="text-secondary fa fa-check mr-1"></i>
                    <span class="text-secondary">Signed</span>
                </div>
                <div v-else>
                    <a v-if="currentPrescription.hcp_pro_id === {{$pro->id}}"
                       href="#"
                       v-on:click.prevent="signAsHcpPro(currentPrescription)">Sign</a>
                    <span v-else>-</span>
                </div>
            </div>-->
            <div class="pb-2 d-flex align-items-center">
                <span class="min-width-140px text-secondary text-sm">Prescription Status</span>
                <div class="d-inline-flex align-items-baseline">
                    <a class="mr-2" href="#" v-on:click.prevent="editProStatus(currentPrescription)"><i class="fa fa-edit on-hover-opaque"></i></a>
                    <div v-if="currentPrescription.pro_declared_status" class="d-flex align-items-baseline">
                        @{{ sanitizeStatus(currentPrescription.pro_declared_status) }}
                    </div>
                    <div v-else>-</div>
                </div>
            </div>
            <div class="pb-2 d-flex align-items-center">
                <span class="min-width-140px text-secondary text-sm">Client Status</span>
                <div class="d-inline-flex align-items-baseline">
                    <a class="mr-2" href="#" v-on:click.prevent="editClientStatus(currentPrescription)"><i class="fa fa-edit on-hover-opaque"></i></a>
                    <div v-if="currentPrescription.client_declared_status" class="d-flex align-items-baseline">
                        @{{ sanitizeStatus(currentPrescription.client_declared_status) }}
                    </div>
                    <div v-else>-</div>
                </div>
            </div>
            <div class="pb-2 d-flex align-items-start" v-if="currentPrescription.has_hcp_pro_signed">
                <span class="min-width-140px text-secondary text-sm">PDF</span>
                <div class="d-flex align-items-baseline">
                    <a class="pdf-viewer-trigger d-block mb-1" native target="_blank"
                       :href="'/prescription-download-as-pdf/' + currentPrescription.uid">View</a>
                    <span class="mx-2 text-sm text-secondary">|</span>
                    <a native target="_blank" class="d-block mb-1"
                       :href="'/prescription-download-as-pdf/' + currentPrescription.uid">Download</a>
                    <span class="mx-2 text-sm text-secondary">|</span>
                    <a href="#" class="d-block mb-1"
                       v-on:click.prevent="transmit(currentPrescription)">Transmit</a>
                </div>
            </div>
            <hr class="my-2">
            <div v-if="!currentPrescription.has_hcp_pro_signed" class="d-flex align-items-baseline">
                <a v-if="currentPrescription.hcp_pro_id === {{$pro->id}}" href="#" class="font-weight-bold mr-3"
                   v-on:click.prevent="signAsHcpPro(currentPrescription)">Sign</a>
                <div v-if="currentPrescription.pro_declared_status === 'CANCELLED'" class="text-secondary font-weight-bold">CANCELLED</div>
                <a v-else href="#" class="text-danger d-block" v-on:click.prevent="cancelItem()">Remove eRx</a>
            </div>
            <div v-else>
                <i class="fa fa-check text-success mr-2"></i>
                <span class="font-weight-bold text-success">Signed</span>
            </div>

        </div>
    </div>
    @include('app.patient.prescriptions.drug-form')
    @include('app.patient.prescriptions.lab-form')
    @include('app.patient.prescriptions.imaging-form')
    @include('app.patient.prescriptions.referral-form')
    @include('app.patient.prescriptions.other-form')
    @include('app.patient.prescriptions.logistics-form')
    @include('app.patient.prescriptions.hcp-pro-form')
    @include('app.patient.prescriptions.sign-as-hcp-form')
    @include('app.patient.prescriptions.pro-status-form')
    @include('app.patient.prescriptions.client-status-form')
    @include('app.patient.prescriptions.transmit-form')

    @include('app.patient.prescriptions.new-lab-form')
    @include('app.patient.prescriptions.new-imaging-form')
    @include('app.patient.prescriptions.new-referral-form')
    @include('app.patient.prescriptions.new-other-form')
</div>
<?php
$uCounts = [];
if (@$note) {
    $unsignedCounts = DB::select("SELECT erx_Category, count(id) FROM erx
WHERE (has_hcp_pro_signed IS NULL OR has_hcp_pro_signed = FALSE) AND
    note_id = {$note->id} AND
    (pro_declared_status <> 'CANCELLED' OR pro_declared_status IS NULL)
GROUP BY erx_category");
    $uCounts = [];
    foreach ($unsignedCounts as $c) {
        $uCounts[$c->erx_category] = $c->count;
    }
}
?>
<script>
    (function() {

        <?php
        $prescriptions = $patient->prescriptions;
        $currentPrescription = null;
        foreach ($prescriptions as $prescription) {
            if($prescription->clinical_detail_json) {
                $prescription->clinical_detail_json = json_decode($prescription->clinical_detail_json);
            }
            if($prescription->logistics_detail_json) {
                $prescription->logistics_detail_json = json_decode($prescription->logistics_detail_json);
            }
            $prescription->created_at_friendly = friendlier_date_time($prescription->created_at);
            $prescription->created_at_friendly_short = friendlier_date_time($prescription->created_at, false);
            $prescription->hcpProDisplayName = $prescription->hcpPro ? $prescription->hcpPro->displayName() : '-';
            $prescription->hcpProUid = $prescription->hcpPro ? $prescription->hcpPro->uid : '';

            if(!!@$currentErx && $currentErx->uid === $prescription->uid) {
                $currentPrescription = $prescription;
            }
        }

        if(!!request()->input('erx_category')) {
            $prescriptions = $prescriptions->filter(function($_p) {
                return $_p->erx_category === request()->input('erx_category');
            });
        }

        $existingActiveDrugs = \App\Models\Point
            ::where('client_id', $patient->id)
            ->where('category', 'MEDICATION')
            ->where('is_removed_due_to_entry_error', false)
            ->where('is_removed', false)
            ->orderBy('created_at')
            ->get();
        foreach ($existingActiveDrugs as $point) {
            if ($point->data) {
                $point->data = json_decode($point->data);
            }
            if($point->lastChildPlan && $point->lastChildPlan->data) {
                $parsedPlan = json_decode($point->lastChildPlan->data);
                if($point->data) {
                    $point->data->instructions = trim(strip_tags($parsedPlan->value));
                }
            }
        }

        ?>

        var DEFAULTLOGISTICSDETAILS = {
                facilityName: '{{ @$defaultFacility->name ?? '' }}',
                facilityCity: '{{ @$defaultFacility->address_city ?? '' }}',
                facilityState: '{{ @$defaultFacility->address_state ?? '' }}',
                facilityAddressMemo: '',
                facilityPhone: '{{ @$defaultFacility->phone ?? '' }}',
                facilityFax: '{{ @$defaultFacility->fax ?? '' }}',
                facilityZip: '{{ @$defaultFacility->address_zip ?? '' }}',
            };
        function init() {

            window.eRxApp = new Vue({
                el: '#prescriptions-{{$patient->id}}',
                delimiters: ['@{{', '}}'],
                data: {
                    includeCancelled: '',

                    prescriptions: <?= json_encode($prescriptions) ?>,

                    numUnsigned: <?= json_encode($uCounts) ?>,

                    currentPrescriptionAction: '',
                    currentPrescriptionType: '',

                    addDrugToErxMode: '',
                    existingDrugs: <?= json_encode($existingActiveDrugs) ?>,
                    existingDrugToAddUid: '',

                    // selected
                    currentPrescription:  <?= $currentPrescription ? json_encode($currentPrescription) : 'null' ?>,

                    // for editing clinical details
                    currentPrescription_DRUG: {
                        noteUid: '{{ @$note ? $note->uid : '' }}',
                        clientUid: '{{ $patient->uid }}',
                        replacesCancelledErxUid: null, // TODO: step-2 support UI to mark a new one as replacing a cancelled one
                        hcpProUid: '{{$pro->uid}}',
                        erxCategory: 'DRUG',
                        clinicalDetailJson: {
                            items: [
                                {
                                    medication: '',
                                    dispense: '',
                                    refills: '',
                                    purpose: ''
                                }
                            ]
                        }
                    },
                    currentPrescription_LAB: {
                        noteUid: '{{ @$note ? $note->uid : '' }}',
                        clientUid: '{{ $patient->uid }}',
                        replacesCancelledErxUid: null, // TODO: step-2 support UI to mark a new one as replacing a cancelled one
                        hcpProUid: '{{$pro->uid}}',
                        erxCategory: 'LAB',
                        clinicalDetailJson: {
                            items: [
                                {
                                    tests: [
                                        {
                                            desc: '',
                                        }
                                    ],
                                    icds: [
                                        {
                                            code: '',
                                            desc: '',
                                        }
                                    ]
                                }
                            ]
                        }
                    },
                    newPrescription_LAB: {
                        noteUid: '{{ @$note ? $note->uid : '' }}',
                        clientUid: '{{ $patient->uid }}',
                        replacesCancelledErxUid: null, // TODO: step-2 support UI to mark a new one as replacing a cancelled one
                        hcpProUid: '{{$pro->uid}}',
                        erxCategory: 'LAB',
                        clinicalDetailJson: {
                            items: [
                                {
                                    tests: [
                                        {
                                            desc: '',
                                        }
                                    ],
                                    icds: [
                                        {
                                            code: '',
                                            desc: '',
                                        }
                                    ]
                                }
                            ]
                        }
                    },
                    currentPrescription_IMAGING: {
                        noteUid: '{{ @$note ? $note->uid : '' }}',
                        clientUid: '{{ $patient->uid }}',
                        replacesCancelledErxUid: null, // TODO: step-2 support UI to mark a new one as replacing a cancelled one
                        hcpProUid: '{{$pro->uid}}',
                        erxCategory: 'IMAGING',
                        clinicalDetailJson: {
                            items: [
                                {
                                    tests: [
                                        {
                                            desc: '',
                                        }
                                    ],
                                    icds: [
                                        {
                                            code: '',
                                            desc: '',
                                        }
                                    ]
                                }
                            ]
                        }
                    },
                    newPrescription_IMAGING: {
                        noteUid: '{{ @$note ? $note->uid : '' }}',
                        clientUid: '{{ $patient->uid }}',
                        replacesCancelledErxUid: null, // TODO: step-2 support UI to mark a new one as replacing a cancelled one
                        hcpProUid: '{{$pro->uid}}',
                        erxCategory: 'IMAGING',
                        clinicalDetailJson: {
                            items: [
                                {
                                    tests: [
                                        {
                                            desc: '',
                                        }
                                    ],
                                    icds: [
                                        {
                                            code: '',
                                            desc: '',
                                        }
                                    ]
                                }
                            ]
                        }
                    },
                    currentPrescription_REFERRAL: {
                        noteUid: '{{ @$note ? $note->uid : '' }}',
                        clientUid: '{{ $patient->uid }}',
                        replacesCancelledErxUid: null, // TODO: step-2 support UI to mark a new one as replacing a cancelled one
                        hcpProUid: '{{$pro->uid}}',
                        erxCategory: 'REFERRAL',
                        clinicalDetailJson: {
                            to: '',
                            memo: '',
                        }
                    },
                    newPrescription_REFERRAL: {
                        noteUid: '{{ @$note ? $note->uid : '' }}',
                        clientUid: '{{ $patient->uid }}',
                        replacesCancelledErxUid: null, // TODO: step-2 support UI to mark a new one as replacing a cancelled one
                        hcpProUid: '{{$pro->uid}}',
                        erxCategory: 'REFERRAL',
                        clinicalDetailJson: {
                            to: '',
                            memo: '',
                        }
                    },
                    currentPrescription_OTHER: {
                        noteUid: '{{ @$note ? $note->uid : '' }}',
                        clientUid: '{{ $patient->uid }}',
                        replacesCancelledErxUid: null, // TODO: step-2 support UI to mark a new one as replacing a cancelled one
                        hcpProUid: '{{$pro->uid}}',
                        erxCategory: 'OTHER',
                        clinicalDetailJson: {
                            title: '',
                            memo: '',
                        }
                    },
                    newPrescription_OTHER: {
                        noteUid: '{{ @$note ? $note->uid : '' }}',
                        clientUid: '{{ $patient->uid }}',
                        replacesCancelledErxUid: null, // TODO: step-2 support UI to mark a new one as replacing a cancelled one
                        hcpProUid: '{{$pro->uid}}',
                        erxCategory: 'OTHER',
                        clinicalDetailJson: {
                            title: '',
                            memo: '',
                        }
                    },

                    // for editing logistics - common
                    currentPrescriptionLogistics: {
                        uid: '',
                        logisticsDetailJson: DEFAULTLOGISTICSDETAILS
                    },

                    newPrescriptionLogistics: {
                        uid: '',
                        logisticsDetailJson: DEFAULTLOGISTICSDETAILS
                    },

                    // for editing hcp, sign, pro status & client status - common
                    currentPrescriptionHcpPro: {
                        uid: '',
                        newHcpProUid: '',
                    },
                    currentPrescriptionSign: {
                        uid: '',
                        declaredVersionNumber: '',
                    },
                    currentPrescriptionProStatus: {
                        uid: '',
                        status: '',
                        memo: '',
                    },
                    currentPrescriptionClientStatus: {
                        uid: '',
                        status: '',
                        memo: '',
                    },
                    currentPrescriptionTransmit: {
                        uid: '',
                        logistics: '',
                        toWho: '',
                        toEmail: '',
                        toFaxNumber: '',
                        toFaxNumberAttentionLine: '',
                        toFaxNumberCoverSheetMemo: '',
                        copyToPatient: false,
                        copyToPatientFaxNumber: '',
                        copyToPatientEmail: '',
                    }
                },
                methods: {

                    cancelItem: function() {
                        let payload = {
                            uid: this.currentPrescription.uid,
                            status: 'CANCELLED',
                            memo: 'Cancelled',
                        };
                        $.post('/api/erx/updateProDeclaredStatus', payload, _data => {
                            if(!hasResponseError(_data)) {
                                localStorage['currentErx_{{$note->id}}'] = 0;
                                closeStagPopup();
                                fastReload();
                            }
                        }, 'json');
                    },

                    newERx: function(_type) {
                        if(!!this.numUnsigned[_type]) {
                            toastr.error('There is already an unsigned ERx of type ' + _type + ' in this note.');
                            return false;
                        }
                        if(_type === 'DRUG') {
                            let payload = {
                                noteUid: '{{ @$note ? $note->uid : '' }}',
                                clientUid: '{{$patient->uid}}',
                                hcpProUid: '{{@$note && $note->hcpPro ? $note->hcpPro->uid : ($patient->mcp ? $patient->mcp->uid : '')}}',
                                erxCategory: _type
                            };
                            $.post('/api/erx/create', payload, _data => {
                                if(!hasResponseError(_data)) {
                                    localStorage.autoOpenNewestPrescription = 1;
                                    localStorage['currentErx_{{$note->id}}'] = 0;
                                    fastReload();
                                }
                            }, 'json');
                        }
                        else {
                            // show popup for all others
                            switch (_type) {
                                case 'LAB':
                                case 'IMAGING':
                                    this['newPrescription_' + _type] = {
                                        noteUid: '{{ @$note ? $note->uid : '' }}',
                                            clientUid: '{{ $patient->uid }}',
                                            replacesCancelledErxUid: null, // TODO: step-2 support UI to mark a new one as replacing a cancelled one
                                            hcpProUid: '{{$pro->uid}}',
                                            erxCategory: _type,
                                            clinicalDetailJson: {
                                                items: [
                                                    {
                                                        tests: [
                                                            {
                                                                desc: '',
                                                            }
                                                        ],
                                                        icds: [
                                                            {
                                                                code: '',
                                                                desc: '',
                                                            }
                                                        ]
                                                    }
                                                ]
                                            }
                                    };
                                    break;
                                case 'REFERRAL':
                                    this.newPrescription_REFERRAL = {
                                        noteUid: '{{ @$note ? $note->uid : '' }}',
                                        clientUid: '{{ $patient->uid }}',
                                        replacesCancelledErxUid: null, // TODO: step-2 support UI to mark a new one as replacing a cancelled one
                                        hcpProUid: '{{$pro->uid}}',
                                        erxCategory: 'REFERRAL',
                                        clinicalDetailJson: {
                                            to: '',
                                            memo: '',
                                        }
                                    };
                                    break;
                                case 'OTHER':
                                    newPrescription_OTHER = {
                                        noteUid: '{{ @$note ? $note->uid : '' }}',
                                        clientUid: '{{ $patient->uid }}',
                                        replacesCancelledErxUid: null, // TODO: step-2 support UI to mark a new one as replacing a cancelled one
                                        hcpProUid: '{{$pro->uid}}',
                                        erxCategory: 'OTHER',
                                        clinicalDetailJson: {
                                            title: '',
                                            memo: '',
                                        }
                                    };
                                    break;
                            }
                            this.newPrescriptionLogistics = {
                                uid: '',
                                logisticsDetailJson: DEFAULTLOGISTICSDETAILS
                            };
                            this.currentPrescriptionType = _type;
                            Vue.nextTick(() => {
                                console.log({n: this.newPrescriptionLogistics, DEFAULTLOGISTICSDETAILS});
                                showStagPopup('new-prescription-popup-' + _type, true);
                                $('[stag-popup-key="new-prescription-popup-' + _type + '"] [stag-suggest-initialized]').removeAttr('stag-suggest-initialized');
                                initStagSuggest();
                                this.initICDAutoSuggest();
                            });
                        }
                        return false;
                    },
                    addTestSet: function(_new = false) {
                        this[(_new ? 'new' : 'current') + 'Prescription_' + this.currentPrescriptionType].clinicalDetailJson.items.push({
                            tests: [
                                {
                                    desc: '',
                                }
                            ],
                            icds: [
                                {
                                    code: '',
                                    desc: '',
                                }
                            ]
                        });
                    },
                    addTest: function(_item) {
                        for (let i = 0; i < _item.tests.length; i++) {
                            if(!_item.tests[i].desc) {
                                toastr.error('One or more existing tests are empty/invalid!');
                                return false;
                            }
                        }
                        _item.tests.push({
                            desc: ''
                        });
                        Vue.nextTick(() => {
                            this.initICDAutoSuggest();
                        });
                    },
                    addICD: function(_item) {
                        for (let i = 0; i < _item.icds.length; i++) {
                            if(!_item.icds[i].code) {
                                toastr.error('One or more existing icds are empty/invalid!');
                                return false;
                            }
                        }
                        _item.icds.push({
                            code: '',
                            desc: ''
                        });
                        Vue.nextTick(() => {
                            this.initICDAutoSuggest();
                        });
                    },
                    deleteTest: function(_item, _index) {
                        _item.tests.splice(_index, 1);
                    },
                    deleteICD: function(_item, _index) {
                        _item.icds.splice(_index, 1);
                    },
                    getBlankPrescriptionClinicalData: function(_type) {
                        let data = null;
                        switch (_type) {
                            case 'DRUG':
                                data = {
                                    items: [
                                        {
                                            medication: '',
                                            dispense: '',
                                            refills: '',
                                            purpose: ''
                                        }
                                    ]
                                };
                                break;
                            case 'LAB':
                            case 'IMAGING':
                                data = {
                                    items: [
                                        {
                                            tests: [
                                                {
                                                    desc: '',
                                                }
                                            ],
                                            icds: [
                                                {
                                                    code: '',
                                                    desc: '',
                                                }
                                            ]
                                        }
                                    ]
                                };
                                break;
                            case 'REFERRAL':
                                data = {
                                    to: '',
                                    memo: '',
                                };
                                break;
                            case 'OTHER':
                                data = {
                                    title: '',
                                    memo: '',
                                };
                                break;
                        }
                        return data;
                    },

                    // new/edit/save-clinical
                    newPrescription: function(_type) {
                        this.currentPrescriptionAction = 'ADD';
                        this.currentPrescriptionType = _type;
                        switch (_type) {
                            case 'DRUG':
                                this.currentPrescription_DRUG = {
                                    noteUid: '{{ @$note ? $note->uid : '' }}',
                                    clientUid: '{{ $patient->uid }}',
                                    replacesCancelledErxUid: null, // TODO: step-2 support UI to mark a new one as replacing a cancelled one
                                    hcpProUid: '{{$pro->uid}}',
                                    erxCategory: _type,
                                    clinicalDetailJson: {
                                        items: [
                                            {
                                                medication: '',
                                                dispense: '',
                                                refills: '',
                                                purpose: ''
                                            }
                                        ]
                                    }
                                };
                                break;
                            case 'LAB':
                                this.currentPrescription_LAB = {
                                    noteUid: '{{ @$note ? $note->uid : '' }}',
                                    clientUid: '{{ $patient->uid }}',
                                    replacesCancelledErxUid: null, // TODO: step-2 support UI to mark a new one as replacing a cancelled one
                                    hcpProUid: '{{$pro->uid}}',
                                    erxCategory: _type,
                                    clinicalDetailJson: {
                                        items: [
                                            {
                                                tests: [
                                                    {
                                                        desc: '',
                                                    }
                                                ],
                                                icds: [
                                                    {
                                                        code: '',
                                                        desc: '',
                                                    }
                                                ]
                                            }
                                        ]
                                    }
                                };
                                break;
                            case 'IMAGING':
                                this.currentPrescription_IMAGING = {
                                    noteUid: '{{ @$note ? $note->uid : '' }}',
                                    clientUid: '{{ $patient->uid }}',
                                    replacesCancelledErxUid: null, // TODO: step-2 support UI to mark a new one as replacing a cancelled one
                                    hcpProUid: '{{$pro->uid}}',
                                    erxCategory: _type,
                                    clinicalDetailJson: {
                                        items: [
                                            {
                                                tests: [
                                                    {
                                                        desc: '',
                                                    }
                                                ],
                                                icds: [
                                                    {
                                                        code: '',
                                                        desc: '',
                                                    }
                                                ]
                                            }
                                        ]
                                    }
                                };
                                break;
                            case 'REFERRAL':
                                this.currentPrescription_REFERRAL = {
                                    noteUid: '{{ @$note ? $note->uid : '' }}',
                                    clientUid: '{{ $patient->uid }}',
                                    replacesCancelledErxUid: null, // TODO: step-2 support UI to mark a new one as replacing a cancelled one
                                    hcpProUid: '{{$pro->uid}}',
                                    erxCategory: _type,
                                    clinicalDetailJson: {
                                        to: '',
                                        memo: '',
                                    }
                                };
                                break;
                            case 'OTHER':
                                this.currentPrescription_OTHER = {
                                    noteUid: '{{ @$note ? $note->uid : '' }}',
                                    clientUid: '{{ $patient->uid }}',
                                    replacesCancelledErxUid: null, // TODO: step-2 support UI to mark a new one as replacing a cancelled one
                                    hcpProUid: '{{$pro->uid}}',
                                    erxCategory: _type,
                                    clinicalDetailJson: {
                                        title: '',
                                        memo: '',
                                    }
                                };
                                break;
                        }
                        Vue.nextTick(() => {
                            showStagPopup('prescription-popup-' + this.currentPrescriptionType, true);
                            if(_type === 'DRUG') {
                                $('[stag-suggest][stag-suggest-initialized]').removeAttr('stag-suggest-initialized');
                                initStagSuggest();
                                this.initFdbMedSuggest();
                            }
                        });
                    },
                    editClinicalDetails: function(_prescription) {
                        this.currentPrescriptionAction = 'EDIT_CLINICAL';
                        this.currentPrescriptionType = _prescription.erx_category;
                        this['currentPrescription_' + this.currentPrescriptionType] = {
                            uid: _prescription.uid,
                            clinicalDetailJson: _prescription.clinical_detail_json ?
                                JSON.parse(JSON.stringify(_prescription.clinical_detail_json)) :
                                this.getBlankPrescriptionClinicalData(this.currentPrescriptionType)
                        };
                        Vue.nextTick(() => {
                            showStagPopup('prescription-popup-' + this.currentPrescriptionType, true);
                            if(this.currentPrescriptionType === 'DRUG') {
                                $('[stag-suggest][stag-suggest-initialized]').removeAttr('stag-suggest-initialized');
                                initStagSuggest();
                                this.initFdbMedSuggest();

                                // re-populate drug fields
                                /*console.log(this.currentPrescription_DRUG);
                                let parentSegment = $('#prescriptions-{{$patient->id}} [stag-popup-key="prescription-popup-DRUG"]>form').first();
                                parentSegment.find('input.prescription-medication').val(this.currentPrescription_DRUG.clinicalDetailJson.medication);
                                parentSegment.find('select.prescription-route')
                                    .empty()
                                    .append($('<option/>').attr('value', 1).text(this.currentPrescription_DRUG.clinicalDetailJson.route))
                                    .val(1);
                                parentSegment.find('select.prescription-dose')
                                    .empty()
                                    .append($('<option/>').attr('value', 1).text(this.currentPrescription_DRUG.clinicalDetailJson.dose))
                                    .val(1);
                                parentSegment.find('select.prescription-strength')
                                    .empty()
                                    .append($('<option/>').attr('value', 1).text(this.currentPrescription_DRUG.clinicalDetailJson.strength))
                                    .val(1);*/
                            }
                            else if(this.currentPrescriptionType === 'LAB' || this.currentPrescriptionType === 'IMAGING') {
                                this.initICDAutoSuggest();
                            }
                        });
                    },
                    savePrescription: function() {
                        let payload = JSON.parse(JSON.stringify(this['currentPrescription_' + this.currentPrescriptionType]));
                        payload.clinicalDetailJson = JSON.stringify(payload.clinicalDetailJson);
                        switch (this.currentPrescriptionAction) {
                            case 'ADD':
                                $.post('/api/erx/create', payload, _data => {
                                    if(!hasResponseError(_data)) {
                                        toastr.success('Prescription added');
                                        closeStagPopup();
                                        fastReload();
                                    }
                                }, 'json');
                                break;
                            case 'EDIT_CLINICAL':
                                $.post('/api/erx/updateClinicalDetail', payload, _data => {
                                    if(!hasResponseError(_data)) {
                                        toastr.success('Prescription updated');
                                        closeStagPopup();
                                        fastReload();
                                    }
                                }, 'json');
                                break;
                        }
                    },

                    saveNewPrescription: function() {
                        let payload = JSON.parse(JSON.stringify(this['newPrescription_' + this.currentPrescriptionType]));
                        payload.clinicalDetailJson = JSON.stringify(payload.clinicalDetailJson);
                        payload.logisticsDetailJson = JSON.stringify(this.newPrescriptionLogistics.logisticsDetailJson);
                        $.post('/api/erx/create', payload, _data => {
                            if(!hasResponseError(_data)) {
                                toastr.success('Prescription added');
                                localStorage.autoOpenNewestPrescription = 1;
                                localStorage['currentErx_{{$note->id}}'] = 0;
                                closeStagPopup();
                                fastReload();
                            }
                        }, 'json');
                    },

                    // edit logistics
                    editLogisticsDetails: function(_prescription) {
                        this.currentPrescriptionAction = 'EDIT_LOGISTICS';
                        this.currentPrescriptionLogistics = {
                            uid: _prescription.uid,
                            logisticsDetailJson: _prescription.logistics_detail_json ? JSON.parse(JSON.stringify(_prescription.logistics_detail_json)) : DEFAULTLOGISTICSDETAILS
                        }
                        Vue.nextTick(() => {
                            showStagPopup('logistics-popup', true);
                            $('[stag-popup-key="logistics-popup"] [stag-suggest-initialized]').removeAttr('stag-suggest-initialized');
                            initStagSuggest();
                        });
                    },
                    saveLogistics: function() {
                        let payload = JSON.parse(JSON.stringify(this.currentPrescriptionLogistics));
                        payload.logisticsDetailJson = JSON.stringify(payload.logisticsDetailJson);
                        $.post('/api/erx/updateLogisticsDetail', payload, _data => {
                            if(!hasResponseError(_data)) {
                                toastr.success('Logistics updated');
                                closeStagPopup();
                                fastReload();
                            }
                        }, 'json');
                    },

                    // edit hcp (ordering) pro
                    editHcpPro: function(_prescription) {
                        this.currentPrescriptionAction = 'EDIT_HCP_PRO';
                        this.currentPrescriptionType = _prescription.erx_category;
                        this.currentPrescriptionHcpPro = {
                            uid: _prescription.uid,
                            newHcpProUid: _prescription.hcpProUid
                        };
                        Vue.nextTick(() => {
                            showStagPopup('hcp-pro-popup', true);
                            $('.erx-hcp-pro-select').removeAttr('pro-suggest-initialized');
                            initProSuggest();
                        });
                    },
                    saveHcpPro: function() {
                        let payload = JSON.parse(JSON.stringify(this.currentPrescriptionHcpPro));
                        $.post('/api/erx/updateHcpPro', payload, _data => {
                            if(!hasResponseError(_data)) {
                                toastr.success('HCP Pro updated');
                                closeStagPopup();
                                fastReload();
                            }
                        }, 'json');
                    },

                    // sign
                    signAsHcpPro: function(_prescription) {
                        this.currentPrescriptionAction = 'SIGN_AS_HCP';
                        this.currentPrescriptionType = _prescription.erx_category;
                        this.currentPrescriptionSign = {
                            uid: _prescription.uid,
                            declaredVersionNumber: _prescription.version_number
                        };
                        Vue.nextTick(() => {
                            showStagPopup('sign-as-hcp-popup', true);
                        });
                    },
                    saveSignAsHcpPro: function() {
                        let payload = JSON.parse(JSON.stringify(this.currentPrescriptionSign));
                        $.post('/api/erx/signAsHcp', payload, _data => {
                            if(!hasResponseError(_data)) {
                                toastr.success('Signed');
                                closeStagPopup();
                                fastReload();
                            }
                        }, 'json');
                    },

                    // edit pro status
                    editProStatus: function(_prescription) {
                        this.currentPrescriptionAction = 'EDIT_PRO_DECLARED_STATUS';
                        this.currentPrescriptionType = _prescription.erx_category;
                        this.currentPrescriptionProStatus = {
                            uid: _prescription.uid,
                            status: _prescription.pro_declared_status,
                            memo: _prescription.pro_declared_status_memo,
                        };
                        Vue.nextTick(() => {
                            showStagPopup('pro-status-popup', true);
                        });
                    },
                    saveProStatus: function() {
                        let payload = JSON.parse(JSON.stringify(this.currentPrescriptionProStatus));
                        $.post('/api/erx/updateProDeclaredStatus', payload, _data => {
                            if(!hasResponseError(_data)) {
                                toastr.success('Pro declared status updated');
                                closeStagPopup();
                                fastReload();
                            }
                        }, 'json');
                    },

                    // edit client status
                    editClientStatus: function(_prescription) {
                        this.currentPrescriptionAction = 'EDIT_CLIENT_DECLARED_STATUS';
                        this.currentPrescriptionType = _prescription.erx_category;
                        this.currentPrescriptionClientStatus = {
                            uid: _prescription.uid,
                            status: _prescription.client_declared_status,
                            memo: _prescription.client_declared_status_memo,
                        };
                        Vue.nextTick(() => {
                            showStagPopup('client-status-popup', true);
                        });
                    },
                    saveClientStatus: function() {
                        let payload = JSON.parse(JSON.stringify(this.currentPrescriptionClientStatus));
                        $.post('/api/erx/updateClientDeclaredStatus', payload, _data => {
                            if(!hasResponseError(_data)) {
                                toastr.success('Client declared status updated');
                                closeStagPopup();
                                fastReload();
                            }
                        }, 'json');
                    },

                    // sane display status
                    sanitizeStatus: function(_s) {
                        if(!_s) return '-';
                        _s = _s.toLowerCase().replaceAll('_', ' ');
                        _s = _s[0].toUpperCase() + _s.substr(1);
                        return _s;
                    },

                    // transmit
                    transmit: function(_prescription) {
                        this.currentPrescriptionTransmit = {
                            uid: _prescription.uid,
                            toWho: _prescription.logistics_detail_json ? _prescription.logistics_detail_json.facilityName : '',
                            toEmail: '',
                            toFaxNumber: _prescription.logistics_detail_json ? _prescription.logistics_detail_json.facilityFax : '',
                            toFaxNumberAttentionLine: '',
                            toFaxNumberCoverSheetMemo: '',
                            copyToPatient: false,
                            copyToPatientFaxNumber: '{{$patient->cell_number}}',
                            copyToPatientEmail: '{{$patient->email_address}}',
                            _token: '{{csrf_token()}}'
                        };
                        Vue.nextTick(() => {
                            showStagPopup('transmit-popup');
                            this.transmitModalPDFPreview();
                        });
                    },
                    transmitModalPDFPreview: function() {

                        let _loadedPDF = null, _numPages = 1, _page = 1;

                        function _load(_url) {

                            _loadedPDF = null;
                            _numPages = 1;
                            _page = 1;

                            $('#transmit-pdf-preview>canvas').remove();

                            let url = _url;
                            let pdfjsLib = window['pdfjs-dist/build/pdf'];
                            pdfjsLib.GlobalWorkerOptions.workerSrc = '/js/pdfjs-2.12.313/build/pdf.worker.js';
                            let loadingTask = pdfjsLib.getDocument(url);
                            loadingTask.promise.then(function (pdf) {
                                _numPages = pdf.numPages;
                                _loadedPDF = pdf;
                                _page = 1;
                                _render();
                            }, function (reason) {
                                // reason.message;
                            });
                        }
                        function _render() {

                            _loadedPDF.getPage(_page).then(function (page) {

                                // create canvas
                                let canvasElement = $('<canvas/>')
                                    .addClass('pdf-viewer-page pdf-preview-page')
                                    .appendTo('#transmit-pdf-preview');

                                let canvas = canvasElement[0];
                                let viewport = page.getViewport({scale: 0.75});
                                let context = canvas.getContext('2d');
                                canvas.height = viewport.height;
                                canvas.width = viewport.width;
                                const $canvas = $(canvas);
                                let renderContext = {
                                    canvasContext: context,
                                    viewport: viewport
                                };
                                let renderTask = page.render(renderContext);
                                renderTask.promise.then(function () {
                                    if(_page < _numPages) {
                                        _page++;
                                        _render();
                                    }
                                });
                            });
                        }

                        _load('/prescription-download-as-pdf/' + this.currentPrescriptionTransmit.uid);
                    },
                    doTransmit: function (_item) {
                        let payload = JSON.parse(JSON.stringify(this.currentPrescriptionTransmit));
                        $.post('/prescription-transmit/' + payload.uid, payload, _data => {
                            if(!hasResponseError(_data)) {
                                toastr.success('Transmission initiated');
                                closeStagPopup();
                                fastReload();
                            }
                        }, 'json');
                        closeStagPopup();
                    },

                    // cancel, etc.

                    initFdbMedSuggest: function() {

                        let self = this;

                        let parentSegment = $('#prescriptions-{{$patient->id}} [stag-popup-key="prescription-popup-DRUG"]>form').first();

                        parentSegment.find('input.prescription-medication').off('stag-suggest-selected');
                        parentSegment.find('input.prescription-medication').on('stag-suggest-selected', (_e, _input, _data) => {

                            // _input is the textbox
                            // _data is {med_name_id: "50567", text: "Children's Tylenol"}

                            // set vue values
                            //self.currentPrescription_DRUG.clinicalDetailJson.medication = _data.text;

                        });
                    },
                    notAlreadyAdded: function(_name) {
                        if(!this.currentPrescription ||
                            !this.currentPrescription.clinical_detail_json ||
                            !this.currentPrescription.clinical_detail_json.items) return true;
                        for (let i = 0; i < this.currentPrescription.clinical_detail_json.items.length; i++) {
                            if(this.currentPrescription.clinical_detail_json.items[i].medication === _name) {
                                return false;
                            }
                        }
                        return true;
                    },
                    addExistingDrugToERx: function(_uid) {
                        let existing = this.existingDrugs.filter(_x => {
                            return _x.uid === _uid;
                        });
                        if(!existing || !existing.length) return false;
                        existing = existing[0];

                        // require dispense and refills
                        if(!existing.data.dispense) {
                            toastr.error('Dispense cannot be blank');
                            return false;
                        }
                        if(!existing.data.refills) {
                            toastr.error('Refills cannot be blank');
                            return false;
                        }

                        if(!this.currentPrescription.clinical_detail_json) {
                            this.currentPrescription.clinical_detail_json = {};
                        }
                        if(!this.currentPrescription.clinical_detail_json.items) {
                            this.currentPrescription.clinical_detail_json.items = [];
                        }
                        this.currentPrescription.clinical_detail_json.items.push({
                            medication: existing.data.name,
                            dispense: existing.data.dispense,
                            refills: existing.data.refills,
                            instructions: existing.data.instructions,
                        });
                        this.currentPrescription.clinical_detail_json.items = JSON.parse(JSON.stringify(this.currentPrescription.clinical_detail_json.items));
                        let temp = this.currentPrescription;
                        this.currentPrescription = null;
                        this.currentPrescription = temp;
                        this.setCurrentPrescription(temp);

                        showMask();

                        // save erx
                        $.post('/api/erx/updateClinicalDetail', {
                            uid: this.currentPrescription.uid,
                            clinicalDetailJson: JSON.stringify(this.currentPrescription.clinical_detail_json)
                        }, _data => {
                            if(!hasResponseError(_data)) {
                                // nothing to do
                                // fastReload();
                                hideMask();
                            }
                        }, 'json');
                    },
                    removeDrugFromERx: function(_name) {
                        this.currentPrescription.clinical_detail_json.items = this.currentPrescription.clinical_detail_json.items.filter(_x => {
                            return _x.medication !== _name;
                        });
                        let temp = this.currentPrescription;
                        this.currentPrescription = null;
                        this.currentPrescription = temp;

                        showMask();

                        // save erx
                        $.post('/api/erx/updateClinicalDetail', {
                            uid: this.currentPrescription.uid,
                            clinicalDetailJson: JSON.stringify(this.currentPrescription.clinical_detail_json)
                        }, _data => {
                            if(!hasResponseError(_data)) {
                                // nothing to do
                                // fastReload();
                                hideMask();
                            }
                        }, 'json');
                    },
                    setCurrentPrescription: function(_prescription, _addMode = false) {
                        this.currentPrescription = _prescription;
                        if(_addMode !== false) {
                            this.setAddMode(_addMode);
                        }

                        @if(@$note)
                        localStorage['currentErx_{{$note->id}}'] = _prescription ? _prescription.id : -1;
                        @endif
                    },
                    setAddMode: function(_mode) {
                        let self = this;
                        this.addDrugToErxMode = _mode;
                        if(this.addDrugToErxMode === 'new') {
                            Vue.nextTick(() => {

                                let parentSegment = $('#prescriptions-{{$patient->id}}');

                                parentSegment.find('[stag-suggest-initialized]').removeAttr('stag-suggest-initialized');
                                initStagSuggest();

                                parentSegment.find('input[stag-suggest][data-name="name"]')
                                    .off('stag-suggest-selected')
                                    .on('stag-suggest-selected', (_e, _input, _data) => {
                                        $(_input).closest('form').find('input[data-name="routedMedId"]').val(_data.routed_med_id);
                                        $(_input).closest('form').find('input[data-name="routedDosageFormMedId"]').val(_data.routed_dosage_form_med_id);
                                        $(_input).closest('form').find('input[data-name="gcnSeqno"]').val(_data.gcn_seqno);
                                        $(_input).closest('form').find('input[data-name="medId"]').val(_data.medid);
                                        return false;
                                    });

                                // bind events for add-new-med and add-to-erx in one shot
                                parentSegment.find('#frm-add-medication-and-add-to-erx')
                                    .off('submit')
                                    .on('submit', function () {

                                        let form = $(this);

                                        if (!form[0].checkValidity()) {
                                            form[0].reportValidity();
                                            return false;
                                        }

                                        // add [data-name] values to payload
                                        let dataField = form.find('[name="data"]').first();
                                        let parsed = null;
                                        if (dataField.val()) {
                                            parsed = JSON.parse(dataField.val());
                                        }
                                        form.find('[data-name]').each(function () {
                                            if (!parsed) parsed = {};

                                            let keys = $(this).attr('data-name').split('->');
                                            let currentNode = parsed;
                                            for (let i = 0; i < keys.length; i++) {
                                                if (i !== keys.length - 1) {
                                                    if (typeof currentNode[keys[i]] === 'undefined') {
                                                        currentNode[keys[i]] = {};
                                                    }
                                                    currentNode = currentNode[keys[i]];
                                                } else {
                                                    if ($(this).is(':checkbox')) {
                                                        currentNode[keys[i]] = $(this).prop('checked');
                                                    } else {
                                                        currentNode[keys[i]] = $(this).val();
                                                    }
                                                }
                                            }

                                        });
                                        if (parsed) {
                                            dataField.val(JSON.stringify(parsed));
                                        }

                                        let newERxItem = {
                                            medication: form.find('[data-name="name"]').val(),
                                            instructions: form.find('[data-name="instructions"]').val(),
                                            dispense: form.find('[name="dispense"]').val(),
                                            refills: form.find('[name="refills"]').val(),
                                        };

                                        showMask();

                                        $.post(form.attr('action'), form.serialize(), _data => {
                                            if (!hasResponseError(_data)) {

                                                if(!self.currentPrescription.clinical_detail_json) {
                                                    self.currentPrescription.clinical_detail_json = {};
                                                }
                                                if(!self.currentPrescription.clinical_detail_json.items) {
                                                    self.currentPrescription.clinical_detail_json.items = [];
                                                }
                                                self.currentPrescription.clinical_detail_json.items.push(newERxItem);
                                                self.currentPrescription.clinical_detail_json.items = JSON.parse(JSON.stringify(self.currentPrescription.clinical_detail_json.items));
                                                let temp = self.currentPrescription;
                                                self.currentPrescription = null;
                                                self.currentPrescription = temp;
                                                self.setCurrentPrescription(temp);

                                                // save erx
                                                $.post('/api/erx/updateClinicalDetail', {
                                                    uid: self.currentPrescription.uid,
                                                    clinicalDetailJson: JSON.stringify(self.currentPrescription.clinical_detail_json)
                                                }, _data => {
                                                    if(!hasResponseError(_data)) {
                                                        // nothing to do
                                                        // fastReload();
                                                        hideMask();
                                                        form[0].reset();
                                                    }
                                                }, 'json');

                                            }
                                        }, 'json');
                                        return false;
                                    });

                            });
                        }
                    },
                    initICDAutoSuggest: function() {
                        let self = this;
                        let parentSegment = $('#prescriptions-{{$patient->id}}');
                        parentSegment.find('input[type="text"][data-field="icd"]:not([ac-initialized])').each(function() {
                            var elem = this,
                                dynID = 'icd-' + Math.ceil(Math.random() * 1000000),
                                itemIndex = $(this).attr('data-item-index'),
                                icdIndex = $(this).attr('data-icd-index'),
                                category = $(this).attr('data-category'),
                                existing = $(this).closest('[stag-popup-key]').length === 0;
                            $(elem).attr('id', dynID);
                            new window.Def.Autocompleter.Search(dynID,
                                'https://clinicaltables.nlm.nih.gov/api/icd10cm/v3/search?sf=code,name&ef=name', {
                                    tableFormat: true,
                                    valueCols: [0],
                                    colHeaders: ['Code', 'Name'],
                                }
                            );
                            window.Def.Autocompleter.Event.observeListSelections(dynID, function() {
                                let autocomp = elem.autocomp, acData = autocomp.getSelectedItemData();
                                if(existing) {
                                    self['currentPrescription_' + category].clinicalDetailJson.items[itemIndex].icds[icdIndex].code = acData[0].code;
                                    self['currentPrescription_' + category].clinicalDetailJson.items[itemIndex].icds[icdIndex].desc = acData[0].data['name'];
                                }
                                else {
                                    self['newPrescription_' + category].clinicalDetailJson.items[itemIndex].icds[icdIndex].code = acData[0].code;
                                    self['newPrescription_' + category].clinicalDetailJson.items[itemIndex].icds[icdIndex].desc = acData[0].data['name'];
                                }
                                return false;
                            });
                            $(elem).attr('ac-initialized', 1);
                        });
                    },
                },
                mounted: function() {
                    let self = this;
                    $(document).on('pro-changed', '.erx-hcp-pro-select', function() {
                        self.currentPrescriptionHcpPro.newHcpProUid = this.value;
                    });

                    // auto select latest prescription (if no current is set)
                    Vue.nextTick(() => {
                        if(+localStorage.autoOpenNewestPrescription) {
                            if(!this.currentPrescription) {
                                for(let x in this.prescriptions) {
                                    this.currentPrescription = this.prescriptions[x];
                                    break;
                                }
                            }
                            localStorage.autoOpenNewestPrescription = 0;
                        }
                    });

                    @if(@$note)
                    if(!!localStorage['currentErx_{{$note->id}}']) {
                        for(let x in this.prescriptions) {
                            if(this.prescriptions[x].id === +(localStorage['currentErx_{{$note->id}}'])) {
                                this.currentPrescription = this.prescriptions[x];
                                break;
                            }
                        }
                    }
                    @endif

                    $('[stag-popup-key="logistics-popup"] .facility-search').off('stag-suggest-selected');
                    $('[stag-popup-key="logistics-popup"] .facility-search').on('stag-suggest-selected', (_e, _input, _data) => {
                        if(self.currentPrescriptionLogistics && self.currentPrescriptionLogistics.logisticsDetailJson) {
                            self.currentPrescriptionLogistics.logisticsDetailJson.facilityName = _data.name;
                            self.currentPrescriptionLogistics.logisticsDetailJson.facilityCity = _data.city;
                            self.currentPrescriptionLogistics.logisticsDetailJson.facilityState = _data.state;
                            self.currentPrescriptionLogistics.logisticsDetailJson.facilityZip = _data.zip;
                            self.currentPrescriptionLogistics.logisticsDetailJson.facilityPhone = _data.phone;
                            self.currentPrescriptionLogistics.logisticsDetailJson.facilityFax = _data.fax;
                        }
                    });

                    $('[stag-popup-key="new-prescription-popup-LAB"] .facility-search').off('stag-suggest-selected');
                    $('[stag-popup-key="new-prescription-popup-LAB"] .facility-search').on('stag-suggest-selected', (_e, _input, _data) => {
                        if(self.newPrescriptionLogistics && self.newPrescriptionLogistics.logisticsDetailJson) {
                            self.newPrescriptionLogistics.logisticsDetailJson.facilityName = _data.name;
                            self.newPrescriptionLogistics.logisticsDetailJson.facilityCity = _data.city;
                            self.newPrescriptionLogistics.logisticsDetailJson.facilityState = _data.state;
                            self.newPrescriptionLogistics.logisticsDetailJson.facilityZip = _data.zip;
                            self.newPrescriptionLogistics.logisticsDetailJson.facilityPhone = _data.phone;
                            self.newPrescriptionLogistics.logisticsDetailJson.facilityFax = _data.fax;
                        }
                    });

                    $('[stag-popup-key="new-prescription-popup-IMAGING"] .facility-search').off('stag-suggest-selected');
                    $('[stag-popup-key="new-prescription-popup-IMAGING"] .facility-search').on('stag-suggest-selected', (_e, _input, _data) => {
                        if(self.newPrescriptionLogistics && self.newPrescriptionLogistics.logisticsDetailJson) {
                            self.newPrescriptionLogistics.logisticsDetailJson.facilityName = _data.name;
                            self.newPrescriptionLogistics.logisticsDetailJson.facilityCity = _data.city;
                            self.newPrescriptionLogistics.logisticsDetailJson.facilityState = _data.state;
                            self.newPrescriptionLogistics.logisticsDetailJson.facilityZip = _data.zip;
                            self.newPrescriptionLogistics.logisticsDetailJson.facilityPhone = _data.phone;
                            self.newPrescriptionLogistics.logisticsDetailJson.facilityFax = _data.fax;
                        }
                    });
                }
            });

        }
        addMCInitializer('prescriptions-{{$patient->id}}', init, '#prescriptions-{{$patient->id}}')
    }).call(window);
</script>
