<div id="erxApp" v-cloak>
    <div class="d-flex align-items-center pb-2">
        <h4 class="font-weight-bold m-0 font-size-14"><i class="fa fa-prescription mr-2"></i>ERx</h4>
        <span class="mx-2 text-secondary">|</span>
        <a class="py-0 font-weight-normal c-pointer" v-on:click.prevent="showPopup('erx-popup')">Add</a>
        <select class="ml-auto max-width-300px form-control form-control-sm"
                onchange="fastLoad('/patients/view/{{$patient->uid}}/action-items-erx/' + this.value, true, false, false)">
            <option value="open" {{ $filter === 'open' ? 'selected' : '' }}>Open tickets</option>
            <option value="closed" {{ $filter === 'closed' ? 'selected' : '' }}>Closed tickets</option>
            <option value="all" {{ $filter === 'all' ? 'selected' : '' }}>All tickets</option>
        </select>
    </div>
    <table class="table table-sm table-bordered mb-0">
        <thead>
        <tr class="bg-light">
            <th class="px-2 text-secondary border-bottom-0 width-30px">#</th>
            <th class="px-2 text-secondary border-bottom-0">Medication</th>
            <th class="px-2 text-secondary border-bottom-0 width-200px">Pharmacy</th>
            <th class="px-2 text-secondary border-bottom-0 width-200px">Collaboration</th>
        </tr>
        </thead>
        <tbody>
            <tr v-for="(item, index) in items" :class="item.is_open ? '' : 'opacity-60 bg-light'">
                <td class="px-2">@{{ index + 1 }}</td>
                <td class="px-2">
                    <div class="d-flex align-items-center flex-wrap">
                        <a :href="'/patients/view/{{$patient->uid}}/action-items-erx/view/' + item.uid"
                           class="font-weight-bold font-size-13">@{{item.medication}}</a>
                        <span class="d-inline-flex align-items-center" v-if="item.strength">
                            <span class="mx-2 text-secondary">•</span>
                            <span>@{{item.strength}}</span>
                        </span>
                        <span class="d-inline-flex align-items-center" v-if="item.route">
                            <span class="mx-2 text-secondary">•</span>
                            <span>@{{item.route}}</span>
                        </span>
                        <span class="d-inline-flex align-items-center" v-if="item.frequency">
                            <span class="mx-2 text-secondary">•</span>
                            <span>@{{item.frequency}}</span>
                        </span>
                        <span class="d-inline-flex align-items-center" v-if="item.dispense">
                            <span class="mx-2 text-secondary">•</span>
                            <span>Dispense:</span> @{{item.dispense}}
                            <span class="text-secondary ml-1" v-html="inWords(item.dispense)"></span>
                        </span>
                        <span class="d-inline-flex align-items-center" v-if="item.refills">
                            <span class="mx-2 text-secondary">•</span>
                            <span><span>Refills:</span> @{{item.refills}}</span>
                        </span>
                        <span class="d-inline-flex align-items-center" v-if="item.purpose">
                            <span class="mx-2 text-secondary">•</span>
                            <span><span>Purpose:</span> @{{item.purpose}}</span>
                        </span>
                    </div>
                    <div>
                        <span class="text-secondary text-sm mt-1">Created:</span>
                        @{{ item.created_at }}
                    </div>
                </td>
                <td class="px-2">
                    <span class="" v-html="pharmacy(item)"></span>
                </td>
                @include('app.patient.partials.ticket_vue_collab_column')
                {{--<td class="px-2">
                    <a class="mr-2 c-pointer" v-on:click.prevent="showPopup('erx-popup', item)">Edit</a>
                    <a class="mr-2 c-pointer" v-if="item.is_open" v-on:click.prevent="closeItem(item)">Close</a>
                    <a class="mr-2 c-pointer" v-if="!item.is_open" v-on:click.prevent="openItem(item)">Open</a>

                    @include('app.patient.partials.ticket_action_links')
                </td>--}}
            </tr>
        </tbody>
    </table>
    <div class="stag-popup stag-popup-sm mcp-theme-1" stag-popup-key="erx-popup">
        <form method="POST" action="">
            <h3 class="stag-popup-title mb-2">
                <span>@{{ popupMode === 'add' ? 'Add ERx Item' : 'Edit ERx Item' }}</span>
                <a href="#" class="ml-auto text-secondary"
                   onclick="return closeStagPopup()"><i class="fa fa-times-circle"></i></a>
            </h3>
            <div class="row mb-2">
                <div class="col-6">
                    <label class="text-sm text-secondary mb-1">Medication</label>
                    <input required type="text" data-field="medication"
                           v-model="popupItem.medication" class="form-control form-control-sm">
                </div>
                <div class="col-6">
                    <label class="text-sm text-secondary mb-1">Strength</label>
                    <input type="text" data-field="strength"
                           v-model="popupItem.strength" class="form-control form-control-sm">
                </div>
            </div>
            <div class="row mb-2">
                <div class="col-6">
                    <label class="text-sm text-secondary mb-1">Frequency</label>
                    <input type="text" v-model="popupItem.frequency" class="form-control form-control-sm"
                           data-option-list="frequency-options">
                    <div id="frequency-options" class="data-option-list">
                        <div>Once a day</div>
                        <div>Twice a day</div>
                    </div>
                </div>
                <div class="col-6">
                    <label class="text-sm text-secondary mb-1">Route</label>
                    <input required type="text" v-model="popupItem.route" class="form-control form-control-sm"
                           data-option-list="route-options">
                    <div id="route-options" class="data-option-list">
                        <div>PO (by mouth)</div>
                        <div>PR (per rectum)</div>
                        <div>IM (intramuscular)</div>
                        <div>IV (intravenous)</div>
                        <div>ID (intradermal)</div>
                        <div>IN (intranasal)</div>
                        <div>TP (topical)</div>
                        <div>SL (sublingual)</div>
                        <div>BUCC (buccal)</div>
                        <div>IP (intraperitoneal)</div>
                    </div>
                </div>
            </div>
            <div class="row mb-2">
                <div class="col-6">
                    <label class="text-sm text-secondary mb-1">Dispense Amount</label>
                    <input required type="number" v-model="popupItem.dispense" class="form-control form-control-sm">
                </div>
                <div class="col-6">
                    <label class="text-sm text-secondary mb-1">Refills</label>
                    <input type="number" v-model="popupItem.refills" class="form-control form-control-sm">
                </div>
            </div>
            <div class="row mb-2">
                <div class="col-12">
                    <label class="text-sm text-secondary mb-1">Purpose</label>
                    <input required type="text" data-field="icd" v-model="popupItem.purpose" class="form-control form-control-sm">
                </div>
            </div>
            <hr class="mt-3 mb-2">

            <div class="row mb-2">
                <div class="col-12">
                    <label class="text-sm text-secondary mb-1 font-weight-bold">Preferred Pharmacy</label>
                </div>
            </div>
            <div class="row mb-2">
                <div class="col-12">
                    <label class="text-sm text-secondary mb-1">Business Name</label>
                    <input type="text" autocomplete="donotdoit" id="pharmacy-search" v-model="popupItem.pharmacyName" class="form-control form-control-sm">
                    <div class="suggestions-outer pharmacy-suggestions position-absolute d-none"></div>
                </div>
            </div>
            <div class="row mb-2">
                <div class="col-6">
                    <label class="text-sm text-secondary mb-1">City</label>
                    <input type="text" v-model="popupItem.pharmacyCity" class="form-control form-control-sm">
                </div>
                <div class="col-6">
                    <label class="text-sm text-secondary mb-1">State</label>
                    <input type="text" v-model="popupItem.pharmacyState" class="form-control form-control-sm">
                </div>
            </div>
            <div class="row mb-2">
                <div class="col-12">
                    <label class="text-sm text-secondary mb-1">Address Memo</label>
                    <input type="text" v-model="popupItem.pharmacyAddressMemo" class="form-control form-control-sm">
                </div>
            </div>
            <div class="row mb-2">
                <div class="col-6">
                    <label class="text-sm text-secondary mb-1">Phone</label>
                    <input type="text" v-model="popupItem.pharmacyPhone" class="form-control form-control-sm">
                </div>
                <div class="col-6">
                    <label class="text-sm text-secondary mb-1">Fax</label>
                    <input type="text" v-model="popupItem.pharmacyFax" class="form-control form-control-sm">
                </div>
            </div>

            <div class="d-flex align-items-center justify-content-center mt-3">
                <button type="button" class="btn btn-sm btn-primary mr-2" v-on:click.prevent="savePopupItem()">Submit</button>
                <button type="button" class="btn btn-sm btn-default border" onclick="return closeStagPopup()">Cancel</button>
            </div>
        </form>
    </div>
    @include('app.patient.partials.ticket_update_pro_form',['ticketType'=>'erx'])
</div>
<script>
    (function() {
        <?php
        $tickets = $patient->tickets->filter(function($_item) use ($filter) {
            $match = $_item->category === 'erx';
            if($filter !== 'all') {
                $match = $match && ($filter === 'open' ? $_item->is_open : !$_item->is_open);
            }
            return $match;
        });
        $items = [];
        foreach ($tickets as $ticket) {
            $item = json_decode($ticket->data);
            $item->uid = $ticket->uid;
            $item->is_open = $ticket->is_open;
            $item->assigned_pro_id = $ticket->assigned_pro_id;
            $item->manager_pro_id = $ticket->manager_pro_id;
            $item->ordering_pro_id = $ticket->ordering_pro_id;
            $item->initiating_pro_id = $ticket->initiating_pro_id;
            $item->has_assigned_pro_signed = $ticket->has_assigned_pro_signed;
            $item->has_manager_pro_signed = $ticket->has_manager_pro_signed;
            $item->has_ordering_pro_signed = $ticket->has_ordering_pro_signed;
            $item->has_initiating_pro_signed = $ticket->has_initiating_pro_signed;
            $item->is_entry_error = $ticket->is_entry_error;
            $item->created_at = friendly_date_time($ticket->created_at);
            $items[] = $item;
        }
        ?>
        function init() {
            let items = [];
            let erxApp = new Vue({
                el: '#erxApp',
                delimiters: ['@{{', '}}'],
                data: {
                    popupMode: 'add',
                    items: {!! json_encode($items) !!},
                    popupItem: {
                        uid: '',
                        is_open: true,
                        medication: '',
                        strength: '',
                        amount: '',
                        route: '',
                        frequency: '',
                        dispense: '',
                        refills: '',
                        purpose: '',
                        pharmacyName: '',
                        pharmacyCity: '',
                        pharmacyState: '',
                        pharmacyAddressMemo: '',
                        pharmacyPhone: '',
                        pharmacyFax: '',
                    },
                    @include('app.patient.partials.ticket_vue_data')
                },
                methods: {
                    showPopup: function(_name, _item) {
                        closeStagPopup();
                        this.popupMode = _item ? 'edit' : 'add';
                        this.popupItem = _item ? JSON.parse(JSON.stringify(_item)) : {
                            uid: '',
                            is_open: true,
                            medication: '',
                            strength: '',
                            amount: '',
                            route: '',
                            frequency: '',
                            dispense: '',
                            refills: '',
                            purpose: '',
                            pharmacy: '',
                            pharmacyName: '',
                            pharmacyCity: '',
                            pharmacyState: '',
                            pharmacyAddressMemo: '',
                            pharmacyPhone: '',
                            pharmacyFax: '',
                        };
                        showStagPopup('erx-popup');
                    },
                    savePopupItem: function() {
                        let form = $('#erxApp form').first();
                        if(!form[0].checkValidity()) {
                            form[0].reportValidity();
                            return false;
                        }

                        showMask();
                        let payload = {};
                        if(this.popupMode === 'add') {
                            payload.clientUid = '{{ $patient->uid }}';
                            payload.category = 'erx';
                            payload.assignedProUid = '{{ $pro->uid  }}';
                            payload.managerProUid = '{{ $pro->uid  }}';
                            payload.orderingProUid = '{{ $pro->uid  }}';
                            payload.initiatingProUid = '{{ $pro->uid  }}';
                            payload.data = JSON.stringify(this.popupItem);
                        }
                        else {
                            payload.uid = this.popupItem.uid;
                            payload.newData = JSON.stringify(this.popupItem);
                        }

                        $.post(
                            '/api/ticket/' + (this.popupMode === 'add' ? 'create' : 'updateData'),
                            payload,
                            function(_data) {
                                console.log(_data);
                                fastReload();
                            },
                            'json');

                        return false;
                    },
                    closeItem: function(_item) {
                        showMask();
                        $.post('/api/ticket/close', {
                            uid: _item.uid
                        }, function(_data) {
                            fastReload();
                        });
                    },
                    openItem: function(_item) {
                        showMask();
                        $.post('/api/ticket/open', {
                            uid: _item.uid
                        }, function(_data) {
                            fastReload();
                        });
                    },
                    initRxAutoSuggest: function() {
                        let self = this;
                        $('#erxApp input[type="text"][data-field="medication"]:not([ac-initialized])').each(function() {
                            let elem = this,
                                randPart = Math.ceil(Math.random() * 1000000),
                                dynID = 'rx-' + randPart;
                            $(elem).attr('id', dynID);
                            var strengthElem = $(elem).closest('.stag-popup').find('[data-field="strength"]')[0],
                                dynStrengthsID = 'rx-' + randPart + '-strengths';
                            $(strengthElem).attr('id', dynStrengthsID);
                            $(strengthElem).attr('rx-id', dynID);
                            new window.Def.Autocompleter.Prefetch(dynStrengthsID, []);
                            new window.Def.Autocompleter.Search(dynID,
                                'https://clinicaltables.nlm.nih.gov/api/rxterms/v3/search?ef=STRENGTHS_AND_FORMS');
                            window.Def.Autocompleter.Event.observeListSelections(dynID, function() {
                                var autocomp = elem.autocomp, acData = autocomp.getSelectedItemData();
                                var strengths = acData[0].data['STRENGTHS_AND_FORMS'];
                                if (strengths) {
                                    strengthElem.autocomp.setListAndField(strengths, '');
                                }
                                self.popupItem.medication = $(elem).val();
                            });
                            window.Def.Autocompleter.Event.observeListSelections(dynStrengthsID, function() {
                                var autocomp = elem.autocomp, acData = autocomp.getSelectedItemData();
                                self.popupItem.strength = $(strengthElem).val();
                            });
                            $(elem).attr('ac-initialized', 1);
                            $(strengthElem).attr('ac-initialized', 1);
                        });
                    },
                    initICDAutoSuggest: function() {
                        let self = this;
                        $('#erxApp input[type="text"][data-field="icd"]:not([ac-initialized])').each(function() {
                            var elem = this,
                                dynID = 'icd-' + Math.ceil(Math.random() * 1000000),
                                vueIndex = $(this).attr('data-index');
                            $(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();
                                self.popupItem.purpose = acData[0].code + ' - ' + acData[0].data.name;
                                return false;
                            });
                            $(elem).attr('ac-initialized', 1);
                        });
                    },
                    inWords: function (num) {
                        try {
                            num = +num;
                            var a = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
                            var b = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
                            if ((num = num.toString()).length > 3) return 'overflow';
                            let n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);
                            if (!n) return; var str = '';
                            str += (n[1] != 0) ? (a[Number(n[1])] || b[n[1][0]] + ' ' + a[n[1][1]]) + 'crore ' : '';
                            str += (n[2] != 0) ? (a[Number(n[2])] || b[n[2][0]] + ' ' + a[n[2][1]]) + 'lakh ' : '';
                            str += (n[3] != 0) ? (a[Number(n[3])] || b[n[3][0]] + ' ' + a[n[3][1]]) + 'thousand ' : '';
                            str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';
                            str += (n[5] != 0) ? ((str != '') ? 'and ' : '') + (a[Number(n[5])] || b[n[5][0]] + ' ' + a[n[5][1]]) : '';
                            return str ? '(' + $.trim(str) + ')' : '';
                        }
                        catch (e) {
                            return '';
                        }
                    },
                    pharmacy: function(_item) {
                        return [
                            _item.pharmacyName,
                            _item.pharmacyCity,
                            _item.pharmacyState,
                            _item.pharmacyAddressMemo,
                            _item.pharmacyPhone,
                            _item.pharmacyFax,
                        ].filter(Boolean).join('<br>');
                    },
                    @include('app.patient.partials.pharmacy-suggest')
                    @include('app.patient.partials.ticket_vue_methods',['ticketType'=>'erx'])
                },
                mounted: function () {
                    this.initRxAutoSuggest();
                    this.initICDAutoSuggest();
                    initFastLoad($('#erxApp'));
                    this.initPharmacySearch();
                }
            })
        }
        addMCInitializer('erx', init, '#erxApp');
    })();
</script>
