@extends ('layouts.patient')
<?php
/** @var \App\Models\Client $patient */
?>
@section('inner-content')

    <div class="mb-3">

        <div id="labSingleApp" 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>Lab Ticket
                    <span v-if="!item.is_open" class="text-secondary font-weight-bold opacity-60">(Closed)</span>
                </h4>
                <span class="mx-3 text-secondary">|</span>
                <a class="c-pointer" v-if="item.is_open" v-on:click.prevent="closeItem(item)">Close</a>
                <a class="c-pointer" v-if="!item.is_open" v-on:click.prevent="openItem(item)">Re-open</a>
                <span class="mx-3 text-secondary">|</span>
                <a class="py-0 font-weight-normal c-pointer" v-on:click.prevent="showPopup('lab-popup', item)">Edit</a>
            </div>

            <div class="row mt-2 mb-3">
                <div class="col-6 pr-0">
                    <div class="card bg-light mb-3">
                        <div class="card-body">
                            <div class="d-flex align-items-start flex-nowrap mb-2">
                                <span class="width-100px text-secondary text-sm">Created</span>
                                <span class="font-weight-bold">@{{ item.created_at }}</span>
                            </div>
                            <div class="d-flex align-items-start flex-nowrap mb-2">
                                <span class="width-100px text-secondary text-sm">Tests</span>
                                <span class="font-weight-bold" v-html="item.tests && Array.isArray(item.tests) ? item.tests.join(', ') : '-'"></span>
                            </div>
                            <div class="d-flex align-items-start flex-nowrap mb-2">
                                <span class="width-100px text-secondary text-sm">ICDs</span>
                                <span class="font-weight-bold" v-html="item.icds && Array.isArray(item.icds) ? item.icds.join(', ') : '-'"></span>
                            </div>
                            <div class="d-flex align-items-start flex-nowrap">
                                <span class="width-100px text-secondary text-sm">Memo</span>
                                <span class="font-weight-bold">@{{ item.memo ? item.memo : '-' }}</span>
                            </div>
                        </div>
                    </div>
                    @include('app.patient.partials.ticket_action_links')
                </div>
                <div class="col-6">
                    @include('app.patient.partials.ticket_vue_collab_card')
                </div>
            </div>

            <div class="stag-popup stag-popup-sm mcp-theme-1" stag-popup-key="lab-popup">
                <form method="POST" action="" class="overflow-visible">
                    <h3 class="stag-popup-title mb-2">
                        <span>@{{ popupMode === 'add' ? 'Add Lab Order Item' : 'Edit Lab Order Item' }}</span>
                        <a href="#" class="ml-auto text-secondary"
                           onclick="return closeStagPopup()"><i class="fa fa-times-circle"></i></a>
                    </h3>
                    <div class="mb-2">
                        <div class="d-flex align-items-center mb-1">
                            <label class="text-sm text-secondary mb-0">Tests</label>
                            <span class="text-sm mx-2 text-secondary">|</span>
                            <a href="#" class="text-sm" v-on:click.prevent="popupItem.tests.push('')">Add</a>
                        </div>
                        <div class="d-flex align-items-center mb-2" v-for="(test, testIndex) in popupItem.tests">
                            <div class="position-relative flex-grow-1">
                                <input required type="text" data-option-list v-model="popupItem.tests[testIndex]" class="form-control form-control-sm">
                                <div class="data-option-list">
                                    <div>Complete Blood Count</div>
                                    <div>Prothrombin Time</div>
                                    <div>Basic Metabolic Panel</div>
                                    <div>Comprehensive Metabolic Panel</div>
                                    <div>Lipid Panel</div>
                                    <div>Liver Panel</div>
                                    <div>Thyroid Stimulating Hormone</div>
                                    <div>Hemoglobin A1C</div>
                                    <div>Urinalysis</div>
                                    <div>Cultures</div>
                                </div>
                            </div>
                            <a v-if="popupItem.tests.length > 1" class="ml-2 text-danger" href="#" v-on:click.prevent="popupItem.tests.splice(testIndex, 1)">
                                <i class="fa fa-trash-alt"></i>
                            </a>
                        </div>
                    </div>
                    <div class="mb-2">
                        <div class="d-flex align-items-center mb-1">
                            <label class="text-sm text-secondary mb-0">ICDs</label>
                            <span class="text-sm mx-2 text-secondary">|</span>
                            <a href="#" class="text-sm" v-on:click.prevent="popupItem.icds.push('')">Add</a>
                        </div>
                        <div class="d-flex align-items-center mb-2" v-for="(icd, icdIndex) in popupItem.icds">
                            <div class="position-relative flex-grow-1">
                                <input required type="text" data-field="icd" :data-index="icdIndex"
                                       v-model="popupItem.icds[icdIndex]" class="form-control form-control-sm">
                            </div>
                            <a v-if="popupItem.icds.length > 1" class="ml-2 text-danger" href="#" v-on:click.prevent="popupItem.icds.splice(icdIndex, 1)">
                                <i class="fa fa-trash-alt"></i>
                            </a>
                        </div>
                    </div>
                    <div class="mb-2">
                        <label class="text-sm text-secondary mb-1">Memo</label>
                        <input type="text" v-model="popupItem.memo" class="form-control form-control-sm">
                    </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'=>'lab'])
        </div>
        <script>
            (function() {
                <?php
                $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 labSingleApp = new Vue({
                        el: '#labSingleApp',
                        delimiters: ['@{{', '}}'],
                        data: {
                            popupMode: 'add',
                            item: {!! json_encode($item) !!},
                            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: '',
                                };
                                Vue.nextTick(() => {
                                    showStagPopup('lab-popup');
                                    this.initICDAutoSuggest();
                                });
                            },
                            savePopupItem: function() {
                                let form = $('#labSingleApp form').first();
                                if(!form[0].checkValidity()) {
                                    form[0].reportValidity();
                                    return false;
                                }

                                showMask();
                                let payload = {};
                                if(this.popupMode === 'add') {
                                    payload.clientUid = '{{ $patient->uid }}';
                                    payload.category = 'lab';
                                    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();
                                });
                            },
                            initICDAutoSuggest: function() {
                                let self = this;
                                $('#labSingleApp 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.icds[vueIndex] = acData[0].code;
                                        return false;
                                    });
                                    $(elem).attr('ac-initialized', 1);
                                });
                            },
                            @include('app.patient.partials.ticket_vue_methods',['ticketType'=>'lab'])
                        },
                        mounted: function () {
                            this.initICDAutoSuggest();
                            initFastLoad($('#labSingleApp'));
                        }
                    })
                }
                addMCInitializer('lab-single', init, '#labSingleApp');
            })();
        </script>

    </div>

@endsection
